Explain the basics of service in Android and how to write it _android

Source: Internet
Author: User

First, let's make sure what the service is.

Service is the services in the Android system, it has so many features: it cannot interact directly with the user, it must be explicitly started by a user or other program, it has a higher priority, it has a lower priority than the application in the foreground, but higher priority than other applications in the background, This determines that when the system destroys some resources that are not exploited because of lack of memory, the probability of its being destroyed is very small.

So, when do we need to use service?
We know that service is running in the background of the application, for users to lose the focus of attention. This is when we open the music play, we want to see the picture, at this time we do not want to stop the music, there will be use of service; For example, after we open a download link, we definitely don't want to stare and wait for him to do something else after downloading, right? At this time if we want to phone one side in the background to download, one side can let me go to see the news what, will use the service.

Service Category:
Generally we think that service is divided into two categories, local service and remote service.

1. Local Service: as the name suggests, that is, and currently applied in the same process of service, with each other have a common memory area, so for some data sharing is particularly convenient and simple;

2. Remote service: mainly involved in the different processes between the service access. Because Android's system security causes us to be unable to share data in a common way between different processes. Here Android provides us with a aidl tool. (Android Interface Description Language) Android Interface Description Language. We'll take a detailed description of it in the rear.

Service initiation Process
Context.startservice () Start process:
Context.startservice ()-> onCreate ()-> OnStart ()-> Service running-> context.stopservice ()-> ondes Troy ()-> Service stop

If the service is not yet running, Android calls OnCreate () first, and then calls OnStart ();
If the service is already running, only OnStart () is invoked, so the OnStart method for a service may be repeated multiple times.
If the stopservice will be directly OnDestroy, if the caller himself withdrew without invoking StopService, the service will always run in the background, When the caller of the service is restarted, the service can be turned off by StopService.
So the lifecycle of invoking StartService is: OnCreate--> onStart (callable multiple times)--> OnDestroy

Context.bindservice () Start process:
Context.bindservice ()-> onCreate ()-> onbind ()-> Service running-> onunbind ()-> OnDestroy ()-> Service stop

Onbind () will return to the client a Ibind interface instance, Ibind a method that allows the client to callback the service, such as obtaining an instance of service, running state, or other operation. This time the caller (context, for example, activity) is bound to the service, the context exits, and Srevice calls Onunbind->ondestroy to exit accordingly.
So the life cycle of the invocation Bindservice is: OnCreate--> onbind (only once, not multiple bindings)--> Onunbind the-->.
Only OnStart can be invoked multiple times (through multiple StartService calls) during each open shutdown of the service, and other oncreate,onbind,onunbind,ondestory can only be invoked once in a lifecycle.

Service life cycle:

Compared to activity, the life cycle of service is simply no longer simple, only OnCreate ()->onstart ()->ondestroy () three methods.

Activity and service-related methods:

    • StartService (Intent Intent): Start a service
    • StopService (Intent Intent): Stop a service


If we want to use some of the data in the service or access some of these methods, then we'll go through the following methods:

    • public boolean Bindservice (Intent Intent, serviceconnection conn, int flags);
    • public void Unbindservice (Serviceconnection conn);

Intent is the Intent that jumps to the service, such as Intent Intent = new Intent (); Intent.setclass (This,myservice.class);

/** 
  * triggered when link to service. * Name is linked to the name of the 
  service component 
  * The IBinder returned when the service calls Onbund in the service, mainly for information exchange/ 
 @Override 
 Public void onserviceconnected (componentname name, IBinder service) { 
  log.i ("Notification", "link successful!") "); 
  Mybinder binder = (mybinder) service; 
  MyService MyService = Binder.getmyservice (); 
  int count = Myservice.getcount (); 
  LOG.I ("Notification", "count=" +count); 
   
 } 


Steps to use service:


The first step: we must inherit the service class, realizes own service.

If you want to access certain values in the service, we usually provide an inner class that inherits the binder and returns it to the service request through the Onbund () method. This is actually a clever use of the internal classes can access the characteristics of the external class properties.

Step two: Register in Androidmanifest.xml, for example:

<!-- 
 service configuration started
 -->
 <service android:name= "MyService" ></service>
<!-- 
 Service configuration End
 -->

Step three: Start, bind, unbind, or stop the service in the activity.

(Many books say that the service and the user can not be interactive, in fact, this is not true, we can completely through the activity and service interaction!) I think the exact statement should be that the service does not interact directly with the user.

Example
Below provides an example of calling the service to listen to music:


Activity code:

Package Cn.com.chenzheng_java; 
Import Cn.com.chenzheng_java.MyService.MyBinder; 
Import android.app.Activity; 
Import Android.content.ComponentName; 
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; 
Import Android.widget.Button; /** * @description Simple application of Service * * public class Serviceactivity extends activity implements onclicklistener{PRI 
 Vate Button Button_start; 
 Private Button Button_bind; 
 Private Button Button_destroy; 
 
 Private Button Button_unbind; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
   
  Setcontentview (R.layout.service); 
  Button_start = (Button) Findviewbyid (R.id.button1_service); 
  Button_bind = (Button) Findviewbyid (R.id.button2_service); 
  Button_destroy = (Button) Findviewbyid (R.id.button3_service); BUtton_unbind = (Button) Findviewbyid (R.id.button4_service); 
  Button_start.setonclicklistener (this); 
  Button_bind.setonclicklistener (this); 
  Button_destroy.setonclicklistener (this); 
   
 Button_unbind.setonclicklistener (this); 
   The private class Myserviceconnection implements serviceconnection{/** * is triggered when it is linked to the service. * Name is linked to the service component's name * The IBinder returned when the service calls Onbund in the service, used primarily for information exchange/@Override public void Onservice Connected (componentname name, IBinder service) {LOG.I ("notification", "link successful!") 
   "); 
   Mybinder binder = (mybinder) service; 
   MyService MyService = Binder.getmyservice (); 
   int count = Myservice.getcount (); 
    
  LOG.I ("notice", "count=" +count); @Override public void onservicedisconnected (componentname name) {LOG.I ("notification"), link not successful! 
  "); 
 } private Myserviceconnection serviceconnection = new Myserviceconnection (); @Override public void OnClick (View v) {if (v = = Button_start) {Intent Intent = newIntent (); 
   Intent.setclass (Getapplicationcontext (), myservice.class); 
  StartService (Intent); 
   } if (v = = button_bind) {Intent Intent = new Intent (); 
   Intent.setclass (Getapplicationcontext (), myservice.class); 
  Bindservice (Intent,serviceconnection, bind_auto_create); 
   } if (V==button_destroy) {Intent Intent = new Intent (); 
   Intent.setclass (Getapplicationcontext (), myservice.class); 
  StopService (Intent); 
  } if (V==button_unbind) {unbindservice (serviceconnection); 

 }   
   
 } 
  
}

Classes that inherit the service:

Package Cn.com.chenzheng_java; 
Import Android.app.Service; 
Import android.content.Intent; 
Import Android.media.MediaPlayer; 
Import Android.os.Binder; 
Import Android.os.IBinder; 
 
Import Android.util.Log; /** * @description realize its own service * @author Chenzheng_java * @since 2011/03/18/public class MyService extends Se 
 
 rvice {MediaPlayer MediaPlayer; /** * When the user invokes the Bindservice method, it triggers the method to return a IBinder object from which we can access certain data in the service * * @Override public ibinder onbind (I Ntent Intent) {LOG.I ("notification", "service binding successful!") 
  "); 
 return new Mybinder (); @Override public void OnCreate () {LOG.I ("Notifications", "Service creation is successful!") 
 
  "); 
  MediaPlayer = Mediaplayer.create (this, r.raw.aiweier); 
  Mediaplayer.setlooping (FALSE); 
 Super.oncreate (); 
  @Override public void OnDestroy () {mediaplayer.stop (); LOG.I ("Notice", "Service Destroy success!") 
  "); 
 Super.ondestroy (); @Override public void Onrebind (Intent Intent) {log.i ("Notifications", "Service rebind succeeded!") 
  "); Super.onrebind (inteNT); 
  @Override public void OnStart (Intent Intent, int startid) {mediaplayer.start (); LOG.I ("Notice", "Service start success!") 
  "); 
 Super.onstart (Intent, Startid); 
  @Override public boolean onunbind (Intent Intent) {mediaplayer.stop (); LOG.I ("Notice", "Service Solution binding success!") 
  "); 
 return Super.onunbind (Intent); 
 
 private int count = 100; 
 public int GetCount () {return count; 
 public void SetCount (int count) {This.count = count; 
   The public class Mybinder extends Binder {/** * @return returns a personal service object/MyService Getmyservice () { 
  return myservice.this; 

 } 
 } 
 
}

Service.xml Code:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
 "http://schemas.android.com/" Apk/res/android " 
 android:layout_width=" match_parent " 
 android:layout_height=" match_parent "> 
 < Button android:text= "Start" android:id= "@+id/button1_service" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" ></Button> 
 <button android:text= "binding" android:id= "@+id/button2_service" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" ></Button> 
 <button Android:text= "Destroy" android:id= "@+id/button3_service" android:layout_width= "Wrap_content" android:layout_height= " Wrap_content "></Button> 
 <button android:text=" android:id= "@+id/button4_service" Android: Layout_width= "Wrap_content" android:layout_height= "wrap_content" ></Button> 
</LinearLayout> 

Androidmanifest.xml

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemas.android.com/apk/res/" Android " 
  package=" Cn.com.chenzheng_java " 
  android:versioncode=" 1 " 
  android:versionname=" 1.0 "> 
 <uses-sdk android:minsdkversion= "8"/> 
 
 <application android:icon= "@drawable/icon" android:label= "@string/app_name" > 
  <activity android:name= "serviceactivity" 
     android:label= "@string/app_name" > 
   <intent-filter> 
    <action android:name= "Android.intent.action.MAIN"/> 
    <category Android:name= "Android.intent.category.LAUNCHER"/> 
   </intent-filter> 
  </activity> 
<!-- 
 service configuration started 
 --> 
 <service android:name= "MyService" ></service> 
<!-- 
 Service configuration End 
 --> 
 </application> 
 </manifest> 


Final Effect Diagram:

Related Article

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.