Android設定軟體開機自啟動
阿新 • • 發佈:2019-01-11
背景知識:當Android啟動時,會發出一個系統廣播,內容為ACTION_BOOT_COMPLETED,它的字
符串常量表示為 android.intent.action.BOOT_COMPLETED。只要在程式中“捕捉”到這個訊息,再啟動之
即可。
首先在清單檔案的manifest的節點下配置許可權
<?xml version="1.0" encoding="utf-8"?> <!-- 這是一個開機自啟動程式 --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ajie.bootstartdemo" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".BootStartDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".BootBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME" /> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> </manifest>
該節點向系統註冊了一個receiver,子節點intent-filter表示接收android.intent.action.BOOT_COMPLETED訊息,並且還要配置android.permission.RECEIVE_BOOT_COMPLETED許可權
自定義一個類BootBroadcastReceiver繼承BroadcastReceiver,在onReceiver中進行開啟頁面
接收廣播訊息:BootBroadcastReceiver.java
public class BootBroadcastReceiver extends BroadcastReceiver { static final String action_boot="android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(action_boot)){ Intent ootStartIntent=new Intent(context,BootStartDemo.class); ootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(ootStartIntent); } } }
介面Activity,BootStartDemo.java檔案
public class BootStartDemo extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 無title requestWindowFeature(Window.FEATURE_NO_TITLE); // 全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); new Thread() { public void run() { try { /* 10秒後關閉頁面*/ sleep(10000); } catch (Exception e) { e.printStackTrace(); } finally { finish(); // 關閉頁面 } } }.start(); } }