I would like to display the status of notification depending on order status changes. As of now, i am able to display it. Now the next task is that when user clicks on notification, I prefer to take this to the track order fragment where the user can see his order status in detail.
Here is my code:
public static void createNotification(FragmentActivity activity, boolean isLoggedIn, String selectedOrderId, String order_status, String status_desc)
{
NotificationCompat.Builder builder =
new NotificationCompat.Builder(activity)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Lugmah Order Status")
.setContentText("The Order Status of Order Id: "+selectedOrderId+ "is: "+status_desc)
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setAutoCancel(true);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(activity, TrackOrderFragment.class);
targetIntent.putExtra("isTrackOrder", false);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
if(isLoggedIn)
{
if(status_desc.equals("Rejected"))
{
targetIntent.putExtra("isLoggedIn", true);
targetIntent.putExtra("status_desc", status_desc);
fragment.setArguments(bundle);
bundle.putString("status_desc", status_desc);
bundle.putString("selectedOrderId", selectedOrderId);
targetIntent.putExtras(bundle);
stackBuilder.addParentStack(TrackOrderFragment.class);
stackBuilder.addNextIntent(targetIntent);
}
}
else
{
targetIntent.putExtra("isLoggedIn", false);
}
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
//PendingIntent contentIntent = PendingIntent.getActivity(activity, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
}
And I would like to pass the data that is Status_desc and SelectedOrderId between two fragments.
To receive data, here is the code I wrote.
status_desc = getArguments().getString("status_desc");
rejectedOrderId = getArguments().getString("rejectedOrderId");
Here the I am getting notification when admin changes order status. But, I am not able to navigate to TrackOrderFragment.class onClick of Notification.
Help would be appreciated.
You can try the below code on button click
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
May be doing
Intent targetIntent = new Intent(activity, TrackOrderActivity.class); instead of Intent targetIntent = new Intent(activity, TrackOrderFragment.class); would help you. You may send a flag as intent extra to know whether the activity is created from notification. Attach the fragment with that activity.
I was mainly talking about this code block.
NotificationCompat.Builder builder =
new NotificationCompat.Builder(activity)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Lugmah Order Status")
.setContentText("The Order Status of Order Id: "+selectedOrderId+ "is: "+status_desc)
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setAutoCancel(true);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(activity, TrackOrderActivity.class);
targetIntent.putExtra("isTrackOrder", false);
Bundle bundle = new Bundle();
if(isLoggedIn)
{
if(status_desc.equals("Rejected"))
{
targetIntent.putExtra("isFromNotification", true);
bundle.putString("status_desc", status_desc);
bundle.putString("sejectedOrderId", selectedOrderId);
targetIntent.putExtra("orderBundle",bundle);
}
}
else
{
targetIntent.putExtra("isLoggedIn", false);
}
//PendingIntent
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
targetIntent, 0);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Now inside of the TrackOrderActivity onCreate method do this.
setContentView(R.layout.activity_track_order);
if(getIntent().getBooleanExtra("isFromNotification",true)){
TrackOrderFragment fragment = new TrackOrderFragment();
fragment.setArguments(getIntent().getBundleExtra("orderBundle"));
getSupportFragmentManager().beginTransaction().
replace(R.id.container,fragment).commit();
}
Now on your TrackOrderFragment if you call getArguments() I think you will get your bundle data.
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 want to open a fragment when the app receive a notification for further processing. In my MainActivity.java, getIntent().getExtras() always return null.
MyFirebaseMessagingService.java
private void sendNotification(String title, String messageBody, String newsID, String newsType) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bundle extras = new Bundle();
extras.putString("newsID", String.valueOf(newsID));
extras.putString("newsType", String.valueOf(newsType));
intent.putExtras(extras);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
MainActivity.java
Bundle i = getIntent().getExtras();
if (i != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.e("News ID", value);
if (key.equals("newsID") ) {
dbHelper.insertNewsID(String.valueOf(value));
//show news details
getSupportFragmentManager()
.beginTransaction()
.replace(ng.naijaleague.R.id.frame_container, new NewsDetails())
.addToBackStack(null).commit();
}
}
String newsType = getIntent().getExtras().getString("newsType");
if ("newsType".equals(newsType) ) {
String value = getIntent().getExtras().getString("newsType");
if("Local".equals(value)){
//add news type to shared preference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("newType", "Local");
editor.apply();
}else{
//add news type to shared preference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("newType", "Foreign");
editor.apply();
}
}
}
I have followed through all the solutions I found on SO but none of them have worked so far. What must be wrong with the code?
POST THIS 4 lines before making PendingIntent Object :P
Bundle extras = new Bundle();
extras.putString("newsID", String.valueOf(newsID));
extras.putString("newsType", String.valueOf(newsType));
intent.putExtras(extras);
LIKE:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//PUT HERE
Bundle extras = new Bundle();
extras.putString("newsID", String.valueOf(newsID));
extras.putString("newsType", String.valueOf(newsType));
intent.putExtras(extras);
//THEN Create PendingIntent Object
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Hope it will helps you :)
Thanks to everyone, all the answers moved me closer to making it work but I needed to change the PendingIntent to the following to nail it.
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Thanks...<3
move extras assign before Pending intent is created
add flag:
FLAG_ACTIVITY_NEW_TASK
Note than when using PendingIntent.getActivity(...) the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.
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);
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.
I'm developing an android app where I display notifications with actions. But on action click notification not clearing, It stuck in that shade. How do I clear a notification on action click?
MY CODE
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
PendingIntent openSettingsActivity = PendingIntent.getActivity(this,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.addAction(R.drawable.ic_notification_button, "Settings", openSettingsActivity);
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setColor(color);
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
notificationBuilder.setContentIntent(openSettingsActivity);
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());
Hiding notifications should be processed in the place where the intent is sent.
In your current code:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("hide_notification", true); //add boolean to check later in activity if it should remove notification on activity create
And in your activity smth like this, to check if it should remove notification:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check for notification remove
boolean hideNotification = getIntent().getBooleanExtra("hide_notification", false);
if (hideNotification) {
NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
nmc.cancel(1); //1 - is your notification id
}
}
Depends on what you want, maybe it will be better to call that not in onCreate() but onStart()