android实现开机自启动可能是移动操作系统中最简单的了,我们只需要监听一个开机启动的Broadcast(广播)即可。首先写一个Receiver(即广播监听器),继承BroadcastReceiver,如下所示:
01 | public class BootReceiver extends BroadcastReceiver { |
02 | private PendingIntent mAlarmSender; |
04 | public void onReceive(Context context, Intent intent) { |
06 | mAlarmSender = PendingIntent.getService(context, 0, new Intent(context, |
07 | RefreshDataService. class ), 0); |
08 | long firstTime = SystemClock.elapsedRealtime(); |
09 | AlarmManager am = (AlarmManager) context |
10 | .getSystemService(Activity.ALARM_SERVICE); |
11 | am.cancel(mAlarmSender); |
12 | am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, |
13 | 30 * 60 * 1000, mAlarmSender); |
接下来,我们只需要在应用程序配置文件AndroidManifest.xml中注册这个Receiver来监听系统启动事件即可,如下所示:
1 | <receiver android:name= ".service.BootReceiver" > |
4 | <action android:name= "android.intent.action.BOOT_COMPLETED" > |