public class RepeatTaskScheduler extends BroadcastReceiver {
public static final String ACTION = "com.yourcompanyname.appname.action.RepeatTaskSchedule";
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION.equals(action)) {
checkEvent();
}
}
}
//在你想要的地方启动
public class YourActivity extends Activity{
@Override
public void onCreate() {
super.onCreate();
//如果interval的值太大会失效,几个小时没问题
setRepeatTasks(1000, 1000 * 30);
}
private void setRepeatTasks(long triggerTime, long interval) {
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(RepeatTaskScheduler.ACTION);
//系统中如果有这个pendingIntent 取消
PendingIntent pending = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_NO_CREATE);
if (pending != null) {
am.cancel(pending);
}
pending = PendingIntent.getBroadcast(this, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, triggerTime, pending);
am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, interval, pending);
}
}
在AndroidManifest.xml中加入
<receiver android:name=".RepeatTaskScheduler">
<intent-filter>
<action android:name="com.yourcompanyname.appname.action.RepeatTaskSchedule" />
</intent-filter>
</receiver>
代码我没测试过,只介绍思路,有问题留言