The service interacts with the activity in a variety of ways, where Messenger is used to achieve the interaction between the two.
Service Program
Public class messengerservice extends Service { FinalMessenger Mmessenger =NewMessenger (NewIncominghandler ()); @Override PublicIBinder Onbind (Intent Intent) {returnMmessenger.getbinder (); } @SuppressLint ("Handlerleak") class incominghandler extends Handler {@Override Public voidHandlemessage (Message msg) {Switch(msg.what) { Case 0: Toast.maketext (Messengerservice. This,"Hello lenve!", Toast.length_long). Show (); Break; Case 1: Toast.maketext (Messengerservice. This,"Hello lenve! Hello world! ", Toast.length_long). Show (); Break;default: Break; } } }}
Mainactivity.java
Public class mainactivity extends Activity { PrivateMessenger Mmessenger;PrivateServiceconnection Conn;PrivateIntent Intent;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Intent =NewIntent ( This, Messengerservice.class); conn =NewServiceconnection () {@Override Public void onservicedisconnected(componentname name) {Mmessenger =NULL; }@Override Public void onserviceconnected(componentname name, IBinder service) {Mmessenger =NewMessenger (service); } }; }@Override protected void OnStart() {Super. OnStart (); Bindservice (Intent, Conn, bind_auto_create); }@Override protected void OnStop() {Super. OnStop (); Unbindservice (conn); } Public void OnClick(View v) {Message msg =NULL;Switch(V.getid ()) { CaseR.id.button1:msg = Message.obtain (NULL,0,0,0);Try{mmessenger.send (msg); }Catch(RemoteException e) {E.printstacktrace (); } Break; CaseR.id.button01:msg = Message.obtain (NULL,1,0,0);Try{mmessenger.send (msg); }Catch(RemoteException e) {E.printstacktrace (); } Break;default: Break; } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.
Android Development uses Messenger to enable service to interact with activity