测试 START_STICKY 服务

Test START_STICKY service

I have read this answer and it's not useful in my case.

我已经创建了一个简单的服务,它只记录方法名称。我从我的 activity 运行 它并使用

杀死它
adb shell am stopservice -n serviceComponent

onDestroy() 调用服务。现在我已经从 onStartCommand() 返回 Service.START_STICKY;我等待系统重启 服务和它从不重新启动。

这是正确的行为吗?我已经解决了 this 个问题,但找不到可靠的答案。

public class SampleService extends Service {

    private static final boolean LOG = true;

    public static final String CALLER = "sample.service.caller";

    /**
     * called once when service is created.
     */
    @Override
    public void onCreate() {
        super.onCreate();
        if(LOG){
            log("onCreate() -> thread: %s", Thread.currentThread().getName());
        }
    } // onCreate

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(LOG){
            log(">>>>>> onStartCommand()");
        }
        if(LOG){
            log("thread: %s", Thread.currentThread().getName());
        }

        if(LOG){
            log("caller[%s]", intent.getStringExtra(CALLER));
        }

        if(LOG){
            log("<<<<<< onStartCommand()");
        }
        return Service.START_STICKY;
    } // onStartCommand

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(LOG){
            log("onDestroy() -> thread: %s", Thread.currentThread().getName());
        }
        Toast.makeText(this, "destroying", Toast.LENGTH_SHORT).show();
    } // onDestroy


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    } // onBind

    private void log(String format, Object... args){
        Utils.log("SampleService", String.format(format, args));
    } // log

} // SampleService

这是我到目前为止尝试过的方法

START_STICKY 文档:

... if this service's process is killed while it is started...

adb shell am stopservicecontext.stopService(Intent) 实际上并没有终止服务进程,而只是停止服务,同时保留应用程序进程 运行。所以这种情况下系统不会重启服务。

您可以尝试以下操作:创建一个带有 ActivityService 的应用。然后启动 activity,启动服务,并通过从概览屏幕(又名最近菜单)滑动来终止应用程序。您的服务应该重新启动。