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