静态注册方法
开机广播接收
1. 自定义广播接收器
public class BootReceiver extends BroadcastReceiver {
private SharedPreferences config;
// 在该方法内实现业务逻辑
public void onReceive(Context context, Intent intent) {
config = context.getSharedPreferences("config", 0);
if(config.getBoolean("firstBOOT", false)){
config.edit().putBoolean("receivedBOOT",true).commit();
Log.d(AppGlobal.logHead, "Received the broadcast of android.intent.action.BOOT_COMPLETED");
Toast.makeText(context, "检测到开机", Toast.LENGTH_SHORT).show();
// 拉起MainActivity
Intent bootIntent = new Intent(context, MainActivity.class);
bootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(bootIntent);
}
}
};
2. Manifest文件注册
- 接收器注册
<!-- 开机广播接收器-->
<receiver android:name="com.chu.miniproject.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<!-- <action android:name="android.intent.action.REBOOT" />-->
<!-- <action android:name="android.intent.action.ACTION_SHUTDOWN" />-->
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
注释掉的两行为重启广播和关闭广播,与开机广播接收同权限(好像是?)
- Permission注册
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
开机启动activity
见上文
开机启动service
context.startService(aIntent);
开机启动悬浮窗
开机启动service,service内拉起悬浮窗 (未尝试)
- 悬浮窗权限
手机设置内打开: 在其他应用上层显示
开机启动对话框
- 普通对话框设计
- 路线一:对话框注册为系统级 failed
- 路线二:对话框样式的Activity 参考博客
坑点
App安装后至少需要启动一次才能接收到开机广播 (避免恶意软件)
有些手机静态注册后还需要设置打开允许开机自启动
手机开机后开机广播可能不止发送一次 (需要避免多次启动)
安装在SD卡中的应用接收不到开机广播
动态注册方法 doing
测试 —— adb 发送开机广播 failed
失败原因 permission denied
开机广播
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
自定义广播
adb shell am broadcast -a 广播名 包名
权限获取 failed
adb root