Android开机自启动服务的实现方法
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>