Home

fangxiaogang

我可以!

Home About Github Email

2017-05-19
Android 开机自启动 App

Android 设备开机自启动的可以用广播实现,因为 Android 设备开机时会发送一条开机广播 “android.intent.action.BOOT_COMPLETED”。接收后实现启动就完成了。

少啰嗦,先看核心代码

1
2
3
4
5
6
7
8
9
10
11
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent intent = new Intent(context,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
}
接下来是准备工作
  1. 先添加权限

    1
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  2. 注册常驻广播

1
2
3
4
5
6
7
8
9
10
11
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
可能出现的问题
  • 安装在 SD 卡的应用自启动无效,安装在手机内存就好了。也可在 manifest 里面添加 android:installLocation="internalOnly

  • 忘记加权限了,哈哈这种低级错误有时真的会遇到

  • 需要 App 运行一次后才能实现开机自启


fangxiaogang

scribble

Home About Github Email