【问题标题】:Android alarmManager gets into loopAndroid alarmManager 进入循环
【发布时间】:2014-12-02 11:39:15
【问题描述】:

我有一项服务,我想每天运行它,因此请检查我的数据库中的一些内容,并在需要时创建通知。 为了每天运行我的服务,我使用了一个alarmManager,它第一次运行良好,但是一旦启动我的服务就会进入无限循环,我知道这是因为alarmManager,因为它只是在什么时候进入循环警报管理器正在启动。这是我的服务代码:

public class MyService extends Service {

...
    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {



        checkMechanicUseer();

        this.stopSelf();


        return START_NOT_STICKY;
    }

    private void checkMechanicUseer() {

    ...

    }




    @Override
    public void onDestroy() {
        super.onDestroy();



        final SharedPreferences settings = getSharedPreferences("MYSETTINGS",0);
        int time = settings.getInt("time",9);



        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();

        calSet.set(Calendar.HOUR_OF_DAY, 9); 
        calSet.set(Calendar.MINUTE, 0);
        calSet.set(Calendar.SECOND, 0);
        calSet.set(Calendar.MILLISECOND, 0); // I want it to trigger at 09:00 am each day

        AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarm.setRepeating(
                alarm.RTC_WAKEUP,
                calSet.getTimeInMillis() ,(1000 * 60 ),
                PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
        ); // I set the (1000 * 60 ) so I can check it with 1 min interval, so I wont need to wait one day for it ... of course I need to change it to (1000 * 60 * 60 * 24)

        Toast.makeText(MyService.this, "Service destroyed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }



}

我想我需要在某个地方取消闹钟,然后再设置一个。但不知道如何或在哪里做

如果我将alarm.setRepeat 更改为alarm.set 如下所示,问题仍然存在:

 alarm.set(
                alarm.RTC_WAKEUP,
                calSet.getTimeInMillis() + (1000 * 60 ),
                PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
        );

【问题讨论】:

    标签: android alarmmanager infinite-loop


    【解决方案1】:

    我认为这是因为您将闹钟设置为过去的日期,首先在 9 点钟响,然后您将闹钟重置为 9 点钟,但这个时间已经过去,所以闹钟立即响起,而您有一个很好的循环。

    检查时间是否过去,如果是,请在日历中添加一天。

    【讨论】:

    • 这就是问题所在,谢谢。但是让我说,如果我将间隔设置为 (1000*60*60*24),并设置 cal 小时、分钟、秒和毫秒,则第二个代码(仅使用 alarm.set 将起作用,因为它会提高@Jivy 发现的问题。
    • 这对我来说也是个问题。我检查时间是否过去的函数中有一个逻辑错误,这使 AlarmManager 进入一个循环,其中警报大约每 4 秒触发一次。您可以查看使用adb shell dumpsys alarm 安排警报的时间,并使用-a 标志查找您的应用名称以获取后面的行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多