import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootReceiver extends BroadcastReceiver { //当手机重启会执行这个方法 @Override public void onReceive(Context context, Intent intent) { //开启mainActivity Intent intent2 = new Intent(context,MainActivity.class); //☆ 如果在广播里面开启Activity 要设置一个任务栈环境 intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //在广播接收者里面开启activity context.startActivity(intent2); } }
<receiver android:name="com.itheima.bootreceiver.BootReceiver"> <intent-filter > <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>
09-08 03:26:15.926: E/AndroidRuntime(1152): java.lang.RuntimeException: Unable to start receiver com.itheima.bootreceiver.BootReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?