Android service Introduction
1. What is service?
2. How to Use Service
3.ServiceLifecycle
1. What isService
ServiceThe name is similar to the "service" that we normally understand. It runs in the background and can interact with each other. It is similar to the activity level, but it cannot be run by itself. It needs to be called through an activity or other context object, context. startservice () and context. bindservice ().
Two types of startupServiceMethods are different. It should be noted that if you areServiceOncreate or onstart to do some time-consuming things, it is bestServiceTo start a thread, becauseServiceRunning in the main thread will affect your UI operations or block other things in the main thread.
When needServiceWhat about it? For example, when the user starts other activities during multimedia playback, the program will continue playing in the background, for example, detecting file changes on the SD card, or recording changes to your location in the background, in short, services are always hidden behind the scenes.
IIHow to UseService
Next, use the code to illustrate how to use it.ServiceHere we will talk about localServiceThat is, your ownServiceYou can also operate other applicationsServiceIf it allows you to do that, it will design a troublesome Interprocess Communication (IPC) mechanism for communication in different processes, I have never used this one myself. I will talk about it later. Generally, local is enough.
Like activity, you must first write a class that inherits fromAndroid. App.ServiceHere I call him testservice
The Code is as follows:
Package com. haric. Tutorial;
ImportAndroid. App. notification;
ImportAndroid. App. icationicationmanager;
ImportAndroid. App. pendingintent;
ImportAndroid. App.Service;
ImportAndroid. Content. intent;
ImportAndroid. OS. Binder;
ImportAndroid. OS. ibinder;
ImportAndroid. Util. log;
Public class testservice extendsService{
Private Static final string tag = "testservice ";
Private icationicationmanager _ nm;
@ Override
Public ibinder onbind (intent I ){
Log. E (TAG, "==============> testservice. onbind ");
Return NULL;
}
Public class localbinder extends binder {
Testservice getservice (){
Return testservice. This;
}
}
@ Override
Public Boolean onunbind (intent I ){
Log. E (TAG, "==============> testservice. onunbind ");
Return false;
}
@ Override
Public void onrebind (intent I ){
Log. E (TAG, "==============> testservice. onrebind ");
}
@ Override
Public void oncreate (){
Log. E (TAG, "==============> testservice. oncreate ");
_ NM = (icationicationmanager) getsystemservice (notification_service );
Shownotification ();
}
@ Override
Public void onstart (intent, int startid ){
Log. E (TAG, "==============> testservice. onstart ");
}
@ Override
Public void ondestroy (){
_ NM. Cancel (R. String. service_started );
Log. E (TAG, "==============> testservice. ondestroy ");
}
Private void shownotification (){
Notification = new notification (R. drawable. face_1,
"ServiceStarted ", system. currenttimemillis ());
Pendingintent contentintent = pendingintent. getactivity (this, 0,
New intent (this, testserviceholder. Class), 0 );
// Must set this for content view, or will throw a exception
Notification. setlatesteventinfo (this, "TestService",
"ServiceStarted ", contentintent );
_ NM. Y (R. String. service_started, notification );
}
}
The notification is used to explicitly indicateServiceThe survival status, learned from the Demo code, looks a little more intuitive. Let's write more about the notification content in the UI section. Now we know how to use it.
@ Override
Public void oncreate (){
Log. E (TAG, "==============> testservice. oncreate ");
_ NM = (icationicationmanager) getsystemservice (notification_service );
Shownotification ();
}
In this wayServiceThe log printing statement is added to several lifecycle functions to facilitate testing.
Public class localbinder extends binder {
Testservice getservice (){
Return testservice. This;
}
}
This method is used to allow the caller to obtain thisServiceAnd operate on it.
ServiceThis is simple. You need to do everything in oncreate and onstart, and start a thread or something.
Let's take a look at its caller, testserviceholder.
Package com. haric. Tutorial;
ImportAndroid. App. activity;
ImportAndroid. Content. componentname;
ImportAndroid. Content. context;
ImportAndroid. Content. intent;
ImportAndroid. Content. serviceconnection;
ImportAndroid. OS. Bundle;
ImportAndroid. OS. ibinder;
ImportAndroid. View. view;
ImportAndroid. View. View. onclicklistener;
ImportAndroid. Widget. Button;
ImportAndroid. Widget. Toast;
Public class testserviceholder extends activity {
Private Boolean _ isbound;
Private testservice _ boundservice;
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. test_service_holder );
Settitle ("ServiceTest ");
Initbuttons ();
}
Private serviceconnection _ connection = new serviceconnection (){
Public void onserviceconnected (componentname classname, ibinderService){
_ Boundservice = (testservice. localbinder)Service). Getservice ();
Toast. maketext (testserviceholder. This ,"ServiceConnected ",
Toast. length_short). Show ();
}
Public void onservicedisconnected (componentname classname ){
// Unexpectedly disconnected, We shoshould never see this happen.
_ Boundservice = NULL;
Toast. maketext (testserviceholder. This ,"ServiceConnected ",
Toast. length_short). Show ();
}
};
Private void initbuttons (){
Button buttonstart = (button) findviewbyid (R. Id. start_service );
Buttonstart. setonclicklistener (New onclicklistener (){
Public void onclick (view arg0 ){
Startservice ();
}
});
Button buttonstop = (button) findviewbyid (R. Id. stop_service );
Buttonstop. setonclicklistener (New onclicklistener (){
Public void onclick (view arg0 ){
Stopservice ();
}
});
Button buttonbind = (button) findviewbyid (R. Id. bind_service );
Buttonbind. setonclicklistener (New onclicklistener (){
Public void onclick (view arg0 ){
Bindservice ();
}
});
Button buttonunbind = (button) findviewbyid (R. Id. unbind_service );
Buttonunbind. setonclicklistener (New onclicklistener (){
Public void onclick (view arg0 ){
Unbindservice ();
}
});
}
Private void startservice (){
Intent I = new intent (this, testservice. Class );
This. startservice (I );
}
Private void stopservice (){
Intent I = new intent (this, testservice. Class );
This. stopservice (I );
}
Private void bindservice (){
Intent I = new intent (this, testservice. Class );
Bindservice (I, _ connection, context. bind_auto_create );
_ Isbound = true;
}
Private void unbindservice (){
If (_ isbound ){
Unbindservice (_ connection );
_ Isbound = false;
}
}
}
Here we can see two startup Methods: Start and bind. Of course, they are also called through intent. In intent, specifyServiceThe same is true for stop:
Private void startservice (){
Intent I = new intent (this, testservice. Class );
This. startservice (I );
}
Private void stopservice (){
Intent I = new intent (this, testservice. Class );
This. stopservice (I );
}
For BIND, A serviceconnection object is required.
Private serviceconnection _ connection = new serviceconnection (){
Public void onserviceconnected (componentname classname, ibinderService){
_ Boundservice = (testservice. localbinder)Service). Getservice ();
Toast. maketext (testserviceholder. This ,"ServiceConnected ",
Toast. length_short). Show ();
}
Public void onservicedisconnected (componentname classname ){
// Unexpectedly disconnected, We shoshould never see this happen.
_ Boundservice = NULL;
Toast. maketext (testserviceholder. This ,"ServiceConnected ",
Toast. length_short). Show ();
}
};
Used to combine activity and specificServiceConnect to each other to survive. For details about the lifecycle, refer to the following section.
3.ServiceLifecycle
ServiceThe life cycle method of is less than activity, only oncreate, onstart, ondestroy
There are two ways to startService, TheyServiceThe impact of lifecycle is different.
1. Use startservice
ServiceWill go through oncreate-> onstart
Ondestroy
If the caller (testserviceholder) Exits without calling stopservice
Words,ServiceWill always run in the background.
The next time testserviceholder gets up again, it can be stopservice.
2. bindservice
ServiceOnly oncreate is run. At this time, testserviceholder and testservice are bound together.
When testserviceholder exits, srevice will call onunbind-> ondestroyed
The so-called binding together will survive.
Some people asked, what will happen if these methods are intertwined?
One principle is thatServiceThe oncreate method of is called only once, that is, no matter how many times you call startservice and bindservice,ServiceIt is created only once. If BIND is started, it runs directly at start.ServiceIf the onstart method is set to start first, the onbind method is run directly during bind. If you get the BIND first, you can stop it. Right, that is, stopservice is not good. You can only unbindservice first, and then stopservice, therefore, there is a difference between start and bind.
It seems that there are many situations, but I will paste this code, including the research code of the previous activity lifecycle, and hope you like it! If you are interested, you can go back and click the button to check the log. You can simply read the log several times.
Reprinted from: http://hi.baidu.com/weiyousheng/blog/item/b82f228bb1cdaf1ac9fc7a40.html