3

У меня есть следующий метод, который сохраняет три значения в намерении, которое добавляется к созданному сигналу тревоги.Android: не удается сохранить и прочитать все значения в Bundle

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 всегда нуль, RSP. "ничего".

Я попытался получить значения от намерения и от Bundle, но все же без успеха. Не ограничено ли количество предметов?

Как я могу получить значение mOccurenceTime в правильном направлении?

Большое спасибо за любой совет.

+0

вы присвоить ALARM_OCCURRENCE_TIME уникальное значение? – Blackbelt

+0

Да, это жестко закодированная константа (ключ), но значение может быть разным или одинаковым (на основе значения переменной). – redrom

+0

- это ключи, которые вы используете, чтобы поместить значения в комплект все разные? (в частности, 'Constants.Global.ALARM_UNIQUE_ID' отличается от' Constants.Global.ALARM_OCCURRENCE_TIME') – njzk2

ответ

0

Это правильный способ сделать это - указать флаг!

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

Вместо:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, 0); 

Поскольку 0 для флагов то, что вызовет у вас головная боль

Это, вероятно, такая популярная проблема, потому что пример код Google, пренебрег включить Экстра в в Тревоге.

решаемые здесь:

Android cannot pass intent extras though AlarmManager