Android 02 Started Service -- Started Service

Source: Internet
Author: User

 

Body

 

 

1 Started Service Introduction

Started Service, that is, the Started Service. It is one of two common services, and the other is Bound Service. Started Service is often used to perform background operations of a process, such as file downloading through this Service.

Steps and usage

(01) create a Started Service class that inherits from the Service.

(02) implement the following interfaces in the Started Service class:
OnStartCommand (): required! Start the functions provided by the Service. For example, if the service downloads files in the background, a new Thread is enabled in the function to implement the download function in the Thread. When you start a function through startService (), the system automatically executes the onStartCommand () function of the service.
OnBind (): required! Return null. OnBind () is a function used in the Bound Service. onBind () is not executed in the Started Service, but must be implemented because onBind () is a Service class.
.
OnCreate (): You do not need to implement it, depending on your needs. When a service is created, the system automatically calls this function. Initialization is generally performed in this function, for example, creating a thread.
OnDestroy (): You do not need to implement it, depending on your needs. When a service is destroyed, the system automatically calls this function. In this function, purge the job, for example, terminate and recycle the thread.

(03) The client starts the service through startService.

(04) The client ends the service through endService.

The following is an example of how to implement the "Started Service.

2 Service example

Use Service to implement the example in "Android IntentService", that is, to write an activity, which contains two buttons and one progress bar. The two buttons are the start button and the end button respectively. Click Start. The progress bar starts loading. the start button changes to restart. The end button is displayed. (by default, the end button is hidden ).

BaseServiceTest includes two main classes:

StartServiceImpl. java-- Service subclass. When the service is started, it creates a new thread, adds a number + 2 every ms, and sends it through broadcast.

StartServiceTest. java-- Call the Activity of StartServiceImpl.

The content of StartServiceImpl. java is as follows::

Package com. skywang. service; import android. OS. IBinder; import android. app. service; import android. content. intent; import android. util. log; import java. lang. thread;/*** @ desc service: send a number + 2 every MS and broadcast the number * @ author skywang **/public class StartServiceImpl extends Service {private static final String TAG = skywang --> StartServiceImpl; // action private static final String COUNT_ACTION = com. skywan G. service. startservice. COUNT_ACTION; // thread: used to send broadcast private static CountThread mCountThread = null every ms; // The index private static int index = 0; @ Override public void onCreate () {Log. d (TAG, onCreate); super. onCreate () ;}@ Override public void onDestroy () {Log. d (TAG, onDestroy); // terminate the service if (mCountThread! = Null) {mCountThread. interrupt (); mCountThread = null;} super. onDestroy () ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {Log. d (TAG, onStartCommand); // when the service is not running for the first time, perform the following operations // The purpose is to set the index to 0 if (mCountThread! = Null) {Log. d (TAG, mCountThread! = Null); index = 0; return START_STICKY;} Log. d (TAG, start thread); // create and start the thread mCountThread = new CountThread (); mCountThread at the first run. start (); return START_STICKY;} @ Override public IBinder onBind (Intent intent) {Log. d (TAG, onBind); return null;} private class CountThread extends Thread {@ Override public void run () {index = 0; try {while (true) {// send the number + 2, index + = 2; // send the index to Intent through broadcast Intent = new Intent (COUNT_ACTION); intent. putExtra (count, index); sendBroadcast (intent); // Log. d (TAG, CountThread index: + index); // if the number is greater than or equal to 100, exit if (index> = 100) {if (mCountThread! = Null) {mCountThread = null;} return;} // modify 200 ms this. sleep (100) ;}} catch (InterruptedException e) {e. printStackTrace ();}}}}
The content of StartServiceTest. java is as follows:

 

Package com. skywang. service; import android. OS. bundle; import android. app. activity; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. view. view; import android. widget. button; import android. widget. progressBar; import android. util. log; public class StartServiceTest extends Activity {private static final String TAG = skywang --> StartServiceTest; private static final String COUNT_ACTION = com. skywang. service. startservice. COUNT_ACTION; private CurrentReceiver mReceiver; private Button mStart = null; private Button mStop = null; private Intent mIntent = null; private Intent mServiceIntent = null; private ProgressBar mProgressBar = null; @ Override protected void onCreate (Bundle savedInstanceState) {su Per. onCreate (savedInstanceState); setContentView (R. layout. start_service_test); mStart = (Button) findViewById (R. id. start); mStart. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View arg0) {Log. d (TAG, click start button); // display the "end" button mStop. setVisibility (View. VISIBLE); // rename the start button to the restart button mStart. setText (R. string. text_restart); // start the service to update the progress if (mServiceIntent = null) MServiceIntent = new Intent (com. skywang. service. startService); startService (mServiceIntent) ;}}); mStop = (Button) findViewById (R. id. stop); mStop. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View view) {Log. d (TAG, click stop button); if (mServiceIntent! = Null) {// end the service. StopService (mServiceIntent); mServiceIntent = null ;}}); mStop. setVisibility (View. INVISIBLE); mProgressBar = (ProgressBar) findViewById (R. id. pbar_def); // hide the progress bar mProgressBar. setVisibility (View. INVISIBLE); // Dynamic Registration listening COUNT_ACTION broadcast mReceiver = new CurrentReceiver (); IntentFilter filter = new IntentFilter (); filter. addAction (COUNT_ACTION); this. registerReceiver (mReceiver, filter) ;}@ Override publi C void onDestroy () {super. onDestroy (); if (mIntent! = Null) stopService (mIntent); if (mReceiver! = Null) this. unregisterReceiver (mReceiver);}/*** @ desc update progress bar * @ param index */private void updateProgressBar (int index) {int max = mProgressBar. getMax (); if (index <max) {mProgressBar. setProgress (index); mProgressBar. setVisibility (View. VISIBLE);} else {// hide the progress bar mProgressBar. setVisibility (View. INVISIBLE); // hide the "end" button mStop. setVisibility (View. INVISIBLE); // rename the "restart" button to the "Start" button mStart. setText (R. string. text_start);} // Log. d (TAG, progress: + mProgressBar. getProgress () +, max: + max);}/*** @ desc broadcast: Listen to COUNT_ACTION and obtain the index value, update the progress bar * @ author skywang **/private class CurrentReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String action = intent. getAction (); if (COUNT_ACTION.equals (action) {int index = intent. getIntExtra (count, 0); updateProgressBar (index );}}}}
The content of the layout file start_service_test.xml is as follows:
 
         
  
   
                   
    
  
 
The manifest content is as follows:
 
     
                          
                                   
                
    
                           
               
                                
            
       
  
 

 

Click to download: Source code

:

3. Additional instructions

In the example, We customize the onStartCommand () return value. The Android API documentation describes its return values. There are four types:

START_STICKY

If the service process is killed, the service State is retained to the starting state, but the intent object to be delivered is not retained. Then the system will try to re-create the service. Because the service status is starting, the onStartCommand (Intent, int, int) method will be called after the service is created. If no startup command is passed to service during this period, the Intent parameter is null.

START_NOT_STICKY

Non-viscous ". When this return value is used, if the service is kill abnormally after onStartCommand is executed, the system will not automatically restart the service.

START_REDELIVER_INTENT

Intent. When this return value is used, if the service is kill abnormally after onStartCommand is executed, the system automatically restarts the service and passes in the Intent value.

START_STICKY_COMPATIBILITY

START_STICKY compatible version, but it is not guaranteed that the service will be restarted after it is killed.



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.