Service interacts with the activity in a variety of ways, and here is the use of Messenger to achieve the interaction between the two.
Service procedure:
public class Messengerservice extends Service {
final messenger Mmessenger = new Messenger (new Incominghandler ());
@Override public
ibinder onbind (Intent Intent) {return
mmessenger.getbinder ();
}
@SuppressLint ("Handlerleak")
class Incominghandler extends Handler {
@Override public
Void Handlemessage (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.javal:
public class Mainactivity extends activity {private Messenger Mmessenger;
Private Serviceconnection Conn;
Private Intent Intent;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Intent = new Intent (This,messengerservice.class); conn = new Serviceconnection () {@Override public void onservicedisconnected (componentname name) {Mmessenger =
Null @Override public void onserviceconnected (componentname name, IBinder service) {Mmessenger = new Messenger (SE
Rvice);
}
};
} @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) {msg = null;
Switch (V.getid ()) {Case r.id.button1:msg = Message.obtain (null, 0, 0, 0);
try {mmessenger.send (msg); catch (RemoteexCeption e) {e.printstacktrace ();
} break;
Case r.id.button01:msg = Message.obtain (null, 1, 0, 0);
try {mmessenger.send (msg);
catch (RemoteException e) {e.printstacktrace ();
} break;
Default:break;
}
}
}
Original link: http://blog.csdn.net/u012702547/article/details/46989417
This is the entire content of this article, I hope to learn more about Android software programming help.