Service details for Android Development

Source: Internet
Author: User

Service details for Android Development

Service, as one of the four Android components, must be the focus. Today, we will explain the service lifecycle, the two activation methods, and their usage.

There are two ways to enable the Service. One is to enable the Service normally, and the other is to bind the service. Of course, these two methods can be combined to enable the Service.


1. The method for enabling a Service normally is very simple. Let's first look at how to define a Service 1. Compile a class to inherit the Service class. We will ignore the binder class in the code first. Which will be used later.
public class TestService extends Service {@Overridepublic IBinder onBind(Intent arg0) {System.out.println("onBind");return new Mybinder();}@Overridepublic void onCreate() {System.out.println("create");super.onCreate();}@Overridepublic void onDestroy() {System.out.println("onDestroy");super.onDestroy();}@Override@Deprecatedpublic void onStart(Intent intent, int startId) {System.out.println("start");super.onStart(intent, startId);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic boolean onUnbind(Intent intent) {System.out.println("onUnbind");return super.onUnbind(intent);}class Mybinder extends Binder implements IService {public void method() {System.out.println("serviceMethod");}}}
2. register the service in the configuration file
  
         
 

3. enable the Service normally
intent = new Intent(getBaseContext(), TestService.class);startService(intent);

4. Close the service normally
stopService(intent);

It is worth noting that the intent object of a service is made into a global variable to destroy the service upon exit. This is a step for normal service use. In normal use, the service life cycle is as follows: Enable: onCreate --> onStartCommand --> onStart: onDestory normally, the service is only enabled once, the onCreate method is executed only once. if the service is enabled, the onCreate method will be skipped when the startService method is executed again, and the onStartCommand method and subsequent method will be executed directly. The onStart method is obsolete.
2. When Service binding is enabled, sometimes we need to call the methods in the service. At this time, we need to bind the service. About how to bind and enable the Service, this android binder Mechanism is involved. This will be explained in the next topic. Skip this step. To enable the Service by binding, we need to prepare several items. 1. Implement a class that inherits the binder. 2. Implement a class that implements the ServiceConnection interface in the activity.
1. binder class implementation binding service, will call the onBind method, and then return an IBinder proxy. Therefore, we need to implement a class that inherits the Binder. Then write a method in it to call the method in the service. IService is an interface class for subsequent operations to remotely call the service method.
class Mybinder extends Binder implements IService {public void method() {System.out.println("serviceMethod");}}

Return the binder in the onBind method.
@Overridepublic IBinder onBind(Intent arg0) {System.out.println("onBind");return new Mybinder();}

2. Get the proxy binder because the Binder implements the IService interface, we also get a class that implements IService.
class Mycon implements ServiceConnection {@Overridepublic void onServiceConnected(ComponentName arg0, IBinder binder) {Iservice = (IService) binder;}@Overridepublic void onServiceDisconnected(ComponentName arg0) {}}

3. Service binding and service calling methods and unbinding
intent = new Intent(getBaseContext(), TestService.class);conn = new Mycon();bindService(intent, conn, BIND_AUTO_CREATE);
After the service is bound in this way, the service life cycle is like this: onCreate --> onBind. The onStartCommand method is not executed. After getting the proxy class, we can execute the methods in the service.
findViewById(R.id.test).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//startService(intent);Iservice.method();}});
In this way, the methods in the service are called. There is a risk of starting the service by binding. If you start the service by binding, an error will be reported when you minimize the number of programs. The program will remind you to unbind the service. In this case, we need to unbind services from some actvity lifecycles.
unbindService(conn);
Run this line of code to unbind the service. The execution Life Cycle letter is onUnBind --> onDestory

3. Before the hybrid service is enabled, we say that starting the service by binding will cause program errors to be minimized. What can be done? At this time, we need to enable the service in a hybrid mode. The so-called hybrid enabling means that after the service is enabled normally, the service is bound using the binding method. Let's look at the code
intent = new Intent(getBaseContext(), TestService.class);startService(intent);conn = new Mycon();bindService(intent, conn, BIND_AUTO_CREATE);

In this way, the hybrid service is enabled. The function for executing the lifecycle is onCreate --> onStartCommand --> onStart --> onBind. We need to unbind the function before stopping the service.
unbindService(conn);stopService(intent);conn=null;intent=null;

At this time, the life cycle function is: onUnbind --> onDestory


4. Call remote services. Sometimes, we need to call the methods of services in other applications. This is actually the implementation of the android IPC Mechanism principle. Let's talk about the method and code for implementing the steps today. 1. Rename the interface file to the. aidl file.
package com.example.servicedemo;interface IService { void method();}

After changing the extension name of the IService interface file to. aidl, we need to remove the public and other modifier fields. 2. In the new application, create a new package with the same name as the. aidl file package. Copy the. aidl file to the package.
3. Modify the binder Implementation Method in the previous service class
class Mybinder extends IService.Stub {public void method() {System.out.println("serviceDemomethod");}}
After modifying the previous interface file, we can directly inherit the. Stub class automatically generated by the interface file.
4. Define the method for enabling the implicit trial intent of the service and enable the Service with the implicit intent because the Class Name of the service in other applications cannot be obtained, therefore, we need to use implicit intent to start the service and bind it.
        
             
                              
          
 
Before binding a service, you need to rewrite the proxy interface implementation class. Here, forced conversion is no longer used.
class Mycon implements ServiceConnection {@Overridepublic void onServiceConnected(ComponentName arg0, IBinder binder) {Iservice = IService.Stub.asInterface(binder);}@Overridepublic void onServiceDisconnected(ComponentName arg0) {}}

Then bind the service to call the remote service method.
Intent intent = new Intent();intent.setAction("com.example.servicedemo.TestService.action");bindService(intent, new Mycon(), BIND_AUTO_CREATE);findViewById(R.id.test).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {try {Iservice.method();} catch (RemoteException e) {e.printStackTrace();}}});


When using the service, you must note that when you end the service, remember to release all the resources in the service, in particular, sub-threads are enabled in the Service and the loop is wireless.
Now, the basic usage of the service is over. I hope this article will help you.

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.