启动Service并传入数据:
在Aty布局中添加“启动服务”按钮监听器调用startService方法
,“停止服务”按钮
监听器调用stopService方法
,id为etData的文本框,在Aty中使用intent向Service传入数据
Intent i=new Intent(this,MyService.class);
i.putExtra("data",etData.getText().toString());
startService(i);
在MyService的onStartCommand函数中通过data=intent.getStringExtra("data")来获取数据
绑定Service进行通信:
添加“绑定”按钮
监听器调用bindService方法
,“
解除绑定”按钮
监听器调用unbindService方法,具体操作同上一节,再添加一个“同步数据”按钮。
在MyService中创建一个
public class Binder extends android.os.Binder{
public void setData(String data){
this.data=data;
}
}
在bind方法中,写入return new Binder();
在Aty中定义一个MyService.Binder类型的变量binder,在onServiceConnected方法中,写入
binder=(MyService.Binder)service;
在同步数据的监听器中,写入
if(binder!=null){
binder.setData(etData.getText().toString());
}
通过方法调用共享数据,更方便直接
主布局再添加一个textView,在程序中获取到它tvOut;MyService中定义一个接口
public static interface Callback{
void onDataChange(String data);
}
private Callback callback=null;
public void setCallback(Callback callback){
this.callback=callback;
}
public Callback getCallback(){
return callback;
}
创建一个线程,run方法中写入for循环,
循环中
String str=i+":"+data;
if(callback!=null){
callback.onDataChange(str);
}
在Binder类中添加
public MyService getService(){
return MyService.this;
}
在Aty中定义一个
private Handler handler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
tvOut.setText(msg.getData().getString("data"));
}
}
onServiceConnected方法加入
binder.getService().setCallback(new MyService.callback(){
public void onDataChange(String data){
Message msg=new Message();
Bundle b=new Bundle();
b.putString("data",data);
msg.setData(b);
handle.sendMessage(msg);
}
});
通过这种方法即可侦听Service中的状态变化