notification in nexus 5 android 6 don't cancel and go away from it. but when i run it on diffrenet device with android 9 or more, notification goes away. please help me.
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent PrevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, PrevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, NOTIFICATION_ID, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture;
picture = getTrackArt(musicFiles.get(position).getPath());
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicnowplaying);
}
Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setChannelId(CHANNEL_ID_2)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOngoing(true)
.setContentTitle(musicFiles.get(position).getSongTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(NOTIFICATION_ID, notification);
}
Related
I have a notification in my music app with following code:
void showNotification(int playPauseBtn){
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class)
.setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
picture = getAlbumArt(musicFiles.get(position).getPath());
Bitmap thumb = null;
if (picture != null){
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
}
else{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(musicFiles.get(position).getTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(2, notification);
notificationManager =
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(2, notification);
}
I have created separate class(ApplicationClass) for creating notification channel.
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel1 =
new NotificationChannel(CHANNEL_ID_1,
"Channel(1)", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("Channel 1 Desc..");
NotificationChannel channel2 =
new NotificationChannel(CHANNEL_ID_2,
"Channel(2)", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("Channel 2 Desc..");
//HERE ABOVE DOUBT
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel1);
notificationManager.createNotificationChannel(channel2);
}
}
}
And also, I have a class (NotificationReceiver) for receiving notification action:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String actionName = intent.getAction();
Intent serviceIntent = new Intent(context, MusicService.class);
if (actionName != null){
switch (actionName){
case ACTION_PLAY:
serviceIntent.putExtra("ActionName", "playPause");
context.startService(serviceIntent);
break;
case ACTION_NEXT:
serviceIntent.putExtra("ActionName", "next");
context.startService(serviceIntent);
break;
case ACTION_PREVIOUS:
serviceIntent.putExtra("ActionName", "previous");
context.startService(serviceIntent);
break;
}
}
}
}
My notification functions(play, pause & next) works properly, but my problem is that, I am unable to clear notification. I tried many times but I could not get it right.
try this
void showNotification(int playPauseBtn){
Intent intent = new Intent(this, NotifAction.class);
//add this to get IdNotif.for all intent
intent.putextra("NotifId",notifId);
//
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotifAction.class)
.setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
picture = getAlbumArt(musicFiles.get(position).getPath());
Bitmap thumb = null;
if (picture != null){
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
}
else{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(musicFiles.get(position).getTitle())
.setContentText(musicFiles.get(position).getArtist())
.addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
.addAction(playPauseBtn, "Pause", pausePending)
.addAction(R.drawable.ic_skip_next, "Next", nextPending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
startForeground(notifId, notification);
notificationManager =
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notifId, notification);
}
set notifId for eachNotification and make this class for handle all action in notification.
note :
To set each event for each notification button, you first rationalize all actions to the NotifAction class, and from there define click events for each using the class.
create class for HandleAction:
public class NotifAction extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
if (action.equals("YourActionName")) {
clearNotification(extra.getInt("YourNotifId",0),context);
Toast.makeText(context, "YourMessage!", Toast.LENGTH_SHORT).show();
} else
/// another event for each action
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}
I am building a notification which has ACCEPT and REJECT buttons but at the same time i also wants to open the activity when user touches over the notification. But in my case only both buttons working and when touched over the other parts than buttons it just disappears.
My efforts :
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String NOTIFICATION_CHANNEL_ID = "BizPhone Channel";
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(context, incoming_service.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
intent.putExtra(Intent.EXTRA_MIME_TYPES, callType);
intent.putExtra("NOTE", Integer.toString(id));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "BizPhone Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("BizPhone related notifications");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
// assuming your main activity
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_call_black_24dp)
.setPriority(Notification.FLAG_INSISTENT)
.setContentTitle(phoneNumber)
.setContentText("Incoming Call")
.setSound(alarmSound)
.setContentIntent(pendingIntent)
.setContentInfo("Call");
Intent accept = new Intent(context, incoming_service.class);
accept.setAction(incoming_service.ANSWER);
accept.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
accept.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
accept.putExtra(Intent.EXTRA_MIME_TYPES, callType);
accept.putExtra("NOTE", Integer.toString(id));
PendingIntent pendingIntentYes = PendingIntent.getService(context, 10, accept, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.ic_permission_granted_24dp, "ACCEPT", pendingIntentYes);
Intent decline = new Intent(context, incoming_service.class);
decline.setAction(incoming_service.REJECT);
decline.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
decline.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
decline.putExtra(Intent.EXTRA_MIME_TYPES, callType);
decline.putExtra("NOTE", Integer.toString(id));
PendingIntent pendingIntentNo = PendingIntent.getService(context, 11, decline, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.ic_call_end_black_24dp, "REJECT", pendingIntentNo);
//notificationBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notificationBuilder.build());
I have tried by looking at other threads too but it did not help. Any help would be appreciated and thanks in advance.
Change
setAutoCancel(true)
to
setAutoCancel(false)
Just try to add :
PendingIntent contentIntent = builder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
I am answering my own question for future incoming users.
Why notification was disappearing on touch ( outside of 2 buttons but still on notification )
Because the base pendingintent was not a activity and it was a service. You can notice the code above. It should have been like :
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, CallActivity.class);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
intent.putExtra(Intent.EXTRA_MIME_TYPES, callType);
And the 2 buttons code and their pendingintent which is service was okay.
I want to open a website when a push notification is clicked on Android.
This is my code, and it opens the main Activity when I click the notification
. How can I open a website / URL in the browser instead ?
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setContentTitle("Big4Com").setSmallIcon(R.drawable.notification_icon).setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Try this:
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://your-website.com"));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setContentTitle("Big4Com").setSmallIcon(R.drawable.notification_icon).setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
I'm trying to use the AlarmManager to send a notification to the user later in the day, whether he is using the application or not.
I basically pasted what I saw here : http://developer.android.com/guide/topics/ui/notifiers/notifications.html, but obviously something went wrong because instead of showing a notification, the AndroidLauncher Activity is shown.
Here is my code :
public void planNotification() {
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, resultPendingIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 86400000, resultPendingIntent);
}
I'm still new to Intents and PendingIntents, so it may be a dumb mistake.
~~~ ~~~ EDIT : Thank you for your help ! Now that I understood that I need a BroadcastReceiver, I can't get it to work. It looks like onReceive() is never called.
Here is my Main Activity :
#Override
public void planNotification() {
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, alarmIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, alarmIntent);
}
And my BroadcastReceiver :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("ON RECEIVE");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(context, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(AndroidLauncher.notifId, mBuilder.build());
}
}
The way you have it, the alarm manager is directly using your resultIntent.
You should move your notification creation code to a BroadcastReceiver:
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
}
}
And use the AlarmManager to call the BroadcastReceiver:
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
if (currentApiVersion >= 19)
am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, 5000, alarmIntent);
else
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 86400000, alarmIntent);
I have code for creating notification:
NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(mId, "New alert!", System.currentTimeMillis());
Intent alert = new Intent(this, AlertInfoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, alert, 0);
notification.setLatestEventInfo(this, data.get("name"), data.get("post_date"), contentIntent);
notifyMngr.notify((int) System.currentTimeMillis(), notification);
I need to create a few notifications, and each notification must execute a new object of AlertInfoActivity by click. But this code executes 1 object of Activity always. How can I do my task?
You need to create a notification for each activity you want to launch. Like this:
NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//First Notification
Notification notification=new Notification(mId, "New alert!", System.currentTimeMillis());
Intent alert = new Intent(this, AlertInfoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, alert, 0);
notification.setLatestEventInfo(this, data.get("name"), data.get("post_date"), contentIntent);
notifyMngr.notify((int) System.currentTimeMillis(), notification);
//Second Notification
Notification notification2 = new Notification(mId, "Second Alert!", System.currentTimeMillis());
Intent alert2 = new Intent(this, DifferntAcitivty.class);
PendingIntent contentIntent2 = PendingIntent.getActivity(this, 0, notification2, 0);
notification2.setLatestEventInfo(this, data.get("name"), data.get("post_date"), contentIntent2);
notifyMngr.notify((int) System.currentTimeMillis(), notification2);
//Third Notification
Notification notification3=new Notification(mId, "Third Alert!", System.currentTimeMillis());
Intent alert3 = new Intent(this, ThirdActivity.class);
PendingIntent contentIntent3 = PendingIntent.getActivity(this, 0, alert3, 0);
notification3.setLatestEventInfo(this, data.get("name"), data.get("post_date"), contentIntent3);
notifyMngr.notify((int) System.currentTimeMillis(), notification3);
//And so on and so forth.