Android alarmManager进入循环

时间:2014-12-02 11:39:15

标签: android alarmmanager infinite-loop

我有一个服务,我想每天运行,所以检查我的数据库中的一些东西,如果需要,创建一个通知。 为了每天运行我的服务,我使用了一个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)
        );

1 个答案:

答案 0 :(得分:1)

我认为这是因为你为过去的日期设置闹钟,首先在9点钟开始闹钟,然后你将闹钟重置为9点,但这次是过去所以警报是立刻开火,你有一个很好的循环。

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