Android learning _ Service, android_service

Source: Internet
Author: User

Android learning _ Service, android_service

Description: one of the modules of the Service application can be seen from the official documents. When an application needs to perform operations that require long running time (processing time-consuming logic in the background ), in addition, you do not need to interact with users. In this case, you can use services in the background.

Recently, I started to reinvent Android development again. I had a simple Android Application when I was busy with projects. Now I have to learn more... No nonsense.

Overview

Public abstract class

Service

Extends ContextWrapper

Implements ComponentCallbacks2

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. each service class must have a correspondingDeclaration in its package's AndroidManifest. xml. Services can be startedContext. startService ()AndContext. bindService ().

From the official documents, we can see that one of the modules of the Service application program, when the application needs to perform some operations that require a long time to run (the background processes some time-consuming logic ), in addition, you do not need to interact with users. In this case, you can use services in the background.

So let's summarize the Service'sFeatures:

  • Running in the background is usually a function module of the application;
  • It is usually a logical operation that runs for a long time. Even if the program exits, the Service can still run in the background;
  • No interaction with users;
  • It is common throughout the application;
  • It runs in the main thread, so it cannot be used for time-consuming requests or operations (you can open a new thread in the service ).
Service Category

Services are generally divided into two types:

  • Local Service: the Local Service is used inside the application. It is started by calling Context. startService () and ended by calling Context. stopService. You can call Service. stopSelf () internally to stop the task. No matter how many times startService () is called, you only need to call stopService () once to stop.
  • Remote Service: Remote Service is used between applications in the system. You can define interfaces for other operations. The client establishes a connection to the service object and calls the service through that connection. Call the Context. bindService () method to establish a connection and start the connection. Call Context. unbindService () to close the connection.
Service Lifecycle

Service only inheritsOnCreate (),OnStartCommand ()AndOnDestroy ()Three methods: when the Service is started for the first time, the onCreate () and onStartCommand () methods are called successively. when the Service is stopped, the onDestory () method is executed, when our Service is started, the onStartCommand () method is directly executed when it is started again (go to the app manager of the mobile phone to check whether your Service is running ).

Service Usage

Generally, you can use Intent to start the Service and override the onCreate (), onStartCommand (), and onDestroy () Methods of the parent class.

Communication between Service and Activity

You can enable a service in the Activity. How can we establish a communication relationship between the two? Here, we write some pseudo code.

public class MyService extends Service {    public static final String M_TAG = "MyService";    private MyBinder m_binder = new MyBinder();    @Override    public void onCreate() {        super.onCreate();        Log.i(M_TAG, "onCreate() executed");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i(M_TAG, "onStartCommand() executed");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        Log.i(M_TAG, "onDestroy() executed");    }    @Override    public IBinder onBind(Intent intent) {        return m_binder;    }    class MyBinder extends Binder {        public void MyMethod() {            Log.i(M_TAG, "Start MyMethod()");            // ...        }    }}

Starting a Service actually starts a new process. Therefore, the communication between the Service and the Activity is actually a communication problem between different processes (not described at the moment ). The above Code uses IBinder. What is this?

Public interface

IBinder

Base interface for a remotable object, the core part of a lightweight remote procedure call mechanic designed for high performance when Discovery Ming in-process and cross-process CILS. this interface describes the abstract protocol for interacting with a remotable object. do not implement this interface directly, instead extend from Binder.

IBinder is a basic interface for remote objects. It is the core part of a lightweight Remote Call mechanism for processes and cross-process call services. This interface describes an abstract protocol. The pseudo code above implements a custom MyBinder method, and adds its own MyMethod method to it.

Next, modify the MainActivity for starting MyService:

public class MainActivity extends Activity {    // ...    private MyService.MyBinder m_binder;    private ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            m_binder = (MyService.MyBinder)service;            m_binder.MyMethod();        }        @Override        public void onServiceDisconnected(ComponentName name, IBinder service) {            // ..        }    };    // ...}

Public interface

ServiceConnection

Interface for monitoring the state of an application service. Like calling callbacks from the system, the methods on this class are called from the main thread of your process.

An anonymous ServiceConnection class is created here, And the onServiceConnected and onServiceDisconnection methods are rewritten. These two methods will be called when the Activity and Service establish and cancel the connection. Then, through the IBinder interface, the Activity can call the internal methods of the Service.

Of course, the bindService (Intent, ServiceConnection, int) interface must be called to bind the two. Here, the third parameter int Is a flag.

  • BIND_ALLOW_OOM_MANAGEMENT: Allow the process hosting the bound service to go through its normal memory management.
  • BIND_AUTO_CREATE: Automatically create the service as long as the binding exists.
  • BIND_DEBUG_UNBIND: Include debugging help for mismatched callto unbind.
  • BIND_IMPORTANT: This service is very important to the client, so shocould be brought to the foreground process level when the client is.
  • BIND_NOT_FOREGROUND: Don't allow this binding to raise the target service's process to the foreground scheduling priority.
  • BIND_WAIVE_PRIORITY: Don't impact the scheduling or memory management priority of the target service's hosting process.

To terminate the connection, you only need to call the unbindService (connection) interface.

Of course, the Service can not only establish a connection with its Activity, but also establish a connection with other activities in the application, and obtain instances of the same extends IBinder.

Continuous updates...

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.