开机自动启动应用程序

背景:写了个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的步骤,花了些时间。









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值