Android 8.1.0 MainActivity call without click on notification - android

I have shown push notification using firebase but I faced one issue - when app is open and any notification received then Main Activity oncreate() method automatically call without click on notification, so please anyone can help me for resolved this.
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_IMMUTABLE);
} else {
pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
}
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(jsonObject.getString("title"))
.setContentText(jsonObject.getString("body"))
.setAutoCancel(true)
.setNumber(jsonObject.getInt("badge"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.ic_stat_notification);
notificationBuilder.setColor(getResources().getColor(R.color.sky_blue));
notificationBuilder.setFullScreenIntent(pendingIntent, true);
} else {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", "Messages"));
NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
mChannel.setDescription("description");
mChannel.setShowBadge(true);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(mChannel);
}
int num = (int) System.currentTimeMillis();
notificationManager.notify(num, notificationBuilder.build());

you can do the same using
BroadcastReceiver (android.content.BroadcastReceiver)
And background services (android.app.Service)

Related

unable passing multiple actions to notification action intent

Be informed, we are trying to send notification with a button using Addaction. The button Start has a intent that directly opens a url in a webview, which works perfectly fine with code given below
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//int notification_id = nid!=null ? Integer.parseInt(nid) : MainActivity.ASWV_FCM_ID;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
int notification_id=m;
Intent buttonIntent = new Intent(this, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",notification_id);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);
String channelId = MainActivity.asw_fcm_channel;
Uri soundUri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/pristine");
NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, tag, pendingIntent).build();
NotificationCompat.Action action1 = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Dismiss", btPendingIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder1 = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(false)
.addAction(action)
.addAction(action1)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
// Configure the notification channel.
mChannel.setDescription("Common notifications");
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setSound(soundUri, attributes);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(mChannel);
}
Notification noti = notificationBuilder1.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notification_id, notificationBuilder1.build());
Update:
I'm sorry but i'm not actually a expert or a regular coder in android java, so you gotta help me here a little bit more. I have passed on my notification id down in the code, but the problem here is how do i invoke removeNotification in the pendingIntent which also carries my url to where the link will go onclick
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.putExtra("notificationId",notification_id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
public static void removeNotification(int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
}
}
But we also like the notification to be dismissed simultaneously onclick. We tried using .setAutocancel (true) and notification flags like FlAG_AUTO_CANCEL, but the button just does first action right of going into webview url and not cancelling the notification.
Shall appreciate should you help us out.
Send the notification id in the intent to activity and use the code to cancel.
public static void removeNotification(Context context, int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
Timber.d(e);
}
}
Intent intent = getIntent();
if (intent.hasExtra("notificationID")) {
removeNotification(context, intent.getIntExtra("notificationID", 0));
}

after tapping on notification app not launch in android 12 version?

My app uses FCM for notifications. When the user taps the notification on Android 12, the application does not launch, whereas it does on lower versions.
The FirebaseMessagingService code is below.
private RemoteViews getCustomDesign(String title, String message) {
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_collapsed);
remoteViews.setTextViewText(R.id.collapsed_notification_title, title);
remoteViews.setTextViewText(R.id.collapsed_notification_info, message);
return remoteViews;
}
#SuppressLint("UnspecifiedImmutableFlag")
public void showNotification(Context context, NotificationData data) {
Intent intent = new Intent(context, MainActivity.class);
String channel_id = "Default";
intent.putExtra(NOTIFICATION_ID, data.getNotificationId());
intent.putExtra(LEAD_ID, data.getLeadId());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifyPendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notifyPendingIntent = PendingIntent.getActivity(context,
0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
}else {
notifyPendingIntent = PendingIntent.getActivity(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_id)
.setSmallIcon(R.drawable.logoo)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setContentIntent(notifyPendingIntent)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(getCustomDesign(data.getTitle(), data.getMessage()));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channel_id, "Default channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(0, builder.build());
}
Please check your com.google.firebase:firebase-messaging version in build.gradle
After hours of searching I found out that the Firebase Team fixed it in v22.0.0
https://firebase.google.com/support/release-notes/android#messaging_v22-0-0

Notifications not pushed with android 10

I am working on Android App with Firebase notification service FCM. and I recives notification successfully. but after I recive it is not showin in Android 10 (it work in 9 and 8 and smaller versions).
This is my showing notification code, I dont know what I missed. I check about if there is any changed with 10 but I dont see that...
My method:
private void sendNotification(String messageBody, String title) {
Intent intent;
if(type.equals("order_pending") || type.equals("order_declined")){
intent = new Intent(this, myOrdersActivity.class);
}else { intent = new Intent(this, MainActivity.class); }
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int f =0;
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
// EventBus.getDefault().post(eventObject);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isActive", true)) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Intent dialogIntent = new Intent(this, MainActivity.class)
.putExtra("ac", "1");
// sendBroadcast(dialogIntent);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
f =1;
// startActivity(dialogIntent);
}
if(f==0) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Any help please?
and Thanks
The ship has sailed, but:
worked skeleton (Java):
void sendNotif(int icon, String sText) {
String channel_id = "1002";
String sTitle = getString(R.string.app_name);
Intent notificationIntent = new Intent(this, activityMain.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android 8.0 (API level 26) and higher
// https://developer.android.com/training/notify-user/build-notification
CharSequence name = "statusbar";
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channel_id, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel_id)
.setSmallIcon(icon)
/*.setContentTitle(sTitle)*/
.setContentText(sText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(contentIntent)
.setAutoCancel(false);
// notificationId is a unique int for each notification that you must define
// and remember for delete notification
notificationManager.notify(0, builder.build());
}
else {
// Android 7.1 (API level 25) and lower
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(getApplicationContext())
.setTicker(sTitle)
.setContentTitle(sTitle)
.setContentText(sText)
.setSmallIcon(icon)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
// for BIG icon:
//notification.contentView.setImageViewResource(android.R.id.icon, R.drawable.icon);
mNotificationManager.notify(0, notification);
}
}

Android. Notification shows in status bar, but doesn't display or make sound. api 24

I have a push notifications coming into the app. However in api 24 the notification I show only appears in the status bar, but it doesn't display (like pop up), and its doesn't makes any sound.
I can't figure out why...
Here is my code:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-03";
String channelName = "Channel Name";
int importance = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N");
importance = NotificationManager.IMPORTANCE_HIGH;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Log.d(TAG, "android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O");
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
Intent intent1 = new Intent(context, MainActivity.class);
stackBuilder.addNextIntent(intent1);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
Needed to add to the builder:
.setDefaults(Notification.DEFAULT_ALL)

Notifications not working with Android oneplus3 phone

I have this function for notification generation.I have updated the code as per oreo requirements as well. What could be the issue here. Any help is appreciated.It is working on all the other phones.I have rechecked the settings for notifications as well
private void sendNotification(String messageTitle,String messageBody) {
android.net.Uri sound;
Intent intent = new Intent(getActivity(), MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0 /* request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500, 500, 500, 500, 500};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
SharedPreferences demoprefs = getActivity().getSharedPreferences("demo", MODE_PRIVATE);
demiIsLoggedIn = demoprefs.getBoolean("demo", true);
if (!demiIsLoggedIn)
sound = defaultSoundUri;
else
sound = null;
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getActivity())
.setSmallIcon(getActivity().getApplicationInfo().icon)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE, 1, 1)
.setSound(sound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "notification channel";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(12 /* ID of notification */, notificationBuilder.build());
Log.d("wajdan","oneplus");
}
Try to set NotificationChannel in notificationBuilder
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity().getApplicationContext(), "my_channel_01")
...

Categories

Resources