Android Start App On Boot from BroadcastReceiver Crashing
I am trying to start my Androi开发者_运维技巧d 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>
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.
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);
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);
}
精彩评论