我不知道为什么你的闹钟会被多次呼叫。我可以假设你可能多次设置了警报。您可以使用
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;
}
}