Turn: Android startService in use and Service Lifecycle

Android There are two main ways to use Service, by calling the method Context startService or call bindService method of Context, we only investigate the use of pure startService does not involve any case bindService method invocation . If you want to know bindService related use, see "Android in bindService use and Service Life Cycle" .

When we startService by calling the Context method, we will start the Service, initiated by the Service startService method will always run indefinitely, stopService only internal or external calls Service calls stopSelf method Service Context of the Service It will stop running and destroyed.

To use the Service, we need to inherit from Service, and then rewritten as follows:
the onCreate, onStartCommand, onBind and onDestroy.

These methods are callback methods are invoked by the Android operating system at the right time, and to note that these callback methods are invoked in the main thread.

onCreate : startService execution method, if the Service is not running when the Service will create and execute a callback method onCreate of Service; if Service is already in operation, the execution startService method does onCreate method Service. This means that if the method repeatedly performed startService Context starting onCreate method Service, Service method is invoked only when you first create the Service once and will not be called again. We can do some initialization Service related operations in onCreate method.

onStartCommand : After executing startService method, there may call onCreate method of the Service, after which you will perform onStartCommand callback method Service. That is, if performed repeatedly startService method Context, then onStartCommand Service will be a corresponding method of multiple calls. onStartCommand method is very important that we carry out the actual operations in the method according to the incoming Intent parameters, such as a thread is created here for downloading data or playing music.

onBind : Service onBind method is an abstract method, the Service class itself is an abstract class, which is onBind method must be overridden, even if we have no use. When using the Service by startService, when we rewrite onBind method, and need to be returned to null. onBind method is mainly used to bindService will be used when the method call Service.

onDestroy : Start by startService method Service will run indefinitely, only when calls stopService Context of the Service or call stopSelf methods inside, Service will stop running and destroyed, when the destruction will perform the Service callback function.

We started to explore the life cycle Service by startService method to verify the above description of the function of each callback method, I wrote the following in a test case.
First, create a service class TestService, the class inherits from Service, the following code:

package com.ispring.startservicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class TestService extends Service {

    @Override
    public void onCreate() {
        Log.i("DemoLog","TestService -> onCreate, Thread ID: " + Thread.currentThread().getId());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("DemoLog", "TestService -> onStartCommand, startId: " + startId + ", Thread ID: " + Thread.currentThread().getId());
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("DemoLog", "TestService -> onBind, Thread ID: " + Thread.currentThread().getId());
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i("DemoLog", "TestService -> onDestroy, Thread ID: " + Thread.currentThread().getId());
        super.onDestroy();
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

We simply print TestService each callback method in the appropriate information, and did not do a lot of complex processing operations.

Then we call the Serivce in the Activity, Activity in the corresponding code is as follows:

package com.ispring.startservicedemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i("DemoLog", "Thread ID: " + Thread.currentThread().getId());

        Log.i("DemoLog", "before test startService");

        //连续启动Service
        Intent intent1 = new Intent(this, TestService.class);
        startService(intent1);
        Intent intent2 = new Intent(this, TestService.class);
        startService(intent2);
        Intent intent3 = new Intent(this, TestService.class);
        startService(intent3);

        //停止Service
        Intent intent4 = new Intent(this, TestService.class);
        stopService(intent4);

        //再次启动Service
        Intent intent5 = new Intent(this, TestService.class);
        startService(intent5);

        Log.i("DemoLog", "after test startService");
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

Activity in our first three consecutive calls startService method to start the Service Activity, and then call the method Activity stopService stop Service, and then start the Service by calling Activity of startService method.

Output from running the program are as follows:
Write pictures described here

We analyze the output of the above, you first print of the main thread ID is 1, then we find all printed in the callback function executing thread behind the ID is 1, which indicates that the individual is the callback method Service run in the main thread. Secondly, we can see that after we called three times in a row startService method, only triggered a callback method onCreate, triggering a three onStartCommand method, in onStartCommand we can read incoming method by startService Intent object, and this three times startId are different and are each 1, 2, each call is automatically assigned a startService startId, startId call can be used to distinguish the different startService, are numbered from 1 startID generally, after each subsequent call startService startID incremented by one increment.

After we called stopService Activity of (intent4) method to stop the Service, through the output we find Service performed onDestroy method, under normal circumstances we can perform some operations in onDestroy resource release method. After executing the instance of the Service on onDestroy destroyed. Although startService method called three times before us, but as long as you can make one call stopService running Service stopped and destroyed.

Finally, when we once again by startService (intent5) Start Service, through the output we find once again the implementation of the method onCreate Service, indicating Service after the destruction by stopService re-created, and subsequently calls the callback method onStartCommand again, and again from startId 1 starts counting.

Finally, note that we operate in the Activity Service at the beginning and end of each output code to write a few words, which are

Log.i("DemoLog", "before test startService");
  
  
  • 1

with

Log.i("DemoLog", "after test startService");
  
  
  • 1

But let's look at the output will be found, the program directly onto the output before test startService later, but immediately output the After the Test startService , is the output TestService inside of each callback method after this, indicating that startService () method and stopService () method returns immediately after the execution, that is, these two methods are not blocking, start the service and stop the service are asynchronous operation, startService (), stopService () are sent to the Android Framework intent objects, Framework layers and then asynchronously start, stop Service.

We use a diagram to summarize by startService start of the life cycle Service:
Write pictures described here

Behavior When Android faces a memory shortage could destroy out Service you are currently running, and then to be memory enough when you can re-create the Service, Service is Android system forces destroyed and rebuilt again depends on the Service in onStartCommand method's return value. We used the return value has three values, START_NOT_STICKY, START_STICKY and START_REDELIVER_INTENT, these three values ​​are Service Static constant.

START_NOT_STICKY: 如果返回START_NOT_STICKY,表示当Service运行的进程被Android系统强制杀掉之后,不会重新创建该Service,当然如果在其被杀掉之后一段时间又调用了startService,那么该Service又将被实例化。那什么情境下返回该值比较恰当呢?如果我们某个Service执行的工作被中断几次无关紧要或者对Android内存紧张的情况下需要被杀掉且不会立即重新创建这种行为也可接受,那么我们便可将 onStartCommand的返回值设置为START_NOT_STICKY。举个例子,某个Service需要定时从服务器获取最新数据:通过一个定时器每隔指定的N分钟让定时器启动Service去获取服务端的最新数据。当执行到Service的onStartCommand时,在该方法内再规划一个N分钟后的定时器用于再次启动该Service并开辟一个新的线程去执行网络操作。假设Service在从服务器获取最新数据的过程中被Android系统强制杀掉,Service不会再重新创建,这也没关系,因为再过N分钟定时器就会再次启动该Service并重新获取数据。

START_STICKY: 如果返回START_STICKY,表示Service运行的进程被Android系统强制杀掉之后,Android系统会将该Service依然设置为started状态(即运行状态),但是不再保存onStartCommand方法传入的intent对象,然后Android系统会尝试再次重新创建该Service,并执行onStartCommand回调方法,但是onStartCommand回调方法的Intent参数为null,也就是onStartCommand方法虽然会执行但是获取不到intent信息。如果你的Service可以在任意时刻运行或结束都没什么问题,而且不需要intent信息,那么就可以在onStartCommand方法中返回START_STICKY,比如一个用来播放背景音乐功能的Service就适合返回该值。

START_REDELIVER_INTENT : If, after the return START_REDELIVER_INTENT, represents the Service processes running Android system is forced to kill, and the situation is similar to the return START_STICKY, Android system will once again re-create the Service, and perform onStartCommand callback method, but the difference is, Android system the last method again onStartCommand Service before being passed in the Intent to kill again preserved and passed to the method Service onStartCommand after the re-created again, so that we can read to the intent parameters. As long as the return START_REDELIVER_INTENT, then onStartCommand weight of intent certainly is not null. If we need to rely on the Service Specific Intent to run (need to read data from Intent-related information, etc.), and it is necessary to re-create destroyed after forced to run, then such Service will return for START_REDELIVER_INTENT.

Related Bowen:
Android by playing background music simple example startService
Android by downloading the sample batch to achieve startService

Forwarding: https: //blog.csdn.net/iispring/article/details/47689819

Guess you like

Origin blog.csdn.net/qq_26369907/article/details/93491727