如果希望android裝置一開機時,就能執行某支程式,無論是activity或是service,流程大致如下:
(1) 需要一個BroadcastReceiver
(2) AndroidManifest.xml對這個Receiver定義intent filter去接收android.intent.action.BOOT_COMPLETED
(3) 在AndroidManifest.xml宣告擁有權限android.permission.RECEIVE_BOOT_COMPLETED
(4) 當Recevier收到intent後,去執行activity或是service
一開就就執行某service 的程式範例如下:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.testboot"
android:versionCode="1"
android:versionName="1.0" >
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".util.CommonReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".service.UpdaterInitService"/>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Receiver程式如下:
public class CommonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent startIntent = new Intent();
startIntent.setClass(context, TestService.class);
context.startService(startIntent);
}
}
}
如此一來,開機時系統會broadcast intent "ACTION_BOOT_COMPLETED",我們的Receiver一收到,就會啟動一條TestService
(1) 需要一個BroadcastReceiver
(2) AndroidManifest.xml對這個Receiver定義intent filter去接收android.intent.action.BOOT_COMPLETED
(3) 在AndroidManifest.xml宣告擁有權限android.permission.RECEIVE_BOOT_COMPLETED
(4) 當Recevier收到intent後,去執行activity或是service
一開就就執行某service 的程式範例如下:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.testboot"
android:versionCode="1"
android:versionName="1.0" >
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".util.CommonReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".service.UpdaterInitService"/>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Receiver程式如下:
public class CommonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent startIntent = new Intent();
startIntent.setClass(context, TestService.class);
context.startService(startIntent);
}
}
}
如此一來,開機時系統會broadcast intent "ACTION_BOOT_COMPLETED",我們的Receiver一收到,就會啟動一條TestService
沒有留言:
張貼留言