Tuesday, September 10, 2013

Android Tip - Auto-launch your App on Bootup


For corporate applications, it is not uncommon for enterprises to require their specific applicatons to be automatically launched when the device starts up.

To ensure your application is launched automatically upon device bootup, add a new Java Class file to the project and name it as BootupReceiver.java. Populate the BootupReceiver.java class as follows:

package net.learn2develop.autostartup;

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

public class BootupReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "App started",
            Toast.LENGTH_LONG).show();

        //---start the main activity of your app---
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

Add the following statements in bold to the AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.learn2develop.autostartup"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name=
        "android.permission.RECEIVE_BOOT_COMPLETED"/>
   
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name=
                    "android.intent.action.MAIN" />

                <category android:name=
                    "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".BootupReceiver">
            <intent-filter>
                <action android:name=
                   "android.intent.action.BOOT_COMPLETED" />
                <category android:name=
                   "android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
       
    </application>

</manifest>


That’s it! Your application will now be automatically launched when the device has finished the bootup process.

No comments: