本文實例講述了Android編程實現開機自動運行的方法。分享給大家供大家參考,具體如下:
有些時候,應用需要在時就運行,例如某個自動從網上更新內容的后臺service。怎樣實現開機自動運行的應用?在撰寫本文時,聯想到高煥堂先生以“Don''t call me, I''ll call you back!”總結框架,真是說到點子上了。理解這句話的含義,許多有關Android平臺上實現某種的問題,都能迎刃而解。
使用場景:開機后,自動運行,在上顯示"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
package com.ghstudio.BootStartDemo;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class SayHello extends Activity {@Overridepublic 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
package com.ghstudio.BootStartDemo;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class BootBroadcastReceiver extends BroadcastReceiver {static final String ACTION = "android.intent.action.BOOT_COMPLETED";@Overridepublic 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
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com//res/android"package="com.ghstudio.BootStartDemo"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"><activity android:name=".SayHello"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" /></intent-filter></receiver></application><uses-sdk android:minSdkVersion="3" /><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。
完成后,編譯出apk包,安裝到模擬器或手機中。關機,重新開機。
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android視圖View技巧總結》、《Android布局layout技巧總結》、《Android調試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答