Starting Activity from a notification - Android Studio - android

I am trying to start an activity from a notification. Upon starting that activity, I add data via intent.putextra to the intent so the activity shows the right content for the situation.
The activity that is being started is supposed to be open only once in the stack. I did achieve this via
android:launchMode="singleTop"
in my manifest.
However - and now I come to my question - if this activity is already running, I want it to close and replace it with the instance I am creating with the specific additional data (put extra). How can I achieve this?
Heres the code of my notification:
public void newMessageNotification(String title, String message, String otherusernumber, String requestStatus, String sendername) {
notificationManager = NotificationManagerCompat.from(this);
Intent chatIntent = new Intent(this,ChatActivity.class);
//these three strings define the behaviour of the chat activtity
chatIntent.putExtra("otherUsername", sendername);
chatIntent.putExtra("otherUsernumber", otherusernumber);
chatIntent.putExtra("requestStatus", requestStatus);
chatIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), chatIntent,
PendingIntent.FLAG_UPDATE_CURRENT);;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_new_message)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(1, notification);
}

Try below code
Add PendingIntent in notification
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Full create notification code
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =
(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager . getDefaultUri (RingtoneManager.TYPE_NOTIFICATION);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String Ch_id = "yourappname_01";
// The user-visible name of the channel.
CharSequence name = "Notification";
// The user-visible description of the channel.
//String description = getString(R.string.channel_description);
int importance = NotificationManager . IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(Ch_id, name, importance);
mChannel.setSound(defaultSoundUri, new AudioAttributes . Builder ().build());
notificationManager.createNotificationChannel(mChannel);
// Create a notification and set the notification channel.
notification = new Notification . Builder (this, Ch_id)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setContentIntent(pendingIntent) //Add PendingIntent
.setChannelId(Ch_id)
.build();
} else {
// Create a notification
notification = new Notification . Builder (this)
.setSmallIcon(R.drawable.notify)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(remoteMessage.getData().get("title"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent) //Add PendingIntent
.build();
}
//Generate Diff Notification
int m =(int)((new Date ().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notification);
Update
Intent intent = new Intent(this, OpenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent,
PendingIntent.FLAG_ONE_SHOT);
I hope this can help you!
Thank You.

Try to add flag: Intent.FLAG_ACTIVITY_NEW_TASK to your Intent

Try Below
Intent intent = new Intent(this, ActivityDestination.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ACTIVITY_NEW_TASK);

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

Redirect to specific screen as per notification - android

I have receive three different screens in my app:
Reading,
Walking, and
Sleeping
How do I identify the specific notification to redirect to in each screen?
To do so, you must specify a content intent defined with a PendingIntent object and pass it to setContentIntent().
The following snippet shows how to create a basic intent to open an activity when the user taps the notification:
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, Reading.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
This is clearly mentioned in Android developer site
private final String CHANNEL_ID = "channel1";
private final String CHANNEL_NAME = "channel_one";
private NotificationManager notificationManager;
private NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
} else {
return notificationManager;
}
}
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("type", "type");
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setShowBadge(true);
getNotificationManager().createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setColorized(true);
builder.setChannelId(CHANNEL_ID);
builder.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Title");
builder.setContentText("Message");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_bottom_logo);
builder.setLargeIcon(/*BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)*/getBitmapFromDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher)));
builder.setContentIntent(pendingIntent);
getNotificationManager().notify((int) SystemClock.uptimeMillis(), builder.build());

Need to make Notification display always on top of notification bar, like a music player

I have tried below code for it with custom Notification but its not working. I want to display counter in my custom notification like music player .
final RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.layout_workout);
remoteViews.setTextViewText(R.id.layout_workout_tv_name, type + " " + videoList.get(position).getName());
remoteViews.setTextViewText(R.id.layout_workout_tv_time, strTime);
final Intent pauseWorkout = new Intent();
pauseWorkout.setAction(ACTION_PAUSE);
final PendingIntent pauseWorkoutPendingIntent = PendingIntent.getBroadcast(this, 101, pauseWorkout, PendingIntent.FLAG_UPDATE_CURRENT);
final Intent resumeWorkout = new Intent();
resumeWorkout.setAction(ACTION_RESUME);
final PendingIntent resumeWorkoutPendingIntent = PendingIntent.getBroadcast(this, 102, resumeWorkout, PendingIntent.FLAG_UPDATE_CURRENT);
final Intent skipWorkout = new Intent();
skipWorkout.setAction(ACTION_SKIP);
final PendingIntent skipExercisePendingIntent = PendingIntent.getBroadcast(this, 103, skipWorkout, PendingIntent.FLAG_UPDATE_CURRENT);
final Intent completeSetWorkout = new Intent();
completeSetWorkout.setAction(ACTION_COMPLETE_SET);
final PendingIntent completeSetPendingIntent = PendingIntent.getBroadcast(this, 104, completeSetWorkout, PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setAutoCancel(false)
.setContent(remoteViews)
.setShowWhen(false)
.setOngoing(true);
notificationBuilder.setWhen(System.currentTimeMillis());
remoteViews.setOnClickPendingIntent(R.id.layout_workout_btn_complete_set, completeSetPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.layout_workout_btn_pause, pauseWorkoutPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.layout_workout_btn_resume, resumeWorkoutPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.layout_workout_btn_skip, skipExercisePendingIntent);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
I have also tried below code as well
.setPriority(Notification.PRIORITY_MAX)
For the higher priority notifications, use below code snippet...
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.some_small_icon)
.setContentTitle("Title")
.setContentText("This is a test notification with MAX priority")
.setPriority(Notification.PRIORITY_MAX);

Android push notification showing text in single line

I have search and found solution but that solution is not showing multi line push notification.
My code is below,
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, Activity.class);
Bundle bundle = new Bundle();
bundle.putString("id", u_id);
intent.putExtras(bundle);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this);
Notification notification = mBuilder.setSmallIcon(getNotificationIcon()).setTicker(getResources().getString(R.string.app_name)).setWhen(0)
.setAutoCancel(true)
.setContentTitle(getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
.setContentIntent(resultPendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(getResources(), getNotificationIcon()))
.setContentText(messageBody).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notification);
How can I show multi line text in push notification?
Intent intent = new Intent(this, target.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap image= BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.youricon)
.setContentTitle("Title")
.setLargeIcon(image)
.setContentText("Message")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap).setSummaryText("multiline text"));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(m/* ID of notification */, notificationBuilder.build());

Categories

Resources