Listen to Phone Restarts on Android

When a phone is restarted the system broadcasts ACTION_BOOT_COMPLETED to all the apps that have the RECEIVE_BOOT_COMPLETED permission. In this article, we will learn how to make our app listen to phone restarts.

1) Add permission to the AndroidManifest.xml file.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

2) Create a broadcast receiver and add ACTION_BOOT_COMPLETED intent filter to receive the broadcasts.

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

public class BootCompletedReceiver extends BroadcastReceiver {
    private static final String TAG = BootCompletedReceiver.class.getSimpleName();


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Log.i(TAG, "Boot Completed")
        }
    }
}

That's it, the onReceive is called whenever the device is restarted. We can start the alarms or start a foreground service, JobIntentService, WorkManger for long running tasks. The lifespan of a broadcast receiver is 10 seconds, so, avoid any time consuming tasks in the onReceive method.

There is another broadcast similar to ACTION_BOOT_COMPLETED that notifies the apps that the device is restarted, its called ACTION_LOCKED_BOOT_COMPLETED. There are few differences between both the broadcasts.

When ACTION_LOCKED_BOOT_COMPLETED is broadcasted on 24+ versions, the device is started but the screen is still in the locked state and when ACTION_BOOT_COMPLETED is broadcasted, the device is started and the screen is unlocked by the user.

Until the screen is unlocked (i.e., when ACTION_LOCKED_BOOT_COMPLETED is broadcasted and ACTION_BOOT_COMPLETED is yet to be broadcasted), the apps can only access device protected storage. So, take these limitations into consideration when listening for ACTION_BOOT_COMPLETED and ACTION_LOCKED_BOOT_COMPLETED.

Popular posts from this blog

Arithmetic Operations in Tensorflow

How to Create Facebook App

How to Create Facebook Page