要想在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就可以了。
有,則成功。