I would like to put two buttons on my notifications from the status bar. Of course they do not appear until the user touches to expand them. I have created the custom layout for my notification using RemoteViews but am unsure if it's possible to obtain a reference to them because of my current code structure.
#Override
public void onMessage(Context context, Intent intent) {
Log.w("C2DMReceiver",
"Message Received, this is the message with no payload");
Bundle extras = intent.getExtras();
if (extras != null) {
String[] payload = new String[3];
payload[0] = (String) extras.get("payload");
payload[1] = (String) extras.get("payload2");
SharedPreferences sharedP = Prefs.get(this);
boolean inApp = sharedP.getBoolean("currentlyInApp", true);
if (!inApp) {
createNotification(context, payload);
}
}
}
public void createNotification(Context context, String[] payload) {
SharedPreferences sharedP = Prefs.get(context);
boolean needsToLogin = sharedP
.getBoolean("loginFromNotification", true);
Log.w("C2DMReceiver", "createNotification called");
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, WebViewActivity.class);
Intent notificationIntent2 = new Intent(this, UniteActivity.class);
PendingIntent pIntent;
if (needsToLogin) {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent2,
PendingIntent.FLAG_CANCEL_CURRENT);
} else {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
// Compatibility builder
NotificationCompat.Builder notification = new NotificationCompat.Builder(
context);
RemoteViews remote = new RemoteViews(getPackageName(),R.layout.notification);
//Button okButton = (Button) findViewById(R.layout.notification);
notification.setAutoCancel(false);
notification.setContent(remote);
notification.setContentIntent(pIntent);
notification.setWhen(System.currentTimeMillis());
notification.setTicker(payload[0]);
notification.setSmallIcon(R.drawable.default1);
notification.setContentTitle(payload[1]);
notification.setContentText(payload[0]);
long duration[] = { 100, 300, 100 };
notification.setVibrate(duration);
notificationmanager.notify(0, notification.getNotification());
}
onMessage is a method pulled from the Google C2DM library where the notifications are generated by intents received from google. Without a view, how can I obtain a reference to my buttons using findViewById()? or some other means
I think you are looking for the method:
RemoteViews.setOnClickPendingIntent(int, android.app.PendingIntent)
So, if you add...
remote.setOnClickPendingIntent(R.id.button, pIntent);
...it should work.
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 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 have an BroadcastReciver that listens for incoming sms. When sms come, it shows notification. I want, when user open notification, it's go to result activity, and it's open google map via intent.
I think I wrote everything ok, but it doesn't work. When the notification is clicked, it opens a blank page.
My incomingSms BroadcastReciver :
public void ShowNotif(String from , String body , Context con){
NotificationCompat.Builder builder =
new NotificationCompat.Builder(con)
.setSmallIcon(R.drawable.ic_search)
.setContentTitle(from)
.setContentText(body);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(con,Resualt.class );
targetIntent.putExtra("loc",body);
PendingIntent contentIntent = PendingIntent.getActivity(con, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) con.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Intent goResIntent = new Intent(con , Resualt.class);
con.startActivity(goResIntent);
// gogole map intent :
}
and Resualt acitivty :
public class Resualt extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.resualt);
double Mylatitude = 12;
double Mylongitude = 11;
GPSTracker tracker = new GPSTracker(this);
if (tracker.canGetLocation()) {
Mylatitude = tracker.getLatitude();
Mylongitude = tracker.getLongitude();
}
Intent intent = getIntent();
String location = intent.getStringExtra("loc");
String ACC_lat = location.substring(0, location.indexOf(","));
String ACC_lang = location.substring(location.indexOf(",") + 1, location.length());
Toast.makeText(this, ACC_lang + " ^ " + ACC_lat, Toast.LENGTH_LONG).show();
Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+Mylatitude +","+ Mylongitude+"&daddr="+ACC_lat+","+ACC_lang));
startActivity(mapIntent);
// this.finish();
}
thanks for any help .
You can open a single blank activity through pending intent in notification service and then on that blank activity open a map intent and finish that blank activity.
the link receiving from notification data can be sent through intent as extras
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("location_link", link);
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.