静态注册方法

开机广播接收

1. 自定义广播接收器

  1. public class BootReceiver extends BroadcastReceiver {
  2. private SharedPreferences config;
  3. // 在该方法内实现业务逻辑
  4. public void onReceive(Context context, Intent intent) {
  5. config = context.getSharedPreferences("config", 0);
  6. if(config.getBoolean("firstBOOT", false)){
  7. config.edit().putBoolean("receivedBOOT",true).commit();
  8. Log.d(AppGlobal.logHead, "Received the broadcast of android.intent.action.BOOT_COMPLETED");
  9. Toast.makeText(context, "检测到开机", Toast.LENGTH_SHORT).show();
  10. // 拉起MainActivity
  11. Intent bootIntent = new Intent(context, MainActivity.class);
  12. bootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  13. context.startActivity(bootIntent);
  14. }
  15. }
  16. };

2. Manifest文件注册

  • 接收器注册
  1. <!-- 开机广播接收器-->
  2. <receiver android:name="com.chu.miniproject.BootReceiver"
  3. android:enabled="true"
  4. android:exported="true">
  5. <intent-filter>
  6. <action android:name="android.intent.action.BOOT_COMPLETED"/>
  7. <!-- <action android:name="android.intent.action.REBOOT" />-->
  8. <!-- <action android:name="android.intent.action.ACTION_SHUTDOWN" />-->
  9. <category android:name="android.intent.category.HOME"/>
  10. </intent-filter>
  11. </receiver>

注释掉的两行为重启广播和关闭广播,与开机广播接收同权限(好像是?)

  • Permission注册
  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Permission中文文档

开机启动activity

见上文

开机启动service

  1. context.startService(aIntent);

开机启动悬浮窗

开机启动service,service内拉起悬浮窗 (未尝试)

  • 悬浮窗权限
    手机设置内打开: 在其他应用上层显示

开机启动对话框

  • 普通对话框设计

AlertDialog(对话框)详解

对话框API

  • 路线一:对话框注册为系统级 failed
  • 路线二:对话框样式的Activity 参考博客

坑点

App安装后至少需要启动一次才能接收到开机广播 (避免恶意软件)

有些手机静态注册后还需要设置打开允许开机自启动

手机开机后开机广播可能不止发送一次 (需要避免多次启动)

安装在SD卡中的应用接收不到开机广播

动态注册方法 doing

测试 —— adb 发送开机广播 failed

失败原因 permission denied

开机广播

  1. adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

自定义广播

  1. adb shell am broadcast -a 广播名 包名

权限获取 failed

  1. adb root