Shutdown Events in Android

2020-03-02 04:29发布

问题:

Is it possible to intercept a phone shutdown event or perhaps use a different hack around this? I have an always running service that's part of a non-market application which is collecting some analytics data. I'd like to tell the analytics to end session and report, then resume the system shutdown.

I've tried triggering the event from the onDestroy or onShutdown parts of the services, but the phone will shutdown without giving it time to report.

Working around this by making many short sessions based on the activity screens yields non-sensical analytics information that I'd like to avoid.

回答1:

Build a broadcast receiver at catches the ACTION_SHUTDOWN intent.

In the onReceive() method you can accomplish what you are trying to do.

http://developer.android.com/reference/android/content/Intent.html#ACTION_SHUTDOWN



回答2:

You could try registering a Shutwdown hook using the Runitme addShutdownHook(Thread hook) method.

Aditionally the method reference states:

If runFinalizersOnExit(boolean) has been called with a true argument, garbage collection and finalization will take place after all hooks are either finished or have failed. Then the VM terminates.

So, theoretically the VM won't terminate until your thread finish.