Starting Android Activity on device restart

I finally got around to fixing a bug in my Android application, Simple Task Reminder, which was on my to-do list for a long time.The issue was that all reminders set in this application were lost on device restart. The solution was to set reminders again after device rebooted.

Android SDK provides a mechanism to receive notification for your application, after the device is booted. You need to add a broadcast receiver in the manifest file –

<receiver android:name="BootNotificationReceiver" android:exported="false"
    android:label="Boot Notification Receiver" android:enabled="true">

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

Value of android:name attribute above is your class name that extends BroadcastReceiver class. In onReceive function of this class you can start the Activity of your application e.g. –

public class BootNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent mainIntent = new Intent (context, SimpleTaskReminderActivity.class);
        mainIntent.putExtra("refresh_reminders", true);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity (mainIntent);
    }
}

You also need to add RECEIVE_BOOT_COMPLETED user permission in the menifest file-

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

Accessing WebView local DB from Java :

I have used WebView for this application and used local database of the WebView to store tasks. All data access code in WebView is in JavaScript. Initially, I was looking for a way to access this database from Java code in my Activity. I found that you can get path of the database file of WebView as follows –

appView.getSettings().getDatabasePath(); //appView is an instance of WebView.

However I did not end up using this API for refreshing reminders, because I already had all the code in JavaScript to get tasks and format data to schedule reminders. What I ended up doing was starting the Activity that had WebView, execute JavaScript function to re-schedule reminders and then hiding the Activity. Hiding Activity in an Android application is as simple as calling moveTaskToBack method on the activity –

activity.moveTaskToBack(true);

-Ram Kulkarni

2 Replies to “Starting Android Activity on device restart”

  1. You can also use the BootNotificationReceiver to start a tiny IntentService which does nothing else but process your reminders. You can even use that service to process the reminders (call Alarmmanager/Notify) from your main activity.

Leave a Reply