Search code examples
androidbroadcastreceiver

How to launch activity on BroadcastReceiver when boot complete on Android


I use below code to let my app can be auto-launch after boot complete 10 seconds:

public class BootActivity extends BroadcastReceiver {
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";   

    public void onReceive(Context context, Intent intent) {   
        if(intent.getAction().equals(ACTION)) {
            context.startService(new Intent(context,    
                    BootActivity.class));
            try {
                Thread.sleep(10000);
                Intent newAct = new Intent();
                newAct.setClass(BootActivity.this, NewActivity.class);
                startActivity( newAct );
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }   
    }   
}  

But the setClass and startActivity cannot use here.
How can I modify to set it to launch activity?


Solution

  • May this help you...

    Create class called AutoStart.class

    public class AutoStart extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
             if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
                    Intent i = new Intent(context, SochActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                }
        }
    

    Manifest file:

    under manifest tag:

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

    Under application tag:

            <receiver
                android:name=".AutoStart"
                android:enabled="true"
                android:exported="true" >
                <intent-filter android:priority="500" >
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>