Android Service-related comprehensive summary _android

Source: Internet
Author: User
1. Type of service
by operational location:
Category Difference Advantages Disadvantages Application
Native Service (local) The service is attached to the main process, Services are attached to the main process rather than the stand-alone process, which saves resources to some extent, and the local service does not require IPC because it is in the same process, and does not need aidl. The corresponding bindservice will be much more convenient. After the main process is killed, the service terminates. Very common applications such as: HTC Music playback service, every day beautiful music playback service.
Remote Service (Sqlremote) The service is an independent process, The service is a separate process, and the format of the process name is the package name plus the android:process string you specify. Because it is a stand-alone process, the service is still running, unaffected by other processes, and has the flexibility to provide services for multiple processes when the activity's process is killed. The service is a stand-alone process that consumes a certain amount of resources and is slightly more cumbersome to use AIDL for IPC. Some service that provides system services, which are permanent.

In fact, remote service is still very rare, and generally are system services.
Sort by Run Type:
Category Difference Application
Front desk Service will display ongoing's Notification in the notification column, When the service is terminated, the notification column of the Notification will also disappear, so that users have a certain role in the notification. Common for music playback services.
Background service The default service is the background service, which does not display the ongoing Notification in the notification column. When the service is terminated, the user does not see the effect. Some services that do not need to run or terminate prompts, such as weather updates, date synchronization, mail synchronization, and so on.

Some students may ask, background services we can create their own ongoing Notification this becomes the front desk service? The answer is no, the front desk will need to call Startforeground (Android 2.0 and later) or Setforeground (previous versions of Android 2.0) to make the service a front desk after doing the above work. The advantage of this is that the ongoing Notification will still be removed when the service is terminated by an external force.
By how to use:
Category Difference
STArtService started service Primarily used to start a service to perform background tasks without communication. Stop service using Stopservice
BindseRvice started service The service initiated by this method is to be communicated. Stop service using Unbindservice
STArtService also Bindservice started service Stop service should use both Stepservice and Unbindservice

Services initiated in the above three ways have a different life cycle, which will be given later.
2, the difference between Service and Thread
A lot of times, you may ask, why use Service instead of thread, because with thread is very convenient, compared to the Service is also more convenient, the following I explain in detail.
1). Thread:thread is the smallest unit of program execution, it is the basic unit of allocating CPU. You can use Thread to perform some asynchronous operations.
2. Service:service is a mechanism of Android that, when it is run, is a local service, and the corresponding service is run on the main thread of the master process. For example: Oncreate,onstart These functions are run on the main thread of the master process when called by the system. In the case of a remote service, the corresponding service is run on the main thread of the standalone process. So please do not understand the Service as a thread, it has nothing to do with the thread half a dime of the relationship!

In that case, then why do we use Service? In fact, this is related to the Android system mechanism, we first take Thread to say. Thread runs independently of activity, which means that when an activity is finished, thread is executed if you do not actively stop the thread or the Run method in thread is not executed. So here's the problem: when the activity is finished, you no longer hold the reference to the Thread. On the other hand, you have no way to control the same Thread in different activity.

As an example: If your thread needs to connect to the server for some sort of synchronization at intervals, the thread needs to run when the activity does not start. This time when you start an activity there is no way to control the Thread created earlier in the activity. So you need to create and start a service, create, run, and control the Thread within the service, which solves the problem (because any activity can control the same service, and the system creates only one instance of the service).

So you can think of service as a message, and you can call Context.startservice, Context.stopservice, Context.bindservice,context.unbindservice, to control it, you can also register Broadcastreceiver in the Service, in other places by sending broadcast to control it, of course these are Thread can't do that.
3, service life cycle
OnCreate OnStart OnDestroy Onbind
1. The life cycle of the service being started: If a service is invoked by an activity to invoke the Context.startservice method, So whether or not an activity is unbound to the service using Bindservice bindings or Unbindservice, the service runs in the background. If a service is started multiple times by the StartService method, the OnCreate method will only be invoked once, and OnStart will be invoked multiple times (corresponding to the number of calls to StartService). And the system creates only one instance of the service (so you should know that only one stopservice call is required). The service will always run in the background, regardless of whether the activity of the corresponding program is running until it is invoked stopservice, or its own Stopself method. Of course, if system resources are low, the Android system may also end the service.

2. The lifecycle of the bound service: If a service is invoked by an activity to invoke the Context.bindservice method binding, the OnCreate method will only be invoked once, regardless of how many times the call Bindservice called. The OnStart method is always not invoked at the same time. When the connection is established, the service will run until the Context.unbindservice disconnected or the context in which Bindservice is called is not present (such as when the activity is finished), The system will automatically stop the service and the corresponding OnDestroy will be invoked.

3. The lifecycle of a service that is started and bound: If a service is started and bound, the service will always run in the background. And no matter how the call, OnCreate will always call only once, corresponding StartService call how many times, the service onstart will be called How many times. Calling Unbindservice will not stop the service, and you must call the stopself of the StopService or service to stop it.

4. Purge service when service is stopped: The OnDestroy method will be invoked when one of the services is terminated (1, call stopservice;2, call stopself;3, no longer have a bound connection (not started)), where you should do some cleanup work, such as a thread that stops creating and running in the service.
Special attention
1, you should know that when the call Bindservice binding to the service, you should ensure that a call to the Unbindservice unbind (although the activity is done when the binding will automatically terminate, and the service will automatically stop);
2, you should pay attention to use StartService start service, be sure to use StopService stop service, whether you use Bindservice;
3, at the same time using StartService and bindservice to note that the termination of service, need to Unbindservice and StopService at the same time to terminate service, regardless of StartService and Bindservice call Order, if the service is not automatically terminated when the Unbindservice is invoked, then the service stops after the call to StopService, and the service does not terminate if first called StopService, and then calls Unbindservice or the previous call to the Bindservice context does not exist (such as when the activity is finished) before the service will automatically stop;
4, when rotating mobile phone screen, when the phone screen in the "horizontal" "vertical" transformation, at this time if your activity will automatically rotate, the rotation is actually the activity of the recreate, so before the rotation of the use of Bindservice established connection will be disconnected (context does not exist), the corresponding service life cycle is the same as above.
5, in the SDK 2.0 and later versions, the corresponding OnStart has been rejected into Onstartcommand, but the previous onStart is still valid. This means that if you are developing an application with an SDK of 2.0 and beyond, then you should use Onstartcommand instead of OnStart.
4, StartService start service
To start a service with StartService, the work we need to do, whether local or Remote, is as simple as that. Of course, remember to register the service in Androidmanifest.xml.
Depending on the life cycle above, we will give the code framework in the Service:
Copy Code code as follows:

Package com.newcj.test;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
public class LocalService1 extends Service {
/**
* Onbind is a virtual method of Service, so we have to implement it.
* Returns null indicating that the customer service side could not establish a connection to the services.
*/
@Override
Public IBinder Onbind (Intent Intent) {
return null;
}
@Override
public void OnCreate () {
Super.oncreate ();
}
@Override
public void OnStart (Intent Intent, int startid) {
Super.onstart (Intent, Startid);
}
@Override
public void OnDestroy () {
Super.ondestroy ();
}
}

Copy Code code as follows:

Start an activity
StartActivity (This, Localservice1.class) (new Intent);
...
Stop an activity
StopService (This, Localservice1.class) (new Intent);

The corresponding Intent is the Intent of the flag service class.
5, local and Remote service binding
Also remember to register your service in Androidmanifest.xml
1. Local Service bindings: The binding of the local service is simpler, first in the service we need to implement the service's abstract method Onbind and return an object that implements the IBinder interface.
The code in the Service:
Copy Code code as follows:

Package com.newcj.test;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.Binder;
Import Android.os.IBinder;
public class LocalService extends Service {
/**
* In the local Service we directly inherit Binder rather than IBinder, because Binder implements the IBinder interface so that we can do a lot less work.
* @author NEWCJ
*/
public class Simplebinder extends binder{
/**
* Get Service instance
* @return
*/
Public LocalService GetService () {
return localservice.this;
}
public int Add (int a, int b) {
return a + B;
}
}
Public Simplebinder Sbinder;
@Override
public void OnCreate () {
Super.oncreate ();
Create Simplebinder
Sbinder = new Simplebinder ();
}
@Override
Public IBinder Onbind (Intent Intent) {
Returns the Simplebinder object
return sbinder;
}
}

The key to the above code is that the Onbind (Intent) method returns an object that implements the IBinder interface, which communicates with the local service the activity that binds the service. Here is the code in the activity:
Copy Code code as follows:

Package com.newcj.test;
Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;
public class Main extends activity {
Private final static String TAG = "Service_test";
Private Serviceconnection SC;
Private Boolean isbind;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
sc = new Serviceconnection () {
@Override
public void onservicedisconnected (componentname name) {
}
@Override
public void onserviceconnected (componentname name, IBinder service) {
Localservice.simplebinder Sbinder = (localservice.simplebinder) service;
LOG.V (TAG, "3 + 5 =" + Sbinder.add (3, 5));
LOG.V (TAG, Sbinder.getservice (). toString ());
}
};
Findviewbyid (R.id.btnbind). Setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Bindservice (New Intent (Main.this, Localservice.class), SC, context.bind_auto_create);
Isbind = true;
}
});
Findviewbyid (R.id.btnunbind). Setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
if (isbind) {
Unbindservice (SC);
Isbind = false;
}
}
});
}
}

In the activity, we use the Serviceconnection interface to obtain a callback that establishes the connection and the connection accidentally lost. Bindservice has three parameters, the first is to distinguish the Service Intent and StartService Intent consistent, the second is the implementation of the Serviceconnection interface object, the last one is the flag flag bit. There are two flag,bind_debug_unbind and Bind_auto_create, the former for debugging (details can be viewed in Javadoc described above), which is used by default. Unbindservice is unbound, and the parameter is the Serviceconnection interface object that was previously created. In addition, repeatedly calling Unbindservice to release the same connection throws an exception, so I created a Boolean variable to determine if Unbindservice has been invoked.
Run Results

2. Remote Service bindings: remote service bindings because the service is in another process, it is necessary to use the IPC mechanism of Android. This is going to be a very long topic, so I'm going to write another Android IPC analysis and detail it, and then update the links here, so stay tuned.
Special attention:
1, Service.onbind if return null, then call Bindservice will start the service, but will not connect to the service, so serviceconnection.onserviceconnected will not be called, But you still need to use the Unbindservice function to disconnect it, so that the Service will stop.
6, create the front desk service
The benefits of the front desk have been described above, but setting up a service for the front desk, we need to note that the method used in SDK 2.0 and later versions is Startforeground and Stopforeground, the previous version using Setforeground, So if your application's minimum operating environment requirement is 2.0, then you can use the new method directly, if the operating environment is below 2.0, then in order to ensure backward compatibility, you must use reflection technology to invoke the new method.
Here's what I did with the code that I Apidemos, and I made some changes to it, so it's more descriptive:
Copy Code code as follows:

Package com.newcj.test;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import android.app.Notification;
Import Android.app.NotificationManager;
Import android.app.PendingIntent;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.os.IBinder;
public class Foregroundservice extends Service {
private static final class[] Mstartforegroundsignature = new class[] {
Int.class, Notification.class};
private static final class[] Mstopforegroundsignature = new class[] {
Boolean.class};
Private Notificationmanager MNM;
Private method Mstartforeground;
Private method Mstopforeground;
Private object[] Mstartforegroundargs = new object[2];
Private object[] Mstopforegroundargs = new Object[1];
@Override
Public IBinder Onbind (Intent Intent) {
return null;
}
@Override
public void OnCreate () {
Super.oncreate ();
MNM = (Notificationmanager) getsystemservice (Context.notification_service);
try {
Mstartforeground = ForegroundService.class.getMethod ("Startforeground", mstartforegroundsignature);
Mstopforeground = ForegroundService.class.getMethod ("Stopforeground", mstopforegroundsignature);
catch (Nosuchmethodexception e) {
Mstartforeground = Mstopforeground = null;
}
We do not need to set flag_ongoing_event for Notification.flags, because
The notification.flags of the foreground service always defaults to the sign bit
Notification Notification = new Notification (R.drawable.icon, "foreground Service started.",
System.currenttimemillis ());
Pendingintent contentintent = pendingintent.getactivity (this, 0,
New Intent (this, main.class), 0);
Notification.setlatesteventinfo (This, "foreground Service"),
"Foreground Service started.", contentintent);
Note Using Startforeground, ID 0 will not display notification
Startforegroundcompat (1, notification);
}
@Override
public void OnDestroy () {
Super.ondestroy ();
Stopforegroundcompat (1);
}
Start the front desk service in a compatible manner
private void Startforegroundcompat (int id, Notification n) {
if (mstartforeground!= null) {
MSTARTFOREGROUNDARGS[0] = ID;
Mstartforegroundargs[1] = n;
try {
Mstartforeground.invoke (this, Mstartforegroundargs);
catch (IllegalArgumentException e) {
E.printstacktrace ();
catch (Illegalaccessexception e) {
E.printstacktrace ();
catch (InvocationTargetException e) {
E.printstacktrace ();
}
Return
}
Setforeground (TRUE);
Mnm.notify (ID, n);
}
To stop the front desk service in a compatible manner
private void Stopforegroundcompat (int id) {
if (mstopforeground!= null) {
Mstopforegroundargs[0] = boolean.true;
try {
Mstopforeground.invoke (this, Mstopforegroundargs);
catch (IllegalArgumentException e) {
E.printstacktrace ();
catch (Illegalaccessexception e) {
E.printstacktrace ();
catch (InvocationTargetException e) {
E.printstacktrace ();
}
Return
}
Call Cancel before Setforeground because we might be able to cancel the foreground service
Was killed in that instant. This time notification will never be removed from the notification column.
Mnm.cancel (ID);
Setforeground (FALSE);
}
}

Special attention: 1, using Startforeground, if the ID is 0, then notification will not be displayed.
7, under what circumstances use StartService or BindserviceOr use both StartService and Bindservice
If you just want to start a background service for a long time to do a task, then use StartService will be OK. If you want to get in touch with a running Service, there are two ways to use broadcast and Bindservice, the disadvantage of which is that if you communicate more frequently, you are prone to performance problems and Broadcastreceiver The time to execute the code itself is very short (perhaps half of the code will not be executed), and the latter does not have these problems, so we definitely choose to use Bindservice (this time you are using both StartService and Bindservice), which It is quite useful to update some of the running state of the Service in the activity. In addition, if your service only exposes a remote interface, the client side of the connection (the Android service is the C/S architecture) calls the execution method remotely. This time you can not let the service start to run, and only with Bindservice, so that the first time to Bindservice to create a service instance to run it, this will save a lot of system resources, especially if your services are remote service, The more obvious the effect will be (of course, when the Service is created, it will take some time, and you should be aware of that).
8. Common options for Service elements in Androidmanifest.xml
Android:name-------------Service class name
Android:label--------------The name of the service, and if this is not set, the service name displayed by default is the class name
Icons for Android:icon--------------Services
Android:permission-------Affirm the permissions of this service, which means that only applications that have this permission can control or connect to this service
Android:process----------Indicate whether the service is running in another process, and if this is set, the string will be appended to the package name to represent the name of another process
Android:enabled----------If this key is set to True, the Service will be booted by default and not set by default to False
android:exported---------Indicate whether the service can be controlled or connected by another application, and do not set default this to False

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.