6

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!
  }
}

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.

Community
  • 1
  • 1
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80

2 Answers2

3

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

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

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
Alex Lipov
  • 13,503
  • 5
  • 64
  • 87
  • This would pretty much be the accepted answer. Works for me and greatly helped to debug a sticky background service restart. – lnstadrum Sep 16 '21 at 20:11
0

for testing purposes, this works pretty well - it kills your app process after 5 seconds, so your service would be restarted by the system(for START_STICKY, null intent would be delivered):

Handler(Looper.getMainLooper()).postDelayed(
            {
                val pid = android.os.Process.myPid()
                android.os.Process.killProcess(pid)
            },
            5_000L
        )
Lukas
  • 1,216
  • 12
  • 25