Mr. Thanks a lot
Mr. Thanks a lot

Reputation: 235

Detect system reboot from inside a service

Is it possible to detect when a service is stopped or destroyed by one of its own methods? e.g. onDestroy() (not currently working)

What I need is to detect, from inside the service, whenever the device is rebooted or turned off.

Upvotes: 2

Views: 949

Answers (1)

Danny Buonocore
Danny Buonocore

Reputation: 3777

You could create a BroadcastReceiver to listen for the ACTION_SHUTDOWN and QUICKBOOT_POWEROFF intents:

<receiver android:name=".PowerOffReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_SHUTDOWN" />
        <action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
    </intent-filter>
</receiver>

Conversely you can listen for the BOOT_COMPLETED intent for when the phone is back on:

<receiver android:name=".PowerOnReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Keep in mind the latter requires the device to be unlocked by the user first. In newer API, you can listen for LOCKED_BOOT_COMPLETED which will allow you to start your service or do whatever you need before the device is unlocked.

Upvotes: 3

Related Questions