Android开机自启动

2023-05-16

两种方式:

1、监听开机广播

        优点:不影响其它应用

        缺点:会等其它优先级高的应用或服务启动完成才会收到广播消息(实测需要1分多钟)

2、设置默认桌面

        优点:开机后马上会启动

        缺点:会霸屏,关掉后也会立马重新启动

一、监听开机广播

AndroidManifest.xml里添加:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
    android:name=".receiver.BootReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

广播接收器:

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            if (!getCurrentTask(context)) {
                Intent i = new Intent(context, SplashActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        }
    }

    private boolean getCurrentTask(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appProcessInfos = activityManager.getRunningTasks(Integer.MAX_VALUE);
        for (ActivityManager.RunningTaskInfo process : appProcessInfos) {
            if (process.baseActivity.getPackageName().equals(context.getPackageName())
                    || process.topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}

二、设置默认桌面

1、给程序的LAUNCHER加上如下两个属性:

<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />

2、在系统设置--应用--Launcher3--主屏幕应用,里面把主屏幕应用设置成你的app即可(也可能不是Launcher3,其它可以设置桌面应用的都行)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android开机自启动 的相关文章

随机推荐