要想在Android系統中實現開機啓動,很簡單,只需要幾個步驟就可以了。
1.定義廣播類
2.Manifest.xml中註冊廣播類
3.添加權限
下面就是具體操作了。
首先,我們來定義廣播類。
創建一個類BootReceiver,使其繼承BroadcastReceiver。
重寫一些必要的Java函數
- package cn.etzmico;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- public class BootReceiver extends BroadcastReceiver {
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
- Log.d("BootReceiver", "system boot completed");
- // context, AutoRun.class
- Intent newIntent = new Intent(context, AutoRun.class);
- /* MyActivity action defined in AndroidManifest.xml */
- newIntent.setAction("android.intent.action.MAIN");
- /* MyActivity category defined in AndroidManifest.xml */
- newIntent.addCategory("android.intent.category.LAUNCHER");
- /*
- * If activity is not launched in Activity environment, this flag is
- * mandatory to set
- */
- newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- /* if you want to start a service, follow below method */
- context.startActivity(newIntent);
- }
- }
- }
AutoRun.class就是程序運行的Activity。
其次,在Manifest.xml中註冊廣播類
- <receiver android:name=".BootReceiver" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </receiver>
最後,再添加上權限就可以了
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
這樣,我們就實現了Android系統的開機自啓動,切勿忘記Manifest.xml中的操作!
資源有兩個,他們本質上是一樣的。程序運行後,把虛擬機或手機之類的移動設備關閉,之後重新啓動;當系統程序加載外幣後,我們的程序就會運行。
如果想隱藏,那麼只需要加上finish();就可以了。我在程序中已經添加了一個System.out,所以finish也不用擔心是否成功,只要看LogCat中是否有Successful就可以了。
有,則成功。
切記要看清時間是否吻合,以免造成不必要的麻煩!