Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Launch application after phone boot or screen unlock in Android using BroadcastReceiver

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 7.18k
    Comment on it

    We have BroadcastReceiver to listen to the system events. There are receivers like BOOT_COMPLETED, SCREEN_ON, USER_PRESENT which we can register to perform any specific task when phone boots or screen unlocks. The same we are using here to Launch our Android application on phone unlock and boot.

    Firstly, as mentioned above, we have to register the receivers that we want our application to listen to. So we register receivers in AndroidManifest.xml like:

     <receiver
            android:name="com.example.android.ScreenReceiver"
            android:enabled="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.SCREEN_OFF" />
                <action android:name="android.intent.action.SCREEN_ON" />
                <action android:name="android.intent.action.USER_PRESENT" />
    
                <category android:name="android.intent.category.DEFAULT" >
                </category>
            </intent-filter>
    </receiver>
    

    To listen to system's boot event, we need to add a permission in AndroidManifest.xml, that is:

    "android.permission.RECEIVE_BOOT_COMPLETED"

    ScreenReceiver used above is the BroadcastReceiver class.

    After doing these things in Android Manifest.xml, Following is how ScreenReceiver class listens to the events in onReceive() method:

    public class ScreenReceiver extends BroadcastReceiver{
        ScreenReceiver screen;
        Context context=null;
        @Override
        public void onReceive(Context context, Intent intent)
        {
            this.context=context;
            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)||intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)||intent.getAction().equals(Intent.ACTION_USER_PRESENT))
            {
                    Intent i = new Intent(context, MainActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
            }
    }
    }
    

    MainActivity.class above is the activity that will be launched after listening to boot complete and screen unlock broadcast receivers.

    That's just all and simple steps to launch an application on phone's boot and screen unlock. :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: