在Android开发之bindService()通信的基础上,实现bindService()方法侦听service内部状态。
实现侦听service内部状态,使用的是回调机制
1.首先实现一个接口
public static interface CallBack{
void onDataChange(String data);
}
2.
private CallBack callBack=null;
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
public CallBack getCallBack() {
return callBack;
}
3.
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
running=true;
new Thread(){
public void run() {
int i=0;
while (running) {
i++;
String str=i+":"+data;
Log.d("learnservice", str);
if (callBack!=null) {
callBack.onDataChange(str);
}
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
}
4.MyBinder提供方法返回BindService实例。
public class MyBinder extends Binder{
public void setData(String data){
MyService.this.data=data;
}
public MyService getService(){
return MyService.this;
}
}
5.
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
binder=(MyBinder) service;
binder.getService().setCallBack(new MyService.CallBack() { @Override
public void onDataChange(String data) {
// TODO Auto-generated method stub
Message msg=new Message();
Bundle bundle=new Bundle();
bundle.putString("data", data);
msg.setData(bundle);
handler.sendMessage(msg);
}
});
}
};
6.通过handler,把data放到UI线程,并更新UI线程
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
tvOut.setText(msg.getData().getString("data"));
};
};