通过使用AlarmManager
,Service
您可以实现这一点。在此阅读文档 AlarmManager。
这是设置和删除重复任务警报的代码块
设置闹钟
public void createAlarm() {
ServerDetails serverDetails = new ServerDetails(this);
if (serverDetails.isSettingsOK()) {
Intent i = new Intent(this, MyService.class);
if (PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_NO_CREATE) == null) {
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int interval = 2 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + interval, interval,
pendingIntent);
Log.d("alarm", "alarm set successfully " + interval);
} else {
Log.d("alarm", "alarm already set");
}
}
}
取消闹钟
public void cancelAlarm() {
Intent i = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Log.d("alarm", "alarm cancelled");
}
}
这是警报激活时将在后台运行的服务。
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("service Created", "service created");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doYourTaskHere();
}
private void doYourTaskHere() {
// call here webservice or any other task here which you want to do in every two minutes
}
}