Based on the Bindservice () Communication of Android development , the Bindservice () method is implemented to listen for service internal state.
Implements the listening service internal state, using a callback mechanism
1. First implement an interface
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 Run Ning=true; 6 New Thread () {7 public void Run () {8 int i=0, 9 while (running) { i++;11 String str=i+ ":" +d ata;12 log.d ("Learnservice", str), if (callback!=null) { callback.ondatachange (str); }16 try {+ sleep (+) } catch (Interruptedexception e) {n //TODO auto-generated Catch Block20 e.printstacktrace (); }22 }23 };24 }.start ();
The 4.MyBinder provides methods to return Bindservice instances.
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 stub10 Message msg=n EW Message (); bundle bundle=new bundle (); bundle.putstring ("Data", data), Msg.setdata (bundle) ; handler.sendmessage (msg); }16 }); }18 };
6. Via handler, put data on the UI thread and update the UI thread
1 Private Handler handler=new Handler () {2 public void Handlemessage (Android.os.Message msg) {3 Tvout.settext (Msg.getdata (). getString ("Data")); 4 };5 };
Android Development Bindservice () listens for service internals
Android Development Bindservice () listens for service internal status