android實現開機自啟動可能是移動作業系統中最簡單的了,我們只需要監聽一個開機啟動的Broadcast(廣播)即可。首先寫一個Receiver(即廣播監聽器),繼承BroadcastReceiver,如下所示:
view source
print?
複製代碼 代碼如下: public class BootReceiver extends BroadcastReceiver {
private PendingIntent mAlarmSender;
@Override
public void onReceive(Context context, Intent intent) {
// 在這裡幹你想乾的事(啟動一個Service,Activity等),本例是啟動一個定時發送器,每30分鐘啟動一個Service去更新資料
mAlarmSender = PendingIntent.getService(context, 0, new Intent(context,
RefreshDataService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) context
getSystemService(Activity.ALARM_SERVICE);
am.cancel(mAlarmSender);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
30 * 60 * 1000, mAlarmSender);
}
}
接下來,我們只需要在應用程式設定檔AndroidManifest.xml中註冊這個Receiver來監聽系統啟動事件即可,如下所示:
view source
print?
複製代碼 代碼如下: < receiver Android:name=".service.BootReceiver">
< intent-filter>
< !-- 系統啟動完成後會調用-->
< action android:name="Android.intent.action.BOOT_COMPLETED">
< /action>
< /intent-filter>
< /receiver>