安卓APP开机自启动

1、编写广播接收器AutoStartReceiver

package com.liang.nano;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import org.apache.cordova.LOG;

public class AutoStartReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        LOG.i("AutoStartReceiver","开机启动");
        //开机启动
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent thisIntent = new Intent(context, MainActivity.class);//设置要启动的app
            thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(thisIntent);
        }
    }
}

2、修改AndroidManifest.xml配置

  • 在<manifest>标签添加android:installLocation="internalOnly"属性。

internalOnly:默认值.当设置为该值时,程序只能被安装在内存中,如果内存为空,则程序将不能成功安装。程序如果没有安装在内存中,则接不到广播。

<manifest 
  android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" 
  package="com.liang.nano" xmlns:android="http://schemas.android.com/apk/res/android" 
  android:installLocation="internalOnly">
  • <manifest></manifest>标签内添加权限
    <!--    开机监听-->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!--    悬浮窗-->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  • <application></application>标签内添加receiver
    receiver的android:name对应广播接收类AutoStartReceiver
        <receiver
            android:name="com.liang.nano.AutoStartReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

3、申请悬浮窗权限

修改MainActivity
在public void onCreate(Bundle savedInstanceState)方法内添加

//检查是否已经授予权限,大于6.0的系统适用,小于6.0系统默认打开,无需理会
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
    //没有权限,须要申请权限,由于是打开一个受权页面,因此拿不到返回状态的,因此建议是在onResume方法中重新执行一次校验
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivity(intent);
}

4、启动管理

目前很多手机都自带手机管家或者权限管理,如果出现开机无法自启动的情况,需要到手机的设置里面手动授权。

参考自启动授权设置

测试用机:MI 6
MIUI版本:11.0.5稳定版

操作步骤:手机管家-应用管理-权限-自启动管理-找到对应的app-允许自启动

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容