my code is
public class AlarmReceiver extends BroadcastReceiver {
public Notification mNotification = null;
public NotificationManager mNotificationManager = null;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "time up!", Toast.LENGTH_SHORT).show();
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification = new Notification(R.drawable.icon, "tip!",
System.currentTimeMillis());
mNotification.contentView = new RemoteViews(context.getPackageName(),
R.layout.notification);
mNotification.contentView.setTextViewText(R.id.tv_tip, "click to see the description");
Intent notificationIntent = new Intent(context,NotificationTip.class);
notificationIntent.putExtra("description", intent.getStringExtra("description")) ;
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
mNotification.contentIntent = contentIntent;
mNotificationManager.notify(0, mNotification);
}
}
While when I click the item in notification ,I can't get to NotificationTip activity,so what's wrong with this code?
following line
Intent notificationIntent = new Intent(context,NotificationTip.class);
needs to be
Intent notificationIntent = new Intent("X");
Where X is the intent action name. this you have to add as intent filter in your android manifest file.
Related
I want to update the content for a reminder after it has been added before being received by the user. After setting a reminder through AlarmManager using the data stored in sqlite database, the notification from the reminder set only shows the data, title and description, that was first added, not any updated data stored corresponding to the ID as primary key.
Things I have tried:
cancelling the pending intent for the reminder then setting it again after updating the data stored in the database but it still displays the same result.
using an activity for adding data to be stored in the database to set a reminder and using another activity for updating this data as an attempt to update the reminder content with the same ID issued. One result shows two notifications received, one with initial title and description, and the other with updated information.
Currently, the methods I use to set and cancel a reminder is in my Adapter class for Recyclerview. I am stuck on updating although adding and cancel works fine.
Update: Now I use two separate activities for the add and update reminder functions.
For adding a reminder:
databaseManager.addReminder(titlePicked, descriptionPicked, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
setAlarm();
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remId);
intent.putExtra("Title", titlePicked);
intent.putExtra("Description", descriptionPicked);
PendingIntent addIntent = PendingIntent.getBroadcast(this, remId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), addIntent);
}
For updating a reminder:
databaseManager.updateReminder(remindId, titlePicked2, descriptionPicked2, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
updateAlarm();
private void updateAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remindId);
intent.putExtra("Title", titlePicked2);
intent.putExtra("Description", descriptionPicked2);
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), updateIntent);
}
Receiver class:
public class ReminderReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "CHANNEL_REMIND";
String DateTimeChoice, TitleChoice, DescriptionChoice;
int notificationID;
#Override
public void onReceive(Context context, Intent intent) {
DateTimeChoice = intent.getStringExtra("DateTime");
notificationID = intent.getIntExtra("NotifID", 0);
TitleChoice = intent.getStringExtra("Title");
DescriptionChoice = intent.getStringExtra("Description");
Intent mainIntent = new Intent(context, ViewReminder.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, notificationID, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For API 26 and above
CharSequence channelName = "My Notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(TitleChoice)
.setContentText(DescriptionChoice)
.setContentIntent(contentIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.getResources().getColor(R.color.purple_700))
.setAutoCancel(true);
notificationManager.notify(notificationID, builder.build());
}
Adapter class:
int remindId = reminder.getReminderId();
databaseManager = new DatabaseManager(holder.view.getContext());
sqLiteDB = databaseManager.getWritableDatabase();
public void onClick(View view) {
Reminder reminder = remindList.get(holder.getAdapterPosition());
PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Intent intent = new Intent(view.getContext(), UpdateReminderActivity.class);
intent.putExtra("reminderId", remindId);
intent.putExtra("title", reminder.getReminderTitle());
intent.putExtra("definition", reminder.getReminderDefinition());
view.getContext().startActivity(intent);
return true;
}
});
For updating a pending intent, you need to use FlAG_UPDATE_CURRENT with the same id you used earlier to set the initial intent.
If you want to update the alarm associated with that pending intent, you need to cancel the old alarm & then the old PendingIntent. Then create a new PendingIntent like this,
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent,PendingIntent.FLAG_UPDATE_CURRENT);
and set it to the alarm.
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 create multiple notifications using AlarmManager. Each notification pop-ups correctly and I would like to cancel each of these notification separately. I have an AlarmReceiver that creates the notification and sets the unique id for it. I'm sending the unique id in the intent (via putExtra). This way, I can retrieve it in the NotificationReceiver and cancel the notification. However, it is not working.
Do you know why I always get the default value when I use intent.getIntExtra("UNIQUE_ID_NAME",0) ?
Is it a proper way to achieve the goal of cancelling these notifications ?
Here is my code:
MainActivity class:
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ReminderBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
long ctime = System.currentTimeMillis();
long tensec = 1000 * 5;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, ctime+tensec, 1000*10 , pendingIntent);
}
AlarmReceiver Class:
#Override
public void onReceive(Context context, Intent intent) {
int notification_id = generateRandom();
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent bYesIntent = new Intent(context, NotifReceiver.class);
bYesIntent.putExtra(NotificationReceiver.YES_ACTION_ID, "yesID");
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, 0, bYesIntent, 0);
Intent bNoIntent = new Intent(context, NotifReceiver.class);
bNoIntent.putExtra(NotificationReceiver.NO_ACTION_ID, "noID");
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, 0, bNoIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel1")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Notif")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(contentIntent)
.addAction(R.mipmap.ic_launcher, "YES", actionYesIntent)
.addAction(R.mipmap.ic_launcher, "NO", actionNoIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notification_id, builder.build());
}
public int generateRandom(){
Random random = new Random();
return random.nextInt(9999 - 1000) + 1000;
}
NotificationReceiver Class:
public class NotificationReceiver extends BroadcastReceiver {
public static String YES_ACTION_ID = "YesID";
public static String NO_ACTION_ID = "NoID";
public static String UNIQUE_ID_NAME = "notification_id";
#Override
public void onReceive(Context context, Intent intent) {
int notification_id= intent.getIntExtra(UNIQUE_ID_NAME,0);
System.out.println("Notif ID: " + notification_id); // here always is 0;
String actionYes = intent.getStringExtra(YES_ACTION_ID);
String actionNo = intent.getStringExtra(NO_ACTION_ID);
if(actionYes!=null){
Toast.makeText(context, "YES", Toast.LENGTH_SHORT).show();
}
if(actionNo!=null){
Toast.makeText(context, "NO", Toast.LENGTH_SHORT).show();
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notification_id);
}
}
I solved this problem by updating current intent and request code. Notifications are reusing the same Intent so adding FLAG_UPDATE_CURRENT should be used to be able to cancel all notification separately.
For contentIntent:
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
For actionYesIntent
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, notification_id, bYesIntent, PendingIntent.FLAG_UPDATE_CURRENT);
For actionNoIntent:
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, notification_id, bNoIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You are not adding notification_id for cases when Yes or No button is pressed,
Intent bYesIntent = new Intent(context, NotifReceiver.class);
bYesIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
bYesIntent.putExtra(NotificationReceiver.YES_ACTION_ID, "yesID");
PendingIntent actionYesIntent = PendingIntent.getBroadcast(context, 0, bYesIntent, 0);
Intent bNoIntent = new Intent(context, NotifReceiver.class);
bNoIntent.putExtra(NotificationReceiver.UNIQUE_ID_NAME, notification_id);
bNoIntent.putExtra(NotificationReceiver.NO_ACTION_ID, "noID");
PendingIntent actionNoIntent = PendingIntent.getBroadcast(context, 0, bNoIntent, 0);
I have wired up a notifications action handler with PendingIntent.getBroadcast that shows actions inside the notification. The actions work fine, when I use the default click event on the heads up notification it works fine. My issue comes when the notification is in the tray and I have other notifications in the drawer, I am trying to program the default click/touch event on the notification to broadcast to the receiver and run an action. Here is some code:
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
//CLICK ON NOTIFICATION HERE ONLY WORKS ON HEADS UP AND NOT DEFAULT
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class);
notificationIntent.putExtra("visitId", visitId);
notificationIntent.putExtra("link", link);
notificationIntent.setAction(ACCEPT_EXAM);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(clickIntent);
//Accept intent action works fine
Intent acceptExam = new Intent(ctx, PushNotificationActions.class);
acceptExam.setAction(ACCEPT_EXAM);
acceptExam.putExtra("visitId", visitId);
acceptExam.putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent action works fine
Intent dismissExam = new Intent(ctx, PushNotificationActions.class);
dismissExam.setAction(DISMISS_EXAM);
dismissExam.putExtra("visitId", visitId);
dismissExam.putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);
Here is the onReceive method:
private Context context;
#Override
public void onReceive(Context ctx, final Intent intent) {
Log.d("PushNotificationActions","Started");
String action = intent.getAction();
Log.d("<-------------------<<<", "getaction is: " + action);
context = ctx;
if (ACCEPT_EXAM.equals(action)) {
Log.d("ACCEPT_ACTION", "READY FOR EXAM NOW");
Map<String, String> params = new HashMap();
params.put("email", email);
final JSONObject parameters = new JSONObject(params);
Log.d("parameters: ", parameters.toString());
volleyJsonObjectPost("ws", parameters, new Login.ServerCallback() {
public void onSuccess(JSONObject response) {
try {
final JSONObject loginData = response.getJSONObject("d");
DataModel.sharedInstance().key = loginData.getString("key");
final String visitLink; String link; final String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
link = extras.getString("link");
visitId = extras.getString("visitId");
visitLink = link + loginData.getString("key") + ',' + visitId;
JSONObject params = new JSONObject();
params.put("key", loginData.getString("key"));
Log.d("params: ", params.toString());
volleyJsonObjectPost("ws", params, new Login.ServerCallback() {
public void onSuccess(JSONObject result) {
try {
final JSONObject acceptExamResultData = result.getJSONObject("d");
Log.d("acceptExamResultData: ", acceptExamResultData.toString());
if (acceptExamResultData.getBoolean("status") == true) {
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(visitLink));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.android.chrome");
try {
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
} catch (ActivityNotFoundException ex) {
// Chrome browser presumably not installed so allow user to choose instead
intent.setPackage(null);
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}else {
// Exam was already accepted by another Doc
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}else if (DISMISS_EXAM.equals(action)) {
Log.d("DISMISS_ACTION", "I CANNOT TAKE THIS EXAM");
String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
visitId = extras.getString("visitId");
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("Visit ID to cancel", visitId);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}
Here is the receiver in the manifest:
<receiver android:name=".PushNotificationActions" >
<intent-filter>
<action android:name="com.Telemed.app.ACCEPT_EXAM" />
<action android:name="com.Telemed.app.DISMISS_EXAM" />
</intent-filter>
</receiver>
Since the notification won't slide easy in the drawer in most cases I need this default functionality to mirror the Accept Exam Action. Only I don't want it to be an action, I just want it to work when the user clicks on the notification. I need to use getBroadcast because I am making a web service call (async) to get some data I need to do the next step
So in order to set the default functionality for the notification you have to create a default pending intent before constructing your notification builder:
Like so:
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Now after that set this:
.setContentIntent(clickIntent)
in the new NotificationCompat.Builder. After that you can set up as many actions as you want but the default will still access your action and act as a default in the case where the drawer sticks your notification at the to and you cannot see your programmed actions.
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("TELEMED PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(clickIntent)
.setAutoCancel(true);
//Accept intent
Intent acceptExam = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent
Intent dismissExam = new Intent(ctx, PushNotificationActions.class).setAction(DISMISS_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);
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());
}