当前位置:   article > 正文

Android 开机自动启动程序_android 开机自启动

android 开机自启动

最近开发项目遇到一个需求,那就是将开发的程序设置成主程序,让Android系统一启动就运行该程序,接下来让我们来实现一下:

我所开发的安卓系统是 Android 12

  1. 我们先在AndroidManifest文件中加入所需要的权限:

	<!--  为程序的用户权限添加接收系统启动完成广播的权限  -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!--  允许出现在其他应用上的权限  -->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 自定义一个开机自启的一个广播接收器:
    定义一个类,让他继承 BroadcastReceiver

public class BootReceiver extends BroadcastReceiver {
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            Intent ootStartIntent = new Intent(context, MainActivity.class);
            ootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ootStartIntent);
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  1. 在AndroidManifests文件中进行注册:
<receiver
    android:enabled="true"
    android:name="com.example.action.BootReceiver"
    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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

最后,我们还需要在代码中判断一下是不是已经有权限:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
	 if (!Settings.canDrawOverlays(this)) {
	         Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
	         intent.setData(Uri.parse("package:" + getPackageName()));
	         startActivityForResult(intent, 0);
	     }
	 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Settings.canDrawOverlays(this)方法是在API level 23也就是Android M中新加入的用于检查当前是否拥有出现在“出现在其他应用上”权限的方法。在6.0以前的系统版本,悬浮窗权限是默认开启的,直接使用即可。

注意:
我们要先运行一遍,把该有的权限都给了然后关机后才能重启。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/712838
推荐阅读
相关标签
  

闽ICP备14008679号