Android BASICS (II), Service and IntentService, androidintent

Source: Internet
Author: User

Android BASICS (II), Service and IntentService, androidintent
I. Overview the lifecycle of the activity of the four major components in the previous article. This article will introduce another component service that is most similar to the activity and its subclass intentService, the service component is the most similar to the activity component among the four android components. The biggest difference between the service component and the activity is that there is no interface and it runs on the background for a long time, in addition, its life cycle can be the longest of the four major components. Without interfaces, the life cycle duration is one of the four essential components in android development, it is also the key to selecting activity or service. To learn about service, we must first know service lifecycle 2 and service lifecycle.

The service has different lifecycles depending on the startup method. The following describes the lifecycle of a service in two ways:

Let's perform a simple test and observe the background log printing:

Layout File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"  >     <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">    <Button        android:id="@+id/btn_start"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:padding="30dp"        android:text="startService" />    <Button        android:id="@+id/btn_end"        android:layout_width="0dp"        android:padding="30dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="stopService" />    </LinearLayout>    <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">    <Button        android:id="@+id/btn_bind"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:padding="30dp"        android:text="bindService" />    <Button        android:id="@+id/btn_unbind"        android:layout_width="0dp"        android:padding="30dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="unbindService" />    </LinearLayout></LinearLayout>

CommonService. java

package com.example.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class CommonService extends Service {    @Override    public IBinder onBind(Intent arg0) {        Log.e("onBind", "===============onBind================");        return null;    }    @Override    public void onCreate() {        Log.e("onCreate", "===============onCreate================");        super.onCreate();    }    @Override    public void onDestroy() {        Log.e("onDestroy", "===============onDestroy================");        super.onDestroy();    }    @Override    public void onRebind(Intent intent) {        Log.e("onRebind", "===============onRebind================");        super.onRebind(intent);    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.e("onStartCommand", "===============onStartCommand================");        return super.onStartCommand(intent, flags, startId);    }    @Override    public boolean onUnbind(Intent intent) {        Log.e("onUnbind", "===============onUnbind================");        return super.onUnbind(intent);    }}

MainActivity. java

Package com. example. servicedemo; import android. app. activity; import android. app. service; 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. widget. button; public class MainActivity extends Activity implements View. onClickListener {private ServiceConnection conn = new ServiceConnection () {/*** callback when the current client is disconnected from the service, here the client is MainActivity * @ param name */@ Override public void onServiceDisconnected (ComponentName name) {Log. e ("onServiceDisconnected", "====== disconnect ======== ");} /*** callback when the client and Service are connected successfully. Here, the client is MainActivity * @ param name * @ param service */@ Override public void onServiceConnected (ComponentName name, IBinder service) {Log. e ("onServiceConnected", "======= connection succeeded ========") ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button btn_start = (Button) findViewById (R. id. btn_start); btn_start.setOnClickListener (this); Button btn_bind = (Button) findViewById (R. id. btn_bind); btn_bind.setOnClickListener (this); Button btn_end = (Button) findViewById (R. id. btn_end); btn_end.setOnClickListener (this); Button btn_unbind = (Button) findViewById (R. id. btn_unbind); btn_unbind.setOnClickListener (this) ;}@ Override public void onClick (View v) {Intent intent; switch (v. getId () {case R. id. btn_start: intent = new Intent (this, CommonService. class); startService (intent); break; case R. id. btn_bind: intent = new Intent (this, CommonService. class); bindService (intent, conn, Service. BIND_AUTO_CREATE); break; case R. id. btn_end: intent = new Intent (this, CommonService. class); stopService (intent); break; case R. id. btn_unbind: unbindService (conn); break ;}}}
Service startup is similar to activity. Do not forget to configure service in the configuration file.
<service       android:name="com.example.servicedemo.CommonService"></service>
StartService and stopService:

The startService button is called five times in a row. We can see that onCreate is called only once, and the onStartCommand method is called every time:

From the above we can see that multiple times to start an existing service will call only one onCreate, but each time the onStartCommand method will be called. Let's take a look at bindService and unbindService:

BindService button five times in a connection:

We can see that, no matter how many times we call bindService, onCreate and onBind will only call once

Through the above images and tests, we have a certain understanding of the service life cycle. Let's summarize the call of each method in the service life cycle.
  • OnBind (): This method must be implemented by the Service subclass. This method returns an IBinder object through which the application can communicate with the Service component.
  • OnCreate (): called when the service is created for the first time. Note that the service is created for the first time.
  • OnDestroy (): called when the service is destroyed
  • OnStartCommand (): each time the client calls startService () to start the service, it calls
  • OnUnbind: This method is called back when all clients bound to the service (usually activity or broadcast) are disconnected.
Service usage is similar to activity usage. When our program can meet our needs without the interface, or we need to perform some operations after an activity exits, at this time, we have to use service instead of activity. Let's take a look at the intentService subclass of service. 3. IntentService

IntentService is a subclass of the Service class and is used to process asynchronous requests. The client can pass the request to the IntentService through the startService (Intent) method. In the onCreate () function, IntentService enables a thread to process all Intent request objects (sent by startService, this prevents transaction processing from blocking the main thread. After the work corresponding to the previous Intent request object is executed, if no new Intent request reaches, the Service is automatically stopped; otherwise, the task corresponding to the next Intent request is executed.
When processing transactions, IntentService still uses the Handler method to create an internal Handler named ServiceHandler and bind it directly to the subthread corresponding to HandlerThread. ServiceHandler encapsulates all the transactions corresponding to an intent into a virtual function called onHandleIntent. Therefore, we directly implement the virtual function onHandleIntent, you can perform different Transaction Processing Based on Intent.
In addition, IntentService implements the Onbind () method by default, and the return value is null.
Two steps are required to use IntentService:
1. Write Constructor
2. Implement the onHandleIntent virtual function and perform different Transaction Processing Based on the Intent.
Benefits: when processing asynchronous requests, you can reduce the workload of writing code and easily implement project requirements.
Note: The constructor of IntentService must be a constructor with null parameters (otherwise, an exception will be reported during initialization of the constructor without null parameters), and then super ("name") will be called ") the name of the constructor in this form is written to our programmers and has no practical significance. We only need to give him a string. Generally, we will pass its name as a parameter.

According to the above description, we can know that we can process time-consuming operations in this service. We only need to put the operations we want to process in the onHandleIntent method for processing. IntentService is easy to use. Others are the same as normal services.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.