How to launch activity on BroadcastReceiver when boot complete on Android

旧巷老猫 提交于 2019-12-01 03:13:03

问题


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?


回答1:


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);
            }
    }

}

And in Manifest declare it..

<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>



回答2:


Try this in manifest file,

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

Make sure also to include the completed boot permission.

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


来源:https://stackoverflow.com/questions/17542286/how-to-launch-activity-on-broadcastreceiver-when-boot-complete-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!