AlarmManager经常执行任务

时间:2018-02-05 12:17:42

标签: android task alarmmanager repeat

功能的目标是执行将app-database的所有条目中的值设置为0的任务。 任务应该在每天午夜执行(或者第一次电话在当天被唤醒(如果我正确理解AlarmManager.RTC))。 问题是该任务每天执行几次而不是一次。

在MainActivity的onCreate中:

// Calendar with timestamp midnight
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

// initiate Alarm to reset commits @ midnight
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);

包含已执行代码的类:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent)
    {
        ContentValues APValues = new ContentValues();
        APValues.put(APEntry.AP_DAILY_COMMIT, 0);

        int rowsUpdated = context.getContentResolver().update(APEntry.CONTENT_URI, APValues, null, null);
        if (rowsUpdated == 0) {
            Toast.makeText(context, "Resetting commits failed!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Reset commits successful!", Toast.LENGTH_SHORT).show();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定为什么多次调用你的闹钟。我可以假设您可能多次设置闹钟。您可以使用SharedPreferences检查是否已过去1天。所以,你的代码看起来像这样:

public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (dayElapsed(context))
        {
            ContentValues APValues = new ContentValues();
            APValues.put(APEntry.AP_DAILY_COMMIT, 0);

            int rowsUpdated = context.getContentResolver().update(APEntry.CONTENT_URI, APValues, null, null);
            if (rowsUpdated == 0)
            {
                Toast.makeText(context, "Resetting commits failed!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(context, "Reset commits successful!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean dayElapsed(Context context)
    {
        String lastUpdateTimeKey = "dayElapsed";
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        long lastUpdateTime = sharedPrefs.getLong(lastUpdateTimeKey, -1);
        long currentMillis = System.currentTimeMillis();
        long oneDayMillis = TimeUnit.DAYS.toMillis(1);
        long timeElapsed = currentMillis - lastUpdateTime;

        if (lastUpdateTime < 0 || timeElapsed >= oneDayMillis)
        {
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putLong(lastUpdateTimeKey, currentMillis);
            editor.commit();

            return true;
        }

        return false;
    }
}