Open app after clicking on Notification - android

I have a notification in my app with the following code:
public class NewMessageNotification {
private static final String NOTIFICATION_TAG = "NewMessage";
public static void notify(final Context context,
final String exampleString,final String boday ,final int number) {
final Resources res = context.getResources();
// This image is used as the notification's large icon (thumbnail).
// TODO: Remove this if your notification has no relevant thumbnail.
final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.billsms);
final String ticker = exampleString;
final String title = res.getString(
R.string.new_message_notification_title_template, exampleString);
final String text = boday;
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
// Set appropriate defaults for the notification light, sound,
// and vibration.
// Set required fields, including the small icon, the
// notification title, and text.
.setSmallIcon(R.drawable.billsms)
.setContentTitle(title)
.setContentText(text)
// All fields below this line are optional.
// Use a default priority (recognized on devices running Android
// 4.1 or later)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Provide a large icon, shown with the notification in the
// notification drawer on devices running Android 3.0 or later.
.setLargeIcon(picture)
// Set ticker text (preview) information for this notification.
.setTicker(ticker)
// Show a number. This is useful when stacking notifications of
// a single type.
.setNumber(number)
// If this notification relates to a past or upcoming event, you
// should set the relevant time information using the setWhen
// method below. If this call is omitted, the notification's
// timestamp will by set to the time at which it was shown.
// TODO: Call setWhen if this notification relates to a past or
// upcoming event. The sole argument to this method should be
// the notification timestamp in milliseconds.
//.setWhen(...)
// Set the pending intent to be initiated when the user touches
// the notification.
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")),
PendingIntent.FLAG_UPDATE_CURRENT))
// Show expanded text content on devices running Android 4.1 or
// later.
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(text)
.setBigContentTitle(title)
.setSummaryText("Dummy summary text"))
// Example additional actions for this notification. These will
// only show on devices running Android 4.1 or later, so you
// should ensure that the activity in this notification's
// content intent provides access to the same actions in
// another way.
.addAction(
R.drawable.ic_action_stat_share,
res.getString(R.string.action_share),
PendingIntent.getActivity(
context,
0,
Intent.createChooser(new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, "Dummy text"), "Dummy title"),
PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(
R.drawable.ic_action_stat_reply,
res.getString(R.string.action_reply),
null)
// Automatically dismiss the notification when it is touched.
.setAutoCancel(true);
notify(context, builder.build());
}
#TargetApi(Build.VERSION_CODES.ECLAIR)
private static void notify(final Context context, final Notification notification) {
final NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
nm.notify(NOTIFICATION_TAG, 0, notification);
} else {
nm.notify(NOTIFICATION_TAG.hashCode(), notification);
}
}
/**
* Cancels any notifications of this type previously shown using
* .
*/
#TargetApi(Build.VERSION_CODES.ECLAIR)
public static void cancel(final Context context) {
final NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
nm.cancel(NOTIFICATION_TAG, 0);
} else {
nm.cancel(NOTIFICATION_TAG.hashCode());
}
}
}
My notifications fires very well, but my problem is that, when I click on notification in Notification Center, it does not start my app.
Basically, after clicking on my notification nothing happens!Thanks.

Basically your Pending Intent should have your application's one of the activity components.
Intent appIntent = new Intent(context, YourActivityName.class);
PendingIntent.getActivity(context, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Similarly you can add other components like Activity, Service and Receiver.
PendingIntent.getActivity ...
PendingIntent.getBroadcast ...
PendingIntent.getService ...
Hope this helps.

I found the answer to my question.
The only change this code :
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")),
PendingIntent.FLAG_UPDATE_CURRENT))
To this code :
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(context.getApplicationContext(),MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))

Related

firebase notification get only inapp subscribers

i am new for android development, i am design one app, in that app in-app subscription option available, after subscription user need to get notification, but all installed users get the notification, i need only subscriber users get the notification, how to resolve this issue any one help me this,
public class FirebaseMessageReceiver extends FirebaseMessagingService {
// Override onMessageReceived() method to extract the
// title and
// body from the message passed in FCM
Prefs prefss;
#Override
public void
onMessageReceived(RemoteMessage remoteMessage) {
// First case when notifications are received via
// data event
// Here, 'title' and 'message' are the assumed names
// of JSON
// attributes. Since here we do not have any data
// payload, This section is commented out. It is
// here only for reference purposes.
/*if(remoteMessage.getData().size()>0){
showNotification(remoteMessage.getData().get("title"),
remoteMessage.getData().get("message"));
}*/
// Second case when notification payload is
// received.
prefss = new Prefs(this);
if (remoteMessage.getNotification() != null) {
// Since the notification is received directly from
// FCM, the title and the body can be fetched
// directly as below.
if (prefss.getPremium() == 1) {
showNotification(
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody());
}
}
}
// Method to get the custom Design for the display of
// notification.
private RemoteViews getCustomDesign(String title,
String message) {
RemoteViews remoteViews = new RemoteViews(
getApplicationContext().getPackageName(),
R.layout.notification);
remoteViews.setTextViewText(R.id.title, title);
remoteViews.setTextViewText(R.id.message, message);
remoteViews.setImageViewResource(R.id.icon,
R.drawable.logo);
return remoteViews;
}
// Method to display the notifications
public void showNotification(String title,
String message) {
// Pass the intent to switch to the MainActivity
Intent intent
= new Intent(this, Subscription.class);
// Assign channel ID
String channel_id = "notification_channel";
// Here FLAG_ACTIVITY_CLEAR_TOP flag is set to clear
// the activities present in the activity stack,
// on the top of the Activity that is to be launched
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Pass the intent to PendingIntent to start the
// next Activity
PendingIntent pendingIntent
= PendingIntent.getActivity(
this, 100, intent,
PendingIntent.FLAG_ONE_SHOT);
// Create a Builder object using NotificationCompat
// class. This will allow control over all the flags
NotificationCompat.Builder builder
= new NotificationCompat
.Builder(getApplicationContext(),
channel_id)
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000,
1000, 1000})
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
// A customized design for the notification can be
// set only for Android versions 4.1 and above. Thus
// condition for the same is checked here.
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.JELLY_BEAN) {
builder = builder.setContent(
getCustomDesign(title, message));
} // If Android Version is lower than Jelly Beans,
// customized layout cannot be used and thus the
// layout is set as follows
else {
builder = builder.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.logo);
}
// Create an object of NotificationManager class to
// notify the
// user of events that happen in the background.
NotificationManager notificationManager
= (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
// Check if the Android Version is greater than Oreo
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel
= new NotificationChannel(
channel_id, "web_app",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(
notificationChannel);
}
notificationManager.notify(1, builder.build());
}
}

Is there any Android notifications setContentTitle and setContextText magic values?

I'm currently working on a library with android support.
I'm being asked to notify user on foreground service start.
The notification must contain "ApplicationName" as title, and "ApplicationName is running" as text. The notification icon has to be the same as the launcher one.
The target API level is 26.
The notification did not work because the previous developper forgot to open the notification chanel. This is now fixed, we have the notification that pops correctly. And the label are matching expectation.
But now i'm questioning why the notification contains the expected values. I could not find any reference in the javadoc.
The following code will display the notification as expectecd the application's name as title and the text "ApplicationName is running" :
#Override
public void onCreate() {
NotificationChannel channel = new NotificationChannel("APPLICATION_CHANNEL", "MyService", NotificationManager.IMPORTANCE_LOW);
channel.setDescription(notificationChannelText);
//block below useful for head up notification
channel.setSound(null, null);
channel.setShowBadge(false);
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
foregroundNotification();
return Service.START_STICKY;
}
/**
* In order to start foreground service we and generate a service running notification.
*/
private void foregroundNotification() {
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, getClass());
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context, "APPLICATION_CHANNEL")
.setContentTitle("Title")
.setContentText("Subject")
.setContentIntent(pendingIntent)
.build();
startForeground(42666, notification);
}
Why doesn't it just display a notification with "Title" as the title and "Subject" as content ?
Are there any constants or magic values that we have to know ?
Where can we find any documentation or definition about it ?
Edit 2020/04/01 : Added code representing notification channel creation
I found your problem. This is result of your code:
and after add small icon:
.setSmallIcon(R.mipmap.ic_launcher)
It works fine

Heads up with reply (RemoteInput) does not cancel notification

Step1 : Build Notification with Reply intent and heads up notification
private void buildInlineReplyNotification() {
// Create an instance of RemoteInput.Builder that you can add to your notification action.
// This class's constructor accepts a string that the system uses as the key for the text input.
// Later, your handheld app uses that key to retrieve the text of the input.
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(
getResources().getString(R.string.reply_label)).build();
// Attach the RemoteInput object to an action using addRemoteInput().
NotificationCompat.Action compatAction =
new NotificationCompat.Action.Builder(R.mipmap.ic_reply,
getResources().getString(R.string.reply), replyPendingIntent).addRemoteInput(
remoteInput).setAllowGeneratedReplies(true).build();
// Build the notification and add the action.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(
getResources().getString(R.string.notification_created) + mNotificationId)
.setContentText(getResources().getString(R.string.type_reply))
.setShowWhen(true)
.addAction(compatAction);
mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]);
// Issue the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(mNotificationId, mBuilder.build());
}
Step2 : cancel after reply from notification
private void updateNotification(Context context, int notifyId) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_notification)
.setContentText(context.getString(R.string.message_sent));
notificationManager.cancel(notifyId);
}
Issues is not cancel notification by notificationManager.cancel(notifyId) but if i remove this mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]); Than work perfect so, what is issue with priority in notification ?

Behaviour of grouped notification on Android 7

I create several notifications like this:
public class NotificationCreator {
Context context;
int c = 0;
public NotificationCreator(final Context context) {
this.context = context;
}
void create() {
String text = "" + c + " " + new Date().toGMTString();
// Intent
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(SecondActivity.KEY, text);
Intent[] intents = new Intent[1];
intents[0] = intent;
PendingIntent pendingIntent = PendingIntent.getActivities(
context,
c,
intents,
PendingIntent.FLAG_CANCEL_CURRENT);
// Build notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.notification);
builder.setContentTitle("Test");
builder.setContentText(text);
// builder.setGroup("");
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
// Send notification
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(c, notification);
c++;
}
}
The outcome on Android 7 is:
The system has grouped all notifications.
When I set explicitly on the builder:
builder.setGroup("myGroup");
the outcome is:
The notifications are not grouped, but all shown individually, despite all having the same group key.
Is this the expected behaviour?
In the first case (grouped), can I determine what happens when the user clicks on the grouped notification? The individual intents seem to be ignored and just the app opened.
Had the same problem and figured it out by using a "Summary notification". Basically, you create one regular notification with the desired group and the "Summary notification" with the same group and setGroupSummary(true).
More here https://blog.stylingandroid.com/nougat-bundled-notifications/

Incorrect timestamp on future notifications

When my application is launched, it performs an API call and then schedules notifications based on the results. This amounts to around ~10 notifications being scheduled. There seems to be an issue with the timestamp displayed on the actual notification being incorrect.
Since I am creating these notifications and then scheduling an alarm with an AlarmManager, the default time present on the notification will be the time at which the notification is created (System.currentTimeMillis()).
I've tried to use the .setWhen() method on my Notification.Builder to set it to the time I am using to schedule the previously mentioned alarm. This is a little better, however, because notifications are not guaranteed to be delivered at the exact time specified, I often get notifications a few minutes in the past.
Additionally, I tried to manually override the when field on the notification in my BroadcastReceiver, right before .notify() is actually called:
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
notification.when = System.currentTimeMillis();
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
However, in the above scenario, it seems that .when is ignored.
Frankly, I am simply looking for a way to have the timestamp displayed on the notification be the time at which it is actually displayed.
I would suggest passing in your notification's information as extras then building the notification inside of the BroadcastReceiver. This will build the notification just before it is issued, so it will have the same time your AlarmManager triggers the BroadcastReceiver.
From wherever you're scheduling the notification:
private void scheduleNotification(){
// Create an intent to the broadcast receiver you will send the notification from
Intent notificationIntent = new Intent(this, SendNotification.class);
// Pass your extra information in
notificationIntent.putExtra("notification_extra", "any extra information to pass in");
int requestCode = 1;
// Create a pending intent to handle the broadcast intent
PendingIntent alarmIntent = PendingIntent
.getBroadcast(this, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set your notification's trigger time
Calendar alarmStart = Calendar.getInstance();
alarmStart.setTimeInMillis(System.currentTimeMillis());
alarmStart.set(Calendar.HOUR_OF_DAY, 6); // This example is set to approximately 6am
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm with the pending intent
// be sure to use set, setExact, setRepeating, & setInexactRepeating
// as well as RTC_WAKEUP, ELAPSED_REALTIME_WAKEUP, etc.
// where appropriate
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmStart.getTimeInMillis(), alarmIntent);
}
Then, inside your BroadcastReceiver's onReceive:
String notificationExtra = null;
// Retrieve your extra data
if(intent.hasExtra("notification_extra")){
notificationExtra = intent.getStringExtra("notification_extra");
}
//Build the notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(notificationIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setAutoCancel(true); // Use AutoCancel true to dismiss the notification when selected
// Check if notificationExtra has a value
if(notificationExtra != null){
// Use the value to build onto the notification
}
//Define the notification's action
Intent resultIntent = new Intent(context, MainActivity.class); // This example opens MainActivity when clicked
int requestCode = 0;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
requestCode,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
//Set notification's click behavior
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 1;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
I have also been struggling with this for a bit, but your question actually brought me to the best answer. I checked out setWhen() and it seems like now this just works fine (checked with API lvl 30 & 31). As this post is a few years old, maybe this issue was fixed in the meantime. So here's how I did it in Kotlin:
class NotificationPublisher : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = intent.getParcelableExtra<Notification>(NOTIFICATION)
notification?.`when` = System.currentTimeMillis() // overwriting the creation time to show the current trigger time when the notification is shown
val postId = intent.getIntExtra(NOTIFICATION_ID, 0)
notificationManager.notify(postId, notification)
}
Your NotificationPublisher's onReceive() method will be invoked only when scheduled alarm triggers as specified time. When you crate a notification from onReceive() method, it will definitely show the current time. No need to require to use .when or .setWhen() method.
Try this one:
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
// Notification
Notification notification = new Notification.Builder(context)
.setContentTitle("This is notification title")
.setContentText("This is notification text")
.setSmallIcon(R.mipmap.ic_launcher).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager .notify(id, notification);
}
}
If you want to redirect to an activity when click on Notification, then you can use PendingIntent and set it to your Notification.
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
Intent intent = new Intent(context, YourTargetActivity.class);
intent.putExtra("KEY_ID", id); // Pass extra values if needed
PendingIntent pI = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Notification
Notification notification = new Notification.Builder(context)
.setContentTitle("This is notification title")
.setContentText("This is notification text")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pI).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager .notify(id, notification);
}
}
Hope this will help~

Categories

Resources