Android 应用自启动

2019-10-24  本文已影响0人  路Promenade

如何实现开机自启动?

1 添加广播类

public class BootReceiver extends BroadcastReceiver {
    private static final String TAG = "BootReceiver";
    public static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";

    /**
     * 给客户留一些时间去进行系统设置
     */
    private static final int START_TIME = 3000;

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.i(TAG, "开启了" + intent.getAction());
        String action = intent.getAction();
        if (null == action)
            return;
        if (action.equals(ACTION_BOOT)) {
            // 10秒后进行自启动
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startApp(context);
                }
            }, START_TIME);
        }
    }

    /**
     * 开启APP
     */
    private void startApp(Context context) {
        Toast.makeText(context, "已开机", Toast.LENGTH_SHORT).show();
        context.startActivity(context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName()));
    }
}

2 清单文件中添加权限及注册广播

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lugq.powerbootdemo">

    <!-- 1. 添加权限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        ...

        <!-- 2 注册广播 完事 -->
        <receiver android:name="com.lugq.powerbootdemo.receiver.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

开机自启动验证

使用 adb 命令方式发送开机广播

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

兼容性

小米8 MIUI 11.0.3.0 (Android9.0)开机后1分多,成功自启动

注意事项

没有自启动的原因:
1 没有添加权限
2 应用安装到了sd卡内,安装在sd卡内的应用是收不到BOOT_COMPLETED广播的
3 手机上有管理自启动的软件会导致失败

源码

下方留言、简信或者发邮件给我哟

上一篇 下一篇

猜你喜欢

热点阅读