原理:Android系統在開機的時候會發出一個廣播。這樣我們就可以接收這個廣播,然後 啓動我們的應用。廣播接收器必須在xml裏面配置,因爲xml裏面配置的廣播接收器 是不隨着應用的退出而退出的。
廣播接收器:
package com.yangshidesign.boot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, UnityPlayerNativeActivity.class);
//這個必須添加flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
在manifest的application標籤裏面配置:
<!-- 開機啓動 -->
<receiver android:name="com.yangshidesign.boot.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
加上權限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
這樣就可以了。
我用的是 紅米note 測試的,要煩煩的設置一番:
點擊 設置 》應用》找到你的應用》點擊,拉到底下的 權限管理》自動啓動》完成。