How to Recover Extras from a Pendingintent (Android)?

Asked

Viewed 200 times

0

I’m implementing Notifications in an app.

I’m using Alarmmanager with a Pendingintent of an Intent with data (in Extras, some model objects) but when I receive them in another Broadcastreceiver class, those extras aren’t there.

here is the code:

Mainactivity

private void saveNotification(Tarefa tarefa) {
    Intent intent = new Intent(this, MyAlarmBroadcastReceiver.class);
    intent.putExtra("tarefa", tarefa); 
    // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); - tentei usar essas flags, mas não funcionou
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 12345678, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
    Toast.makeText(this, "setting the notification in 5 seconds", Toast.LENGTH_SHORT).show();
}

Myalarmbroadcastreceiver:

public class MyAlarmBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras(); 
        Tarefa tarefa = (Tarefa) b.getSerializable("tarefa");
        startNotification(context, taskTitle , taskText );
    }
}

My guess is that when I get an Indtent in the onReceive method, this Indtent is not necessarily the one that was previously sent in the saveNotification method, my question is how to recover that data from the right Intent.

EDIT

I’m trying to send an object Tarefa which implements the Serializable class, but the object returns null by flinging the Nullpointerexception. I fixed the above code.

They asked about the Androidmanifest.xml if I had included a receiver, follow code:

<receiver android:name=".receiver.MyAlarmBroadcastReceiver ">
    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver> 

From now on, thank you.

  • I made here a test using this same code and is working, passing the extras normally. Some error appears?

  • @Acklay I also see nothing wrong.

  • @ramaral has two choices, or the error is in the startNotification(), that we can’t replace, or he didn’t create the <receiver> on Androidmanifest.xml. ^^

  • @Acklay if the Broadcastreceiver is being called is because it was registered or on Androidmanifest.xml or through Context#registerReceiver(). We have to wait for the feedback his.

  • @Acklay thanks for the help, I changed the question and includes the doubts

  • @ramaral includes in the Manifesto the receiver, but still comes empty the object

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.