我有以下方法将三个值保存到intent中,该方法附加到创建的警报。
public static Boolean setUniqueAlarm(Long alarmId, String occurenceTime, Context context) {
Boolean saveResult = null;
try {
DateTime dt = TimeHelper.getDateTimeObject(occurenceTime);
Logger.d("Year: " + dt.getYear() + ", month: " + dt.getYear() + ", day: " + dt.getDayOfMonth() + ", hour: " + dt.getHourOfDay() + ", minute: " + dt.getMinuteOfHour());
Logger.d("Occurrence time to save: "+occurenceTime);
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
// Pass the intent type and other additional values into bundle
Bundle bundle = new Bundle();
bundle.putString(Constants.Global.ALARM_TYPE, Constants.Global.ALARM_TYPE_UNIQUE);
bundle.putString(Constants.Global.ALARM_OCCURRENCE_TIME, "123456");
bundle.putLong(Constants.Global.ALARM_UNIQUE_ID, alarmId);
alarmIntent.putExtras(bundle);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, dt.getMillis(), pendingAlarmIntent);
saveResult = true;
} catch (Exception e) {
Logger.e(e.getMessage());
saveResult = false;
}
return saveResult;
}
在接收器中我有以下代码:
@Override
public void onReceive(Context context, Intent intent) {
try {
Logger.d("ALARM RECEIVED!!!");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
// Device battery life will be significantly affected by the use of this API.
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
// Acquire the lock
wl.acquire();
//Release the lock
wl.release();
// Get the intent type (or stored variables)
Bundle extras = intent.getExtras();
mAlarmType = extras.getString(Constants.Global.ALARM_TYPE);
mAlarmId = extras.getLong(Constants.Global.ALARM_UNIQUE_ID, 0);
mOccurenceTime = extras.getString(Constants.Global.ALARM_OCCURRENCE_TIME, "nothing");
triggerActionBasedOnTheAlarmType(mAlarmType, mAlarmId, mOccurenceTime, context);
} catch (Exception e) {
TrackingEventLogHelper.logException(e, Constants.Global.EXCEPTION,
Constants.ExceptionMessage.EXC_CANNOT_PROCESS_RECEIVED_ALARM, true);
}
}
问题是变量 mOccurenceTime 始终为null,rsp。 “无”。
我试图从意图和Bundle获取值,但仍然没有成功。物品的捆绑数量是否有限?
如何以正确的方式获得价值 mOccurenceTime ?
非常感谢您的任何建议。
答案 0 :(得分:0)
这是正确的方法 - 指定一个标志!
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
而不是:
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, 0);
因为标志的0会让你头疼
这可能是一个很受欢迎的问题,因为Google的示例代码在警报中忽略了Extra。
解决方案: