想要启动service后在线程中输出EditText的内容,但是真机调试报错没有看到输出,求大神帮忙看下是什么问题。下面贴出代码:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.vancool.connectservice.MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/edData"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnStartService"
android:text="启动服务"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnStopService"
android:text="停止服务"/>
MainActivity.java
package com.vancool.connectservice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (EditText) findViewById(R.id.edData);
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnStartService:
Intent i = new Intent(this, MyService.class);
i.putExtra("data", data.getText().toString());
startService(i);
break;
case R.id.btnStopService:
stopService(new Intent(this, MyService.class));
break;
default:
break;
}
}
}
MyService.java
package com.vancool.connectservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
private boolean running = false;
private String data = "默认信息";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
data = intent.getStringExtra("data");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
running = true;
new Thread(){
@Override
public void run() {
super.run();
while(running)
{
System.out.println(data);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
running = false;
}
}