背景:写了个demo,实现开机之后自动启动应用程序。总是报错,程序已停止响应。
实现步骤:先列一下正确的实现步骤。
1. 实现自己的BroadcastReceiver。
package com.chanryma.servicedemo.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.chanryma.servicedemo.activity.MainActivity; public class BootDoneReceiver extends BroadcastReceiver { private static final String TAG = "BootDoneReceiver"; private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "BootDoneReceiver onReceive action=" + intent.getAction()); if (ACTION_BOOT.equalsIgnoreCase(intent.getAction())) { Intent myIntent = new Intent(context, MainActivity.class); myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(myIntent); } } }
2. 在AndroidManifest.xml中注册自己的receiver。
<receiver android:name="com.chanryma.servicedemo.receiver.BootDoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3. 在AndroidManifest.xml中添加权限。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
要点:
在onReceive方法中启动Activity的时候,要用下面的方法添加一个flag。
<span style="color:#ff0000;">myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);</span>
如果没有设置Intent.FLAG_ACTIVITY_NEW_TASK,最终看到的就是程序停止响应。要是连着Eclipse,能看到logcat中生成的异常消息。如下:
04-22 22:58:23.759: E/AndroidRuntime(3326): FATAL EXCEPTION: main
04-22 22:58:23.759: E/AndroidRuntime(3326): java.lang.RuntimeException: Unable to start receiver com.chanryma.servicedemo.receiver.BootDoneReceiver: android.util.AndroidRuntimeException: <span style="color:#ff0000;">Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag</span>. Is this really what you want?
04-22 22:58:23.759: E/AndroidRuntime(3326): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2448)
...
...
04-22 22:58:23.759: E/AndroidRuntime(3326): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
04-22 22:58:23.759: E/AndroidRuntime(3326): at android.app.ContextImpl.startActivity(ContextImpl.java:1277)
...
...
自己在写的时候,想当然了,忽略了设置flag的步骤,花了些时间。