I want to open a fragment when the app receive a notification for further processing. In my MainActivity.java, getIntent().getExtras()
always return null
.
MyFirebaseMessagingService.java
private void sendNotification(String title, String messageBody, String newsID, String newsType) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bundle extras = new Bundle();
extras.putString("newsID", String.valueOf(newsID));
extras.putString("newsType", String.valueOf(newsType));
intent.putExtras(extras);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
MainActivity.java
Bundle i = getIntent().getExtras();
if (i != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.e("News ID", value);
if (key.equals("newsID") ) {
dbHelper.insertNewsID(String.valueOf(value));
//show news details
getSupportFragmentManager()
.beginTransaction()
.replace(ng.naijaleague.R.id.frame_container, new NewsDetails())
.addToBackStack(null).commit();
}
}
String newsType = getIntent().getExtras().getString("newsType");
if ("newsType".equals(newsType) ) {
String value = getIntent().getExtras().getString("newsType");
if("Local".equals(value)){
//add news type to shared preference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("newType", "Local");
editor.apply();
}else{
//add news type to shared preference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("newType", "Foreign");
editor.apply();
}
}
}
I have followed through all the solutions I found on SO but none of them have worked so far. What must be wrong with the code?