I implemented a notification service in my android app (FirebaseMessagingService). When I click a notification, and the app is closed, the wrong activity is opened. If the notification arrives while the app is open (foreground, background), the activity that is opened is correct.
In the following code, the splash activity (first activity of the project) is opened instead of IntroNoti.class.
This is the code of my FireBaseMessagingService class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
//Log.d(TAG, "From: " + remoteMessage.getFrom());
//Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Globals.messageIn = true;
sendNotification(remoteMessage);
}
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, Login.class);
Intent intent = new Intent(this, IntroNoti.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_launcher: R.mipmap.ic_launcher;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setContentText("CIAO CIAO")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Thanks to the advice of #Eugen Pechanec I added this instruction in my MainActivity. The "messageid" property is only valued when the app is opened by the notification.
Thank you all!
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().size() > 0) {
Log.d(TAG, "Received extras in onCreate()");
Bundle extras = getIntent().getExtras();
if (!extras.getString("messageid","").isEmpty()) {
Globals.fromNotification = true;
}
}
Use PendingIntent.FLAG_UPDATE_CURRENT flag with pending intent . It's work for me.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplication(), CHANNEL_ID)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setContentIntent(getPendingIntent())
.setAutoCancel(true);
private PendingIntent getPendingIntent() {
Intent intent = new Intent(getApplication(), ConversationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return PendingIntent.getActivity(getApplication(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Related
I have a class Home.java which runs first on opening the app when I open it to check if the user is logged in or not.
public class Home extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
The issue I'm facing is when I'm getting a notification for this app, it is starting from LogIn activity instead of going to HomeActivity.
I'm aware that if I want to open a specific activity from a notification, I need to specify getIntent() in the launcher activity, but I don't have any launcher activity.
When I try to implement getIntent() in Home.java class the method is not getting imported since it doesn't extends the Activity class.
Any help!
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}
}
When you want open an activity when click to Notification then use a code like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
//Create an intent to gom HomeActivity
Intent intent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}
I have an app that sends/receives notification using Firebase. Im sending the notification with no problem, but if the app is open the notification display an square instead of the smallicon also if i click the notification nothing happens, but if i'm using a different app i receive the notification and the notification show the correct icon and also opens the app.
public class MyMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void showNotification(String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifitcation")
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
new NotificationChannel("MyNotifitcation", "MyNotifitcation", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
FirebaseMessaging.getInstance().subscribeToTopic("general").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "Successfull";
if (!task.isSuccessful()) {
msg = "Failed";
}
// Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
For Notification click add Pending intent to notification builder. and for adding image/icon to notification use setSmallIcon() in notification builder. below is my notification code.
private void sendNotification(String body, String title) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("action_type", "notify");
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this,"channel")
.setSmallIcon(R.drawable.logo)
// .setContent(contentView)
.setContentTitle("title")
.setContentText("body")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
See below code. Opening Activity.
original post credit
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
This method is from my Helper class for sending notification. I call this method in for loop.
synchronized public void sendNotification(String app, String actionId, String notificationTitle, String notificationText) {
if (SessionManager.isUserLoggedIn()) {
//Initial validation before sending the notifications
if (NullCheckUtils.isEmpty(context)) return;
//If notification is already sent, this action id will be available in map, so need to send notification again
if (notificationMap.get(actionId) != null) return;
notificationMap.put(actionId, notificationCounterId);
//Preparing notification manager for sending notifications
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Customizing notification content's to be displayed
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContentTitle(notificationTitle)
.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText))
.setLargeIcon(icon)
.setChannelId(channelId)
.setContentText(notificationText);
//Defualt loading of Intent when the body of notification is clicked
Intent intent = new Intent(context, FunctionMenuActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Intent openIntent = new Intent(context, NotificationReceiver.class);
openIntent.putExtra("notificationId", notificationMap.get(actionId) + "");
openIntent.setAction(Constants.Notification.YES_ACTION);
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(context, 1, openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_launcher, context.getString(R.string.open), pendingIntentYes);
Intent dismissIntent = new Intent(context, NotificationReceiver.class);
dismissIntent.putExtra("notificationId", actionId);
dismissIntent.setAction(Constants.Notification.STOP_ACTION);
PendingIntent pendingIntentNo = PendingIntent.getBroadcast(context, 1, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_launcher, context.getString(R.string.close), pendingIntentNo);
System.out.println("Data Check:" + notificationMap.get(actionId) + " : " + actionId);
notificationManager.notify(notificationMap.get(actionId), mBuilder.build());
notificationCounterId++;
}
}
Followed by my receiver class, where I receive the action events of Yes & Stop action events. In both case I am getting notificationId same everytime. Expected result is to get the unqiue notification id, which I am passing in the intent bundle. Could anyone explain me, what am I doing wrong here.
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Constants.Notification.YES_ACTION.equals(action)) {
String notificationId = intent.getStringExtra("notificationId");
context.startActivity(new Intent(context, FunctionMenuActivity.class));
Toast.makeText(context, "YES CALLED", Toast.LENGTH_SHORT).show();
System.out.println("Data Check:"+action+" : "+notificationId);
} else if (Constants.Notification.STOP_ACTION.equals(action)) {
String notificationId = intent.getStringExtra("notificationId");
NotificationHelper.getInstance().removeNotification(notificationId);
Toast.makeText(context, "STOP CALLED: " + notificationId, Toast.LENGTH_SHORT).show();
System.out.println("Data Check:"+action+" : "+notificationId);
}
}
}
Upon changing the request id of pending intent, the issue got resolved. Earlier I was passing request id as 0(Now replaced with notificationCounterId) all the time.
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(context, notificationCounterId, openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_launcher, context.getString(R.string.open), pendingIntentYes);
Here there is an activity called grouchat. The messages are sent and received by gcmIntent class. In that class I have the code that issues the notification to the mobile.
In our app more than one event is there for groupchat. If I click the notification, it should take me to the right chat window, so I have passed the eventMO by putExtra parcelable. In the groupchat there is code to get a parcelable
The following is the code in groupchat activity:
eventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(eventMO.getEventId());
The following code is in gcmIntend class to build the notification:
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
//here i have messageMO so i just set the eventid from messageMO to eventMO according to get the eventID in groupchat Activity
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_dialog_info)
.setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName()))
.setContentText(messageMO.getMessage())
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
If I clicked the notification it throws a null pointer exception, because I get eventMO as null. Please tell me how to pass the current event id in GcmIntent class to groupchat activity.
I use this code in my projects
Notification
Intent intent = new Intent(context.getApplicationContext(), MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)//
.setContentTitle(title == null ? context.getString(R.string.app_name) : title)//
.setContentText(message)//
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))//
.setSmallIcon(R.drawable.ic_launcher)//
.setContentIntent(pendingIntent)//
.setTicker(context.getString(R.string.app_name))//
.build();
notification.defaults |= Notification.DEFAULT_ALL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
In Activity check intent in onCreate and onNewIntent
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (getIntent() != null) {
checkIntent(getIntent());
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent(intent);
}
private void checkIntent(Intent intent)
{
...
}
You need change getEvent Id to id of notification.
int notification_id = 123;
notificationManager.notify(notification_id, notification);
Is it possible (and if yes how) to make push notification sound repeat until it's read? I am creating app that notifies user about new event in app, but user needs to read notification as soon as possible. When user "reads" notification it should stop ringing. Here's code:
public class GCMIntentService extends IntentService {
String mes;
HelperGlobals glob;
public GCMIntentService() {
super("GcmIntentService");
}
#SuppressLint("SimpleDateFormat")
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
glob = (HelperGlobals) getApplicationContext();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
// .... Doing work here
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
public void createPush(String title, String msg, Intent intent) {
Uri soundUri = Uri.parse("android.resource://example.project.com/" + R.raw.notification);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, DoNothing.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
n.defaults |= Notification.DEFAULT_VIBRATE;
//n.defaults |= Notification.DEFAULT_SOUND;
n.sound = soundUri;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
And BroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BukuLog", "Receiver");
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
like this:
Notification note = mBuilder.build();
//here
note.flags = Notification.FLAG_INSISTENT;
mNotificationManager.notify(1, note);
int FLAG_INSISTENT : Bit to be bitwise-ored into the flags field that if set, the audio will be repeated until the notification is cancelled or the notification window is opened.
follow android developer