我正在使用應用程序中的鬧鐘管理器,並且需要一些DefaultSharedPreferences值在上午2:00重置(設置爲0)。 我有我的主要活動的功能被稱爲每當應用程序是開放的:Android AlarmManager無法正常工作
protected void setUpAlarmManager(){ //To delete the data of each day and pass it to Records database
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 02);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pIntent); //set repeating every 24 hours
Log.i("Set", "Alarm set");
}
然後我用一個BroadcastReceiver重置值。
package com.javierd.iifym;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import com.javierd.iifym.sqlite.RecordsDataSource;
//To delete the data of each day and pass it to Records database
public class AlarmReceiver extends android.content.BroadcastReceiver {
private RecordsDataSource dataSource;
private Utils utils;
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Time", "TIMEEEE!!!!");
SharedPreferences macros = context.getSharedPreferences(context.getPackageName() + "_preferences", Context.MODE_PRIVATE); //As we store data using DefaultSharedPreferences, not SharedPreferences
SharedPreferences.Editor editor = macros.edit();
editor.putString("eaten_carbs", "0");
editor.putString("eaten_proteins", "0");
editor.putString("eaten_fats", "0");
editor.apply();
}
}
接收機工作,問題是AlarmManager隨機工作。雖然它應該只在凌晨2點,也許你在16:00進入應用程序,保存一些值,下次你在17:30輸入值被刪除,或者可能不會,這是隨機的東西我不明白這一點。
如果手機被關閉這將無法正常工作 - 報警消失在重新啓動。 – natario