I am trying to write a simple notification application. All it does is notify a notication whenever the button is clicked.
I write my app step by step according to this tutorial.
I don't understand what channel id I should pass to the constructor in order that the app will work. Now the app doesn't do anything (it's not collapses either). I guess that the problem is in the initialization of the variable NotificationCompat.Builder notifyBuilder. I didn't know what to pass so I just passed an arbitary string "0".
My questions are what should I pass to the constructor of NotificationCompat.Builder and will it make the app to work?
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button mNotifyButton;
private static final int NOTIFICATION_ID = 0;
private static final String NOTIFICATION_ID_STRING = "0";
private NotificationManager mNotifyManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotifyButton = (Button) findViewById(R.id.notificationButton);
}
public void sendNotification(View view) {
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notifyBuilder
=new NotificationCompat.Builder(this, NOTIFICATION_ID_STRING)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android);
Notification myNotification = notifyBuilder.build();
mNotifyManager.notify(NOTIFICATION_ID, myNotification);
}
}
private static final int NOTIFICATION_ID = 0;
This one identifies your notification. If you send multiple notifications with the same ID, the old notification will be replaced by the newer one. So, if want to display several notifications at once, you need multiple IDs.
private static final String NOTIFICATION_ID_STRING = "0";
This one is the ID of the channel. It tells which channel should be used to send that notification. You can assign any String. You just need to ensure that you use the same String for a specific channel. And if you want to create more channels, you need to use a different String for them.
About channel
In recent versions of Android (Android Oreo onwards), you can have different channels to send Notifications. This way, you allow your user to customize which notification he wants to receive.
For example, you have a shopping app. Then, you can have some channels such as:
My Orders (to notify about the orders)
Promotions (to notify about promotions.. this one, the user will probably want to disable).
Miscellaneous (to any other type of notification).
Before sending a notification on that channel, you should create it:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Orders Notification";
String description = "Notifications about my order";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID_STRING, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Then, you can send notifications via:
NotificationCompat.Builder notifyBuilder
= new NotificationCompat.Builder(this, name.toString())
You can check all channes an app have via:
Settings -> Apps -> App you want to check -> Notifications
Some apps have just one channel. Other apps may have more than one channel.
Returning to your question
So, returning to you example, NOTIFICATION_ID_STRING can be any string. You just need to use "0" everytime you want to send a message on that specific channel.
And, if you create a new channel, use a new string "channel1", for example.
However, you must create a channel before sending a notification on it:
// This ID can be the value you want.
private static final int NOTIFICATION_ID = 0;
// This ID can be the value you want.
private static final String NOTIFICATION_ID_STRING = "My Notifications";
public void sendNotification(View view) {
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//Create the channel. Android will automatically check if the channel already exists
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID_STRING, "My Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("My notification channel description");
mNotifyManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notifyBuilder
= new NotificationCompat.Builder(this, NOTIFICATION_ID_STRING)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android);
Notification myNotification = notifyBuilder.build();
mNotifyManager.notify(NOTIFICATION_ID, myNotification);
}
You can find more information about them HERE
Related
I have a problem with notifications where the notification doesn't appear on my xiaomi and samsung devices but works for the other device. I've tried what people recommend like trying auto start, managing battery settings, but it still doesn't appear on both devices. I also tried to use the notify library but the results were the same. Strangely, when I checked the notification setting and then clicked on the application, it appeared as shown below
samsung
This is my notification code :
public void showNotification() {
String appname = "App Name";
String title = "Notification Title";
String text = "This is the notification text";
String iconUrl = "http://url.to.image.com/image.png";
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(MainActivity.this);
stackBuilder.addParentStack(NewsActivity.class);
stackBuilder.addNextIntent(new Intent(MainActivity.this, NewsActivity.class));
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentTitle(title).setContentInfo(appname).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo_wanda_flp)).setContentText(text).setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.logo_wanda_flp);
notifyManager.notify("textid", 123, builder.getNotification());
}
The code won't work on Android 8 (API 26) and above without first registering a notification channel. On Android before that, it will work just fine.
Some of the code snippets below are taken from here.
Creating a notification channel
Register notification channels inside your activity before attempting to show any notification. Alternatively, you can register them inside a custom Application class before any activities or services start (but this won't be shown here for the sake of simplicity).
#Override
public void onCreate(Bundle savedInstanceState) {
createNotificationChannel(); // Registering a notification channel
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
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);
}
}
Deliver the notification
public void showNotification() {
// ...
// NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
// Replace with line below.
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
// ...
}
I need to generate notifications when a PUSH notification is received but also I need to generate notifications (for display them in the notification bar of the device) when something happens in the application, so I'm using NotificationCompat.Builder for it.
As you know, android has deprecated this call to Notification.Builder:
Notification.Builder (Context context)
And now you must use this call:
NotificationCompat.Builder (Context context, String channelId)
What happens if you don't want to specify a notification channel and you want to send general notifications to all the users of your app and you want to receive all the notifications in all the apps installed without dealing with notification channels? Or what happens if you want to create a simple notification in the notification bar when a user has pressed a button in your app? How to display a notification without specifying the channelId? I mean... just working like until api 26 and before notification channels appeared.
Can't see how to work without specifying notification channels in any place of the official documentation.
Notification Channels are mandatory on Android 8+. So you must use NotificationCompat.Builder(Context context, String channelId) and create channel(s) on api 26+ via NotificationManager.createNotificationChannel(NotificationChannel channel).
On api < 26, just don't call createNotificationChannel but let the channel id parameter (just a String).
val builder = NotificationCompat.Builder(context, "a_channel_id")
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_notif)
.setAutoCancel(true)
...
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(NOTIFICATION_ID, builder.build())
on Api 26+, create a channel before:
val channel = NotificationChannel("a_channel_id", "channel_name", NotificationManager.IMPORTANCE_HIGH)
channel.description = "channel_description"
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.createNotificationChannel(channel)
There is currently no workaround for this. Notification Channels has been recently announced (last last I/O if I remember correctly), and is (most probably if not absolutely) here to stay. What I do though is something like this.
To abide to the new standard, I just implement the Notification Channels, but only as needed. I also use FCM on my app and here's something similar to what I have for it -- this is in my Application class:
private void initFirebase() {
... // other Firebase stuff.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) initNotificationChannels();
}
#TargetApi(Build.VERSION_CODES.O)
private void initNotificationChannels() {
NotificationChannel publicChannel = new NotificationChannel(NOTIFICATION_CHANNEL_PUBLIC,
NOTIFICATION_CHANNEL_PUBLIC, NotificationManager.IMPORTANCE_DEFAULT);
publicChannel.setDescription(NOTIFICATION_CHANNEL_PUBLIC);
NotificationChannel privateChannel = new NotificationChannel(NOTIFICATION_CHANNEL_PRIVATE,
NOTIFICATION_CHANNEL_PRIVATE, NotificationManager.IMPORTANCE_HIGH);
publicChannel.setDescription(NOTIFICATION_CHANNEL_PRIVATE);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(publicChannel);
mNotificationManager.createNotificationChannel(privateChannel);
}
}
And my MessagingService has something like this:
private static final String NOTIFICATION_CHANNEL_PRIVATE = "my.app.package.name.private";
private static final String NOTIFICATION_CHANNEL_PUBLIC = "my.app.package.name.public";
private void buildNotification(....(other params),String source, String message) {
String channelId = getChannelId(source);
Intent resultIntent = new Intent(this, MyActivity.class);
resultIntent.putExtra(EXTRAS_PARAM_ID, myVal);
PendingIntent notificationIntent = buildNotificationIntent(channelId, roomId, roomType);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, getChannelId(source))
.setSmallIcon(R.drawable.ic_sample
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentIntent(notificationIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, 0, notificationBuilder.build());
}
private String getChannelId(String source) {
switch(source){
case PRIVATE:
return NOTIFIFICATION_CHANNEL_PRIVATE;
default:
return NOTIFICATION_CHANNEL_PUBLIC;
}
}
I don't know if this answers the question or not. But, having any channel below api 26 just worked without doing anything on my app.
1. instantiate notificationCompat with some channel Id
//which is irrelevant for api < 26
2. handle the case of creating notification channel for api 26+
3. bundled it up.
It just worked. Configuring Notifications did not have any effects below api 26.
I have an Chat app in which a user is subscribed to an topic and each group is a topic. Whenever an message is sent in the group. An notification is sent to that topic.
There are two problems that I am facing.
When the sender sends the message in the group, a notification message is sent to the topic. But before the user gets the notification from firebase, He closes the application or the app goes in the background. So According to the firebase documentations, the notification is sent to the notification tray and not the onMessageReceived callback.
The notification that is received from the firebase is added to the tray. How can the users other than the sender get the notification Id so that i can be cancelled when it required. How can this notification be customised?
Is there a way to keep an active listener for receiving the notification when the app is in the background or terminated.
Please help
You might wan to take a look this.At first I always have problem reading the doc due to english not my primary language. It very confuse but just follow the step you will get more understading.
For your first question you do not need to use both notification and data message. If you use so it will prevent onMessageReceived() get call if the app is in foreground or force close. Trust me just remove the notification{notification:"data"} but keep {data:"something"} while sending to firebase. It will always trigger onMessageReceived().
For you second question after you follow the step above you won't get any notification display on your status bar. Here you can check wether this user is the sender, if it wasn't the sender then you can just show your custom notification inside onMessageReceived().
You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .
Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .
Fire base Cloud Messaging
it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:
Create you first class MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size()>0){
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.icon,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
String adminChannelDescription = getString(R.string.notifications_admin_channel_description);
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Create another class FirebaseIDService to get instance id service of fire base
public class FirebaseIDService extends FirebaseInstanceIdService {
public static final String FIREBASE_TOKEN = "firebase token";
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();
}
Make class Name LikeService
public class LikeService extends Service {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.
in oncreate of your project first launcher activity include these channels;
String channelId = "1";
String channel2 = "2";
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
Now you have to put your Firebase service class in Mainfest under application tag:
<service android:name=".activities.services.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service android:name=".activities.services.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:
put data as in photo according to your app: when its closed:
if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,
make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class
like
title ,message,applink,imageurl
I donĀ“t know how to group two or more notifications into only one and show a message like "You have two new messages".
Steps to be taken care from the below code.
NotificationCompat.Builder:contains the UI specification and action information
NotificationCompat.Builder.build() :used to create notification (Which returns Notification object)
Notification.InboxStyle: used to group the notifications belongs to same ID
NotificationManager.notify():to issue the notification.
Use the below code to create notification and group it. Include the function in a button click.
private final int NOTIFICATION_ID = 237;
private static int value = 0;
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.push_notify_icon);
public void buttonClicked(View v)
{
value ++;
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());
}
}
For separate notifications assign different NOTIFICATION_IDs..
For full logic please consider checking my answer.I used the logic with shared preferences and broadcast receiver as i needed to group each user message into single one and be in sight of active notifications.As only by targeting the api level 23 you can get active notifications,it did not help me at all.So i decided to write some slight logic.Check it here if you feel like to.
https://stackoverflow.com/a/38079241/6466619
You need to create the notification so that it can be updated with a notification ID by calling NotificationManager.notify(ID, notification).
The following steps need to be created to update the notification:
Update or create a NotificationCompat.Builder object
Build a Notification object from it
Issue the Notification with the same ID you used previously
An example taken from the android developer docs:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText).setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is updated.
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
...
Also see the Android docs on Stacking Notifications
https://developer.android.com/training/wearables/notifications/stacks.html
You can stack all your notifications into a single group using the setGroup method and passing your groupId string as parameter.
builer.setGroup("GROUP ID STRING" ) ;
NotificationManager nManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setGroup("GROUP_ID_STRING");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());
Now in android i put this code in one activity to show notification when a button pressed.
static int notificationCount = 0;
then
btnNotification.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent notificationIntent = new Intent(AlertsActivity.this,NotificationActivitty.class);
PendingIntent pIntent = PendingIntent.getActivity(AlertsActivity.this,notificationCount,notificationIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
// Construct the notification
Notification.Builder nBuilder = new Notification.Builder(AlertsActivity.this);
nBuilder.setContentTitle("You Have a notification!");
nBuilder.setContentText("See Your Notification");
nBuilder.setSmallIcon(android.R.drawable.btn_star);
nBuilder.setContentIntent(pIntent);
nBuilder.addAction(android.R.drawable.stat_notify_call_mute, "go to", pIntent); // from icecream sandwatch - required api 16
// Build the notification
Notification noti = nBuilder.build(); // required api 16
//Send it to manager
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.notify(notificationCount++,noti);
}
}
);
From Notification manager, Any notification that i clicked on it, it will redirect me to another activity (NotificationActivity)
Now i put this code to clear the notification but it only clear the notification with id 0 so how can i clear the current pressed notification
public class NotificationActivitty extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.cancel(0);
// manager.cancelAll(); // Cancel all notifications for this app. from manager
}
I need to clear the notification by it's id if it's possible.
You should add a Tag to your notification and then clear you notification by providing correct id and correct tag.
You don't need notification counter if you pass the same id, because when notification sees the same id, it clears old notification and puts a new one, unless you want to show that user received multiple notifications.
private static final String TAG = "YourNotification";
private static final int NOTIFICATION_ID = 101;
private Notification notification;
public NotificationManager notificationManager;
//you can create notification with it's own id and tag, text, etc by passing
//these variables into the method (int id, String tag, ... etc)
public void createNotification()
{
notification = new Notification.Builder(context)
.setContentTitle("Content title")
.setContentText("Content text")
.setSmallIcon(R.drawable.your_small_icon)
.setLargeIcon(bitmapYourLargeIcon)
.setContentIntent(pendingIntent)
.addAction(R.drawable.icon, pendingIntentAction)
.build();
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(TAG, NOTIFICATION_ID, notification);
}
to cancel notification simply use this method:
//clears your notification in 100% cases
public void cancelNotification(int id, String tag)
{
//you can get notificationManager like this:
//notificationManage r= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(tag, id);
}
you need to add this line of code when you create your notification!!!
notification.flags |= Notification.FLAG_AUTO_CANCEL;
This will cancel the notification on click.
Further reading: Open application after clicking on Notification
** Edit, adding an extra to determine if certain notification was clicked
pIntent.putExtra("fromNotification", true);
Also you can use notification channels https://developer.android.com/develop/ui/views/notifications#ManageChannels