Service as the four components worthy of our more attention
In Android, the activity is primarily responsible for the presentation of the front page, and the service is primarily responsible for tasks that require long-term operation. For example, a music player that plays music from a service should be set up for the foreground to run, because the user will be aware of its operation explicitly. Notifications in the status bar may display the current song and allow the user to initiate an activity to interact with the music player.
Two forms of implementation of service
1. Non-binding
Start a service by calling the StartService () method of an application component, such as an activity. Once started, the service runs in the background even if the application component is turned off at this time. Typically, services that have been started handle a single function, And there is no need to return the results to the caller. For example, you can download or upload files on your network. When the service is finished working, the service is closed on its own.
2. Bind (BIND)
Bind a service by calling the application component's Bindservice () method. A bound service provides a client-server interface. This interface is primarily used to interact with applications, send requests, get results, The process is even accessed through IPC. As long as one program component binding service runs the binding service, multiple application components can bind a service at the same time. When all application components are unbound, the bound server is destroyed.
Introduction to the method of implementing service
Onstartcommand ()
The system calls this method when other components, such as activity, are started by invoking the StartService () request service. Once this method is implemented, the service starts and runs for a long time in the background. If you implement it, you will be responsible for stopping it when the service completes the task by calling Stopself () or StopService (). (If you only want to provide bindings, you do not need to implement this method).
Onbind ()
This method is called when the component calls Bindservice () when it wants to bind to the service (for example, to perform interprocess communication). In your implementation, you must provide a return to a ibinder to enable the client to use it to communicate with the service, you must always implement this method, but if you do not allow binding, then you should return NULL.
OnCreate ()
The system executes this method the first time the service is created to perform an initialization work that is run only once (before invoking its method such as Onstartcommand () or Onbind ()). This method is not invoked if the service is already running.
OnDestroy ()
The system calls this method when the service is no longer in use and is to be destroyed. Your service should release resources in this method, such as threads, registered listeners, receivers, and so on. This is the last call received by the service.
If a component starts a service by invoking StartService (), which eventually causes Onstartcommand () to be invoked, the service remains running until it passes through Stopself () Stop yourself or another component call StopService () to stop it.
Service Implementation Code
1. Non-binding
Creates a new myservice inherits from the service and overrides the OnCreate (), Onstartcommand (), and OnDestroy () methods of the parent class
public class Myintentservice extends Intentservice {public
myintentservice () {
super ("Myintentservice");
}
@Override
protected void onhandleintent (Intent Intent) {
//Intentservice uses a separate thread to execute the method's code
// This method performs time-consuming tasks, such as downloading files, where the thread waits only for 20 seconds
long endtime = System.currenttimemillis () + * 1000;
System.out.println ("OnStart");
while (System.currenttimemillis () < Endtime) {
synchronized (this) {a
try {wait
(Endtime- System.currenttimemillis ());
} catch (Interruptedexception e) {
e.printstacktrace ();
}}} SYSTEM.OUT.PRINTLN ("----time-consuming task execution complete---");
}
We have added two buttons to the layout file, one for starting the service and one for stopping the service.
Then open or create a new mainactivity as the main activity of the program, adding the logic to start the service and stop the service, as shown in the following code:
public class Mainactivity extends activity implements Onclicklistener {
private Button startservice;
Private Button StopService;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
StartService = (Button) Findviewbyid (r.id.start_service);
StopService = (Button) Findviewbyid (r.id.stop_service);
Startservice.setonclicklistener (this);
Stopservice.setonclicklistener (this);
}
@Override public
void OnClick (View v) {
switch (V.getid ()) {case
R.id.start_service:
Intent Startintent = new Intent (this, myservice.class);
StartService (startintent);
break;
Case R.id.stop_service:
Intent stopintent = new Intent (this, myservice.class);
StopService (stopintent);
break;
Default: Break
;
}
}
Each service in the project must be registered in Androidmanifest.xml, so you also need to edit the Androidmanifest.xml file, as shown in the following code:
<application
android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
android:label= "@ String/app_name "
android:theme=" @style/apptheme "> ...
<service android:name= "Com.example.servicetest.MyService" >
</service>
</application>
Cycle analysis
The OnCreate () method is invoked only the first time the service is created, and if the current service has been created, the OnCreate () method will not be executed either by invoking the StartService () method. So you can click a few more times to try the Start Service button once, and each time there will only be a print log in the Onstartcommand () method.
2. Bonded Service
public class LocalService extends Service {
//Binder given to clients
private final IBinder mbinder = new Localbi NDEr ();
Random number generator
private final Random mgenerator = new Random ();
The public class Localbinder extends Binder {
LocalService getservice () {
//Returns an instance of this service to the client, So the client can invoke the public method of the service return
localservice.this
}
}
@Override public
IBinder onbind (Intent Intent) {return
mbinder;
}
/** the method to be invoked by the client
/public int getrandomnumber () {return
mgenerator.nextint ()}
}
The following is an example of a actvity that is bound to LocalService and calls GetRandomNumber () when the button is pressed:
public class Bindingactivity extends activity {LocalService mservice;
Boolean mbound = false;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
} @Override protected void OnStart () {Super.onstart ();
An instance bound to a class LocalService Intent Intent = new Intent (this, localservice.class);
Bindservice (Intent, mconnection, context.bind_auto_create);
} @Override protected void OnStop () {super.onstop ();
Unbind if (mbound) {Unbindservice (mconnection) from service;
Mbound = false;
}/** call when button is pressed (button defined in layout file and specify response to this method with Android:onclick property) * * public void OnButtonClick (View v) {if (Mbound) {
Call a method of LocalService. However, if there is a suspend operation in this call, then the request should be//is born on another thread to avoid pulling down the performance of the activity.
int num = Mservice.getrandomnumber ();
Toast.maketext (This, "number:" + num, Toast.length_short). Show (); }/** defines a callback for a service binding, passed to Bindservice () 's/private serviceconnection mconnection = new Serviceconnection () {@OverRide public void onserviceconnected (componentname className, IBinder service) {//We have been bound to LocalService, forcing the IBinder to type
Swap and get the LocalService instance.
Localbinder binder = (localbinder) service;
Mservice = Binder.getservice ();
Mbound = true;
@Override public void onservicedisconnected (ComponentName arg0) {mbound = false;
}
}; }
periodic function of service
1. When using the Context.startservice () method to start the service, the life cycle method associated with it
OnCreate () –> OnStart () –> OnDestroy ()
OnCreate () This method is invoked when a service is created, and the method is only invoked once, no matter how many times the StartService () or Bindservice () method is invoked, and the service is only created once.
OnStart () The method is only invoked when the service is started with the Context.startservice () method. The method is invoked when the service starts running. The StartService () method is called multiple times, although the service is not created more than once, but the OnStart () method is invoked multiple times.
OnDestroy () This method is invoked when a service is terminated.
2. When using the Context.bindservice () method to start the service, the life cycle method associated with it
OnCreate () –> onbind () –> onunbind () –> OnDestroy ()
Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is invoked when the caller and the service are bound, and when the caller and the service have already been bundled, calling the Context.bindservice () method multiple times does not cause the method to be invoked more than once.
Onunbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is invoked when the caller and the service are unbound.
If you start the service with the StartService () method and then call the Bindservice () method to bind to the service, then call the Unbindservice () method to unbind, and finally call the Bindservice () method to bind to the service again. The life cycle methods that are triggered are as follows:
OnCreate () –>onstart () –>onbind () –>onunbind () [overloaded method needs to return True–>onrebind ()
What if we clicked on the Bind service button and clicked on the Start service button?
This time you will find that no matter whether you click the Stop Service button or the Unbind service button alone, the service will not be destroyed, it is necessary to click on the two buttons, the service will be destroyed. That is, clicking the Stop Service button will only stop the service, and clicking the Unbind Service button will only allow service and activity to be terminated. A service must be destroyed only if it is not associated with any activity and is disposed of in a stopped state.
The difference between service and thread
Mainly because of the background concept of service. Thread we all know that it is used to open a child thread, where you can perform some time-consuming operations without blocking the main thread's operation. When we first understand the service, we always feel that it is used to deal with some background tasks, some of the more time-consuming operations can also be put here to run, which will cause confusion. However, if I tell you that the service is actually running in the mainline Chengri, so there is no relationship.
What is the use of service?
In fact, we do not connect the background and child thread together on the line, this is two completely different concepts.
The background to Android is that it runs completely independent of the UI. Even if the activity is destroyed or the program is closed, the service can continue to run as long as the process is still in progress.
For example, some applications, always need to maintain a heartbeat connection with the server, you can use the service to achieve. You may ask again, the front is not just verified service is running in the main line Chengri? Do you have a heartbeat connection here that doesn't block the main thread running? Of course, but we can create a child thread in the service and then deal with the time-consuming logic here.
The difference between creating threads and activity directly by using service
It is difficult for the activity to control thread, and when the activity is destroyed there is no other way to retrieve the instance of the child thread that was previously created. Also, a child thread created in one activity cannot be manipulated by another. But the service is different, all the activity can be associated with the service, and then it is easy to manipulate the methods, even if the operation is destroyed, and then once again with the service to establish association, It is also possible to obtain an example of binder in the original service. Therefore, the use of service to handle background tasks, the activity can be assured finish, there is no need to worry about the background task cannot control the situation.
Intentservice Introduction
Intentservice is a subclass of service that adds extra functionality to an ordinary service.
First look at the service itself there are two problems:
Service does not specifically initiate a separate process, the service is in the same process as its application;
Service is also not a dedicated new thread, so it should not be handled directly in service.
Ii. Characteristics of Intentservice
A separate worker thread is created to handle all intent requests;
A separate worker thread is created to handle the code implemented by the Onhandleintent () method without having to deal with multithreading issues;
When all requests are processed, Intentservice automatically stops without invoking the Stopself () method to stop the service;
Provides a default implementation for the service's Onbind (), returning null;
Provides a default implementation for the service's Onstartcommand, adding the request intent to the queue;
Realize
public class Myintentservice extends Intentservice {public
myintentservice () {
super ("Myintentservice");
}
@Override
protected void onhandleintent (Intent Intent) {
//Intentservice uses a separate thread to execute the method's code
// This method performs time-consuming tasks, such as downloading files, where the thread waits only for 20 seconds
long endtime = System.currenttimemillis () + * 1000;
System.out.println ("OnStart");
while (System.currenttimemillis () < Endtime) {
synchronized (this) {a
try {wait
(Endtime- System.currenttimemillis ());
} catch (Interruptedexception e) {
e.printstacktrace ();
}}} SYSTEM.OUT.PRINTLN ("----time-consuming task execution complete---");
}
Activity Code
public void Startintentservice (View source) {
//Create the Intentservice Intent
Intent Intent = new Intent that need to be started (this, Myintentservice.class);
StartService (intent);
}
The above is a small set to introduce the Android service in the use of detailed introduction of the method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!