0

我已经创建了启动警报,如下所示

 public class MyScheduleReceiver extends BroadcastReceiver {

   // Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 5;

@Override
public void onReceive(Context context, Intent intent) {
  AlarmManager service = (AlarmManager) context
    .getSystemService(Context.ALARM_SERVICE);
 Intent i = new Intent(context, MyStartServiceReceiver.class);
 PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
    PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
    cal.getTimeInMillis(), REPEAT_TIME, pending);

我将此用于停止警报,并从主要活动中调用它。我认为清单没问题...工作重复但没有停止!

      public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setup);

    sendBroadcast(new Intent(this,MyScheduleReceiver.class));

}

public void StopRepeat(View view) {

    sendBroadcast(new Intent(this,MyStopReceiver.class));   

}

 public class MyStartServiceReceiver extends BroadcastReceiver {


 public void onReceive(Context context, Intent intent) {

  Toast.makeText(context, "Repeat service!.",
           Toast.LENGTH_LONG).show();
    }

  public class MyStopReceiver extends BroadcastReceiver {

  // Restart service every 30 seconds
  private static final long REPEAT_TIME = 1000 * 5;

  @Override
  public void onReceive(Context context, Intent intent) {
    AlarmManager service = (AlarmManager) context
        .getSystemService(Context.ALARM_SERVICE);
    Intent istop = new Intent(context, MyStartServiceReceiver.class);
    PendingIntent pending = PendingIntent.getBroadcast(context, 0, istop,
        PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 5);

      service.cancel(pending);

但服务并没有停止。可能是什么问题?谢谢。

4

1 回答 1

0

最简单的选择是重新启动您的设备。(如果您创建了一个BOOT_COMPLETED侦听器,请暂时将其删除。)

您还可以通过将用于创建警报的 PendingIntent 传递给 来取消警报AlarmManager#cancel()。您已经编写了执行此操作的代码,但是您有一个带有 XML 属性的 Buttonandroid:onClick="StopRepeat"setup.xml?你点击了吗?


解决方案
我们最终发现您的 Manifest 文件中有错误,因此MyStopServiceReceiver从未调用...

于 2013-01-13T18:28:20.717 回答