我有totalTime = 1小时,而intervalTime = 5分钟,都是毫秒,
我想在每个时间间隔重复我的GPS设置服务,并且在完成总时间之后,这个重复应该停止。
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent1 = new Intent(C2DMReceiver.this, GPSSetting.class);
PendingIntent pendingIntent = PendingIntent.getService(
C2DMReceiver.this, 0, intent1, 0);
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), intervalTime,
pendingIntent);
那么如何才能阻止这种重复警报?
此致 吉里什
答案 0 :(得分:5)
创建与注册闹钟时相同的PendingIntent
,然后使用AlaramManager.cancel()
取消闹钟。
答案 1 :(得分:4)
如果你已经设置闹钟服务重复一段时间而你想要取消你的服务,那么这个解决方案会帮助你,首先我会在每30秒创建一次重复服务,但是当我按下停止按钮然后它将取消我生成的所有服务。
public void AlarmService_afte30sec()
{
Toast.makeText(this, "Starting Alarm Services", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(this, StartAlarmServices.class);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int sec=30;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sec*1000, pendingIntent);
}
现在我将使用相同的“pendingintent”和“alarmManager”停止/取消此服务,取消此代码将
public void stopservice()
{
alarmManager.cancel(pendingIntent);
}
答案 2 :(得分:2)
您可以将当前系统时间的意外额外值传递为1小时(或任何)。然后,您可以从服务的onBind()事件中检查该值并进行比较。以下是一个例子:
//your code:
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent1 = new Intent(C2DMReceiver.this, GPSSetting.class);
//my code:
intent1.putExtra("end", System.currentTimeMillis() + 3600000); //current time plus 1 hour
//your code:
PendingIntent pendingIntent = PendingIntent.getService(
C2DMReceiver.this, 0, intent1, 0); //You might wanna give PendingIntent.FLAG_UPDATE_CURRENT as flag.
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), intervalTime,
pendingIntent);
然后在onBind()方法中:
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
long end = intent.getLongExtra("end", 0);
if(end <= System.currentTimeMillis()){
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
}
return null;
}
不确定它是否适用于服务,但它适用于BroadcastReceiver。
答案 3 :(得分:0)
您可以通过传递在警报管理器的取消方法中设置时使用的相同待处理意图取消警报:
am.cancel(pendingIntent);