2015-04-24 9 views
13

Przekazuję oczekującą zgodę na zgłoszenie alarmu, z klasy serwisowej. Jednak po oczekiwaniu na pożary intencyjne, informacja intent.putExtra() nie jest odbierana przez klasę broadcastreceiver. Oto mój kod do wypalania pendingIntentintent.putExtra() w oczekiwaniu na zamiar nie działa

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, aint, PendingIntent.FLAG_UPDATE_CURRENT); 
aint.putExtra("msg", msg); 
aint.putExtra("phone", phone); 
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); 

Klasa odbiornik alarmu jest poniżej

public String msg, phonen; 

@Override 
public void onReceive(Context context, Intent intent){ 
    Bundle extras = intent.getExtras(); 
    msg = extras.getString("msg"); 
    phonen = extras.getString("phone"); 

    Log.d("onReceive", "About to execute MyTask"); 
    Toast.makeText(context,msg, Toast.LENGTH_LONG).show(); 
} 

msg Informacje na tosty, które są odbierane od oczekiwaniu intencje, nie jest pokazane. Zamiast tego pokazany jest pusty tost.

Odpowiedz

23

Spróbuj

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
aint.putExtra("msg", msg); 
aint.putExtra("phone", phone); 



PendingIntent pendingIntent = PendingIntent.getBroadcast(
    getApplicationContext(), 
    id, 
    aint, 
    // as stated in the comments, this flag is important! 
    PendingIntent.FLAG_UPDATE_CURRENT); 
+4

Dla tych, patrząc na to i mają metody .putExtra przed dołączeniem do PendingIntent The 'PendingIntent.FLAG_UPDATE_CURRENT' jest ważna, więc spróbuj, że przed przejściem do innego rozwiązania. – DonutGaz

1

Musisz użyć getStringExtra() i być pewien ciąg nie są nieważne:

 Intent intent = getIntent();  
    msg = intent.getStringExtra("msg"); 
    phonen = intent.getStringExtra("phone"); 

    if(msg!=null){ 
     Toast.makeText(context,msg, 
     Toast.LENGTH_LONG).show(); 
    } 

i odwrócić putExtras przed PendingIntent:

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
    aint.putExtra("msg", msg); 
    aint.putExtra("phone", phone); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, aint, PendingIntent.FLAG_UPDATE_CURRENT); 
1

To jest ponieważ najpierw zainicjujesz Intent i dodasz do PendingIntent. Następnie dodajesz informacje w intencji. Powinieneś dodać informację do intencji, a następnie dodać tę intencję do PendingIntent.

0

Pamiętaj, aby umieścić unikatowy identyfikator w konstruktorze PendingIntent, lub możesz uzyskać dziwne rzeczy, gdy próbujesz uzyskać wartości putExtra.

PendingIntent pendingIntent = PendingIntent.getBroadcast(
      getApplicationContext(), 
      UUID.randomUUID().hashCode(), 
      aint, 
      PendingIntent.FLAG_UPDATE_CURRENT 
    ); 
Powiązane problemy