Android Start App On Boot from BroadcastReceiver Crashing

坚强是说给别人听的谎言 提交于 2019-12-14 03:59:24

问题


I am trying to start my Android 2.1 Galaxy S Phone on boot and it crashes.

Here is my receiver if I comment out context.startActivity(i) I don't get crash otherwise I see it on powerup. startActivity from another activity using same ACTION does not cause crash. This seems to be just on Boot.

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent();
        i.setAction("DISPLAY_FIRSTPAGE");
        context.startActivity(i);
    }
}

I setup an receiver in the manifest like this:

<receiver android:name=".MyBroadcastReceiver">
             android:enabled="true" android:exported="false"
             android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> 
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter> 
</receiver>

回答1:


Please first look at the log before anything else. In this case the problem (both with your original code and your fixed code) will be pretty clearly explained in the crash in the log.




回答2:


You're clearly not telling it what to launch (unless you specify that your activity handles DISPLAY_FIRSTPAGE intents in the manifest, which wouldn't be a good idea). Try something along the lines of:

Intent i = new Intent(context, MyActivity.class);
context.startActivity(i);



回答3:


This is what worked for me:

    Intent i = new Intent(context, MyService.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(i);
    } else {
        context.startService(i);
    }


来源:https://stackoverflow.com/questions/5331467/android-start-app-on-boot-from-broadcastreceiver-crashing

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