模拟Android终止并重启服务 [英] Simulate Android killing and restart service

查看:84
本文介绍了模拟Android终止并重启服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟android杀死并重启我的服务,以测试当我收到空意图时会发生什么以及我需要进行清理/恢复的事情.这可能吗?

I want to simulate android killing and restarting my service to test what happens when I receive a null intent and what I need to do with cleanup / recovery. Is this possible?

public MyService extends Service {
  @Override
  public void onCreate() {
    //Do stuff
  }

  @Override
  public void onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null) {
      //Do stuff for restart
    } else {
      //Do stuff for normal start
      return START_STICKY;
    }
  }


  @Override
  public void onDestroy() {
    //Cleanup that may never be called!
  }
}

注意:我阅读了 how-to-simulate-android-杀死我的进程.答案非常有用!但是我认为我的用例有些不同.

Note: I read how-to-simulate-android-killing-my-process. The answers are very useful! But I think my use case is a bit different.

推荐答案

您可以使用相同的方法来模拟服务终止和重新启动.

You can use the same method for simulating service kill and restart.

启动服务(onStartCommand返回 START_STICKY ),logcat显示:

Started the service (onStartCommand returns START_STICKY), logcat shows:

08-13 11:55:38.649 24159-24159/? D/TAG: onCreate()
08-13 11:55:38.650 24159-24159/? D/TAG: onStartCommand: intent is null? false; flags=0; startId=1

在此阶段,使用以下命令杀死该进程:

At this stage, used the following command to kill the process:

adb shell ps | grep <package name> | awk '{print $2}' | xargs adb shell run-as <package name again> kill

该服务立即重新启动(请注意新的进程ID和intent为null的事实):

The service was restarted immediately (note the new process id and the fact that the intent is null):

08-13 11:55:43.742 24236-24236/? D/TAG: onCreate()
08-13 11:55:43.743 24236-24236/? D/TAG: onStartCommand: intent is null? true; flags=0; startId=2

这篇关于模拟Android终止并重启服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆