android上怎樣讓一個Service開機自動啟動
阿新 • • 發佈:2019-01-21
1.首先開機啟動後系統會發出一個Standard Broadcast Action,名字叫android.intent.action.BOOT_COMPLETED,這個Action只會發出一次。
2.構造一個IntentReceiver類,重構其抽象方法onReceiveIntent(Context context, Intent intent),在其中啟動你想要啟動的Service。
3.在AndroidManifest.xml中,首先加入<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> 來獲得BOOT_COMPLETED的使用許可,然後註冊前面重構的IntentReceiver類,在其<intent-filter>中加入<action android:name="android.intent.action.BOOT_COMPLETED" /> ,以使其能捕捉到這個Action。
一個例子
xml:
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
- <receiver android: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> <receiver android:name=".OlympicsReceiver" 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>
java:
Java程式碼- publicclass OlympicsReceiver extends IntentReceiver
- {
- /*要接收的intent源*/
- staticfinal String ACTION = "android.intent.action.BOOT_COMPLETED";
- publicvoid onReceiveIntent(Context context, Intent intent)
- {
- if (intent.getAction().equals(ACTION))
- {
- context.startService(new Intent(context,
- OlympicsService.class), null);//啟動倒計時服務
- Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
- }
- }
- }
public class OlympicsReceiver extends IntentReceiver
{
/*要接收的intent源*/
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceiveIntent(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION))
{
context.startService(new Intent(context,
OlympicsService.class), null);//啟動倒計時服務
Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
}
}
}
注意:現在的IntentReceiver已經變為BroadcastReceiver,OnReceiveIntent為onReceive。所以java這邊的程式碼為:
(也可以實現應用程式開機自動啟動) Java程式碼- publicclass OlympicsReceiver extends BroadcastReceiver
- {
- /*要接收的intent源*/
- staticfinal String ACTION = "android.intent.action.BOOT_COMPLETED";
- publicvoid onReceive(Context context, Intent intent)
- {
- if (intent.getAction().equals(ACTION))
- {
- context.startService(new Intent(context,
- OlympicsService.class), null);//啟動倒計時服務
- Toast.makeText(context, "OlympicsReminder service has started!", Toast.LENGTH_LONG).show();
- //這邊可以新增開機自動啟動的應用程式程式碼
- }
- }
- }