启动Service并传递数据的小实例(通过外界与服务进行通信):
1、activity_main.xml:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="默认信息"
android:id="@+id/etData"/>
<Button
android:text="启动服务"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStartService" />
<Button
android:text="停止服务"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStopService" />
2、MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.etData);
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent i = new Intent(this,MyService.class);
switch(v.getId()){
case R.id.btnStartService:
i.putExtra("data",editText.getText().toString()); //获取默认信息
startService(i);
break;
case R.id.btnStopService:
stopService(i);
break;
}
}
}
3、MyService.java:
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"); //获取Intent里面的数据
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;
}
}