使用場景:手機開機后,自動運行程序,在屏幕上顯示”Hello. I started!”字樣。
背景知識:當 Android 啟動時,會發出一個系統廣播,內容為 ACTION_BOOT_COMPLETED,它的字符串常量表示為 android.intent.action.BOOT_COMPLETED。只要在程序中“捕捉”到這個消息,再啟動之即可。記住,Android 框架說:Don”t call me, I”ll call you back。我們要做的是做好接收這個消息的準備,而 實現的手段就是實現一個 BroadcastReceiver。
代碼解析:
1、界面 Activity:SayHello.java
public class SayHello extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello. I started!"); setContentView(tv); } }這段代碼很簡單,當 Activity 啟動時,創建一個 TextView,用它顯示”Hello. I started!”字樣。
2、接收廣播消息:BootBroadcastReceiver.java
public class BootBroadcastReceiver extends BroadcastReceiver { static final String ACTION = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION)){ Intent sayHelloIntent=new Intent(context,SayHello.class); sayHelloIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(sayHelloIntent); } } }該類派生自 BroadcastReceiver ,覆載方法 onReceive 中,檢測接收到的 Intent 是否符合 BOOT_COMPLETED,如果符合,則啟動 SayHello 那個 Activity。
3、配置文件:AndroidManifest.xml
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <receiver android:name=".BootBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>android.intent.action.BOOT_COMPLETED 消息。不要忘記配置 android.permission.RECEIVE_BOOT_COMPLETED 權限。 完成后,編譯出 apk 包,安裝到模擬器或手機中。關機,重新開機。 如果是系統進程的話,需要加入 init 配置文件來啟動,隨著 linux 啟動而啟動
新聞熱點
疑難解答