Tuesday, January 28, 2014

Run Android Application On Device Startup

In this example I am going to show how to make your application runs on device startup. All the steps are very easy.

 Create a new Android project using Android Development Tools. Let MainActivity to be
   created by IDE.
 Add following permission in to your Manifest file.

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

Create a BroadcastReceiver class which is going to be informed when device rebooted.
package com.example.startuprunner;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class StartupReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent mainIntent = new Intent(context, MainActivity.class);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mainIntent);
        }
    }

Finally register the receiver in Manifest file.
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity android:name="com.example.startuprunner.MainActivity"
              android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
 
    <receiver android:enabled="true" android:exported="true" android:label="StartupR"
             android:name="com.example.startuprunner.StartupReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>
</application>

No comments:

Post a Comment