如何實現(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ā)郵件給我喲