Android 應用自啟動

如何實現(xiàn)開機自啟動?

1 添加廣播類

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

    /**
     * 給客戶留一些時間去進行系統(tǒng)設置
     */
    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 命令方式發(fā)送開機廣播

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

兼容性

小米8 MIUI 11.0.3.0 (Android9.0)開機后1分多,成功自啟動

注意事項

沒有自啟動的原因:
1 沒有添加權限
2 應用安裝到了sd卡內(nèi),安裝在sd卡內(nèi)的應用是收不到BOOT_COMPLETED廣播的
3 手機上有管理自啟動的軟件會導致失敗

源碼

下方留言、簡信或者發(fā)郵件給我喲

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容