Issue
I'm developming an Android App with an Alarm function.
So far so good, I'm using this tutorial for Alarm Manager, but I've been having some issues while working with PendingIntents.
Everything works just fine until I tried to send another Object in Extras on my Intent, when it comes to the other side, the Object (witch implements Serializable class) is null.
Here's my code:
Intent intent = new Intent(context, AlarmMedicBroadcastReceiver.class);
intent.setAction(AlarmeMedicamentoBroadcastReceiver.ACTION_ALARM);
intent.putExtra("alarm", dto); // <- My Object that extends Serializable
/* Setting 10 seconds just to test*/
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
long tempo = cal.getTimeInMillis();
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, dto.getId(), intent, 0);
AlarmManager alarme = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarme.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, tempo, alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alarme.setExact(AlarmManager.RTC_WAKEUP, tempo, alarmIntent);
} else {
alarme.set(AlarmManager.RTC, tempo, alarmIntent);
}
In my Receiver class:
@Override
public void onReceive(Context context, Intent intent) {
if(ACTION_ALARM.equals(intent.getAction())){
AlarmeMedicamentoDTO alarm = (AlarmeMedicamentoDTO) intent.getExtras().getSerializable("alarm");
/*for this moment, alarm is null*/
/*Other Stuff*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Company name")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Alarme de Medicamento")
.setContentText("Hora de tomar seu medicamento: " + alarm.getNomeMedicamento()) //<- Null Pointer Exception
.setContentIntent(pendingIntent)
.setContentInfo("Info");
notificationManager.notify(1, notificationBuilder.build());
}
}
thanks in advance
Solution
You can no longer add custom objects as "extras" to an Intent
that you pass to AlarmManager
. In more recent versions of Android, the AlarmManager
tries to unpack the "extras" and it has no idea how to unpack your custom objects, so these get removed from the "extras".
You either need to serialize your custom object to a byte array and put that in the "extras", or store your custom object somewhere else (file, SQLite DB, static member variable, etc.)
Answered By - David Wasser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.