Open Application home page after dismissing notification - android

Upon pressing the back button, after opening the notification, the user is taken back to the Home screen instead of going back to the main page of the application. (Using a Samsung S5 with Android 5.0)
The notification is built and shown as follows:
NotificationManager mNotifyMgr =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(GcmMessageHandler.this, ListViewItemDetailActivity.class);
Bundle b = new Bundle();
//... put some data
resultIntent.putExtras(b);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(GcmMessageHandler.this);
stackBuilder.addParentStack(ListViewItemDetailActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(GcmMessageHandler.this)
.setContentTitle("Notification")
.setSmallIcon(R.drawable.common_signin_btn_icon_dark)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(resultPendingIntent)
.setPriority(0)
.setContentText(title);
mNotifyMgr.notify(mNotificationId++, mBuilder.build());
Also in the Manifest file, i have set the parentActivity as follows
<activity
android:name=".ListViewItemDetailActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>

The simplest thing that you can do is pass the bool variable form your notification e.g**(_Is_Coming_From_notification)** and in your ListViewItemDetailActivity activtiy get that variable and based on that if user go back open your app home page.
below is some code for your reference.
resultIntent.putExtra("is_Comming_Form_Notification", true);
get that in your activity.
boolean _Is_Comming_From_Notification = intent.getBooleanExtra("is_Comming_Form_Notification", false);
and in your BackPressed method
#Override
public void onBackPressed() {
if (_Is_Comming_From_Notification ) {
Intent intent = new Intent(this, App_Home_Page.class);
startActivity(intent);
}
super.onBackPressed();
}

Related

Unable to create back stack for activities

I am receiving a notification and i want to create a custom back stack so the user can navigate through it.But as of now clicking on the notification opens the desired activity but when i press the back button it completely exits the app.
Intent resultIntent = new Intent(this, NotifViewActivity.class);
resultIntent.putExtra(StringHolder.NOTIFICATION_ID, notif.getId());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(HomeActivity.class);
stackBuilder.addParentStack(NotifActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentTitle(notif.getTitle())
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(resultPendingIntent);
Manifest File
<activity
android:name=".NotifActivity"
android:parentActivityName=".HomeActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".HomeActivity" />
</activity>
<activity
android:name=".NotifViewActivity"
android:parentActivityName=".NotifActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".NotifActivity" />
</activity>
The way i want it to work is,on click of the notification the user is taken to
NotifViewActivity then when back button is pressed the user is taken to NotifActivity and when back button is pressed again the user is taken to
HomeActivity .Thats the hierarchy i am trying to create,how can i do that?
You should build your task stack that way:
stackBuilder.addParentStack(HomeActivity.class);
stackBuilder.addParentStack(NotifActivity.class);
stackBuilder.addNextIntentWithParentStack(resultIntent);
Or actually because you already specifying activity hierarchy in manifest, you can do it with just one line:
stackBuilder.addNextIntentWithParentStack(resultIntent);
Or another way to archive the same without specifying hierarchy in manifest:
Intent mainActivityIntent = new Intent(this, HomeActivity.class);
Intent notifActivityIntent = new Intent(this, NotifActivity.class);
stackBuilder.addNextIntent(mainActivityIntent);
stackBuilder.addNextIntent(notifActivityIntent);
stackBuilder.addNextIntent(resultIntent);
For anyone who is trying to start those the created activity with TaskStackBuilder, follow #Divers solution and then use taskStackBuilder.startActivities().
try this :
put below code into NotifViewActivity
#Override
public void onBackPressed() {
Intent i = new Intent(this, HomeActivity.class);
i.putExtra("exit", true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
super.onBackPressed();
}

Android navigation up about notification with TaskStackBuilder

I want to start the "ChatActivity" of my app by click Notification, and when i click back button, we will go to the "MainActivity" of my app. I write my code as the Android Notification Guide. My code is follow.
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentTitle("你有" + unreadCount + "条新的消息")
.setContentText(content)
.setNumber((int) unreadCount)
//.setColor(Color.RED)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.mipmap.icon_notify_bold);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
Intent resultIntent = new Intent(context, ChatActivity.class);
resultIntent.putExtra("to", CommonUtils.removeString(conversation.communicator,
ProfileHelper.getProfile().username));
resultIntent.putExtra("conversationId", conversation.id);
taskStackBuilder.addParentStack(ChatActivity.class);
taskStackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
manager.notify(NOTIFY_ID_MESSAGE, builder.build());
My manifest xml is like this:
<activity
android:name=".ui.HomeActivity"
android:label="#string/homepage"
android:launchMode="singleTask"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ui.ChatActivity"
android:label="#string/back"
android:launchMode="singleTask"
android:parentActivityName=".ui.HomeActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.HomeActivity" />
</activity>
My problem is when I press back button in ChatActivity, the HomeActivity will be recreated even if I already started my app. If I have started my app and stay at the HomeActivity page, I think it should not created again. How to avoid recreate HomeActivity?
Any help is grateful.
On ChatActivity class add the following code snippet
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

Why do we use the TaskStackBuilder?

Why do we use the TaskStackBuilder when creating a notification? I do not get the logic behind it.
Can someone please explain.
public void showText(final String text){
Intent intent = new Intent (this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(text)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICACTION_ID, notification);
}
Suppose you have an email sending app and you have two activities in it. One is MainActivity which has the email list and other one is for displaying an email (EmailViewActivity). So now when you receive a new email you display a notification on statusbar. And now you want to view that email when a user clicks on it and also after displaying the email if the user clicks back button you want to show the email list activity(MainActivity). For this scenario we can use TaskStackBuilder. See below example:
public void showEmail(final String text){
Intent intent = new Intent (this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
Intent intentEmailView = new Intent (this, EmailViewActivity.class);
intentEmailView.putExtra("EmailId","you can Pass emailId here");
stackBuilder.addNextIntent(intentEmailView);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(text)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICACTION_ID, notification);
}
Hope you can understand.
Follow below urls for more details:
http://developer.android.com/reference/android/support/v4/app/TaskStackBuilder.html
http://developer.android.com/guide/components/tasks-and-back-stack.html
http://www.programcreek.com/java-api-examples/index.php?api=android.app.TaskStackBuilder
To provide proper navigation.
1) When the app is launched by App icon (Normal Flow)
**
2) When the app is launched by some Notification
General flow of navigation in your app is MainActivity->DetailActivity
But sometimes a Notification might directly open the DetailActivity. In this case, pressing the back button in DetailActivity will not lead you to the `MainActivity. It's an EXPECTED BEHAVIOR. However, you can modify this if you want to navigate back to MainActivity.
How do I do it?
1) Add android:parentActivityName="com.example.myApp.MainActivity in your Activity
This feature was added in Android 4.1. So if you want to target older devices. Add a meta-tag ALSO.
<activity android:name=".Activities.DetailActivity"
android:parentActivityName=".Activities.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".Activities.MainActivity" />
</activity>
2) Use TaskStackBuilder to create a Pending Intent.
public PendingIntent getPendingIntent(Intent intent){
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
taskStackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
}
Now pass this Pending intent to create Notifications.
We use a TaskStackBuilder to make sure that the back button will play nicely when the activity gets started. The TaskStackBuilder allows you to access the history of activities used by the back button. Basically, we use it when we want the user to navigate to another activity after pressing back button.
I know it has been a while but I came across this problem, this time, my stack had several levels of depth. Looking at the good answers here, I was able to infer it for 3 levels or more of course. As it looks straight forward, it did not look so at the beginning for me because I was triplicating the back stack. Hope it helps someone. Be sure to have the Manifest.xml set up properly
Anyway, for those with several levels, this works nicely:
Intent level3Intent = new Intent(this, Level3.class);
level3Intent.putExtra(YOUR STUFF);
Intent level2Intent = new Intent(this, Level2.class);
//level2Intent.putExtra(YOUR STUFF);
Intent level1Intent = new Intent(this, MainActivity.class);
// Get the PendingIntent containing the entire back stack with the needed extras
PendingIntent pendingIntent =
TaskStackBuilder.create(this)
.addParentStack(MainActivity.class)
.addNextIntent(level1Intent)
.addNextIntent(level2Intent)
.addNextIntent(level3Intent)
.getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle(notification_title)
.setContentText(notification_msg)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notification_msg))
.setSmallIcon(R.drawable.ic_sea)
.setDefaults(Notification.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis())
.setGroup(OWS_GROUP)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
The other answers explained it nicely: you use a pending intent to send a user into a detail activity, then you want them to use the back button to go back to the main activity. An alternative way to set this is
Intent detailIntentForToday = new Intent(context, DetailActivity.class);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(detailIntentForToday);
PendingIntent resultPendingIntent = taskStackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
resultPendingIntent.send();
For this, you also need to set
android:parentActivityName=".MainActivity"
for the DetailActivity in AndroidManifest.xml.
I had the same problem and I solved in this way:
As already suggested, I added
android:parentActivityName=".MainActivity" in my AndroidManifest file.
I also added to every classes the method onResume
I used TaskStackBuilder to create a Pending Intent:
Intent intent = new Intent(context, myClass);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

Up navigation using backstack not working while clicked from notification

I am opening an activity from notification, which opens fine.
However, I want to open it's parent activity while I click 'back button', currently it exits the application directly. I want it to navigate to HomeScreenActivity.
Here is manifest declaration -
<activity
android:name="com.discover.activities.MyTrialsActivity"
android:exported="true"
android:parentActivityName="com.discover.activities.HomeScreenActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.discover.activities.HomeScreenActivity" />
</activity>
Here is my code to generate notification -
public static PendingIntent getAction(Activity context, int actionId) {
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(context, MyTrialsActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack
//stackBuilder.addParentStack(HomeScreenActivity.class);
stackBuilder.addParentStack(HomeScreenActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(intent);
// Gets a PendingIntent containing the entire back stack
pendingIntent =
stackBuilder.getPendingIntent(0 /*request code */, PendingIntent.FLAG_ONE_SHOT);
/*pendingIntent = PendingIntent.getActivity(context, 0 *//* Request code *//*, intent,
PendingIntent.FLAG_UPDATE_CURRENT*//*|PendingIntent.FLAG_ONE_SHOT*//*);*/
return pendingIntent;
}
/**
* Create and show a simple notification containing the message.
*
* #param message Message to show in notification
*/
public static void sendNotification(Context context, String message, int actionId) {
PendingIntent pendingIntent = NotifUtils.getAction((Activity) context, actionId);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{1000})
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I you have everything set up correctly and it's still not working it might be that you need to uninstall and reinstall the app. It seems like some changes to the manifest are not updated properly when you run the app!
Solution -
I added my child activity as well in addParentStack(MyTrialActivity.class);
And it worked as expected.
I thought adding addNextIntent() should be doing that already, though it did not work that way..
I found the solution in android's documentation
// Intent for the activity to open when user selects the notification
Intent detailsIntent = new Intent(this, DetailsActivity.class);
// Use TaskStackBuilder to build the back stack and get the PendingIntent
PendingIntent pendingIntent =
TaskStackBuilder.create(this)
// add all of DetailsActivity's parents to the stack,
// followed by DetailsActivity itself
.addNextIntentWithParentStack(upIntent)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pendingIntent);
And,
Here is the link.
Also, see this answer for more references.
Try using startActivities(Context context, Intent[] intents),
Intent homeIntent = new Intent(context, HomeScreenActivity.class);
Intent newIntent = new Intent(context, MyTrialsActivity.class);
Intent[] intents = new Intent[]{homeIntent, newIntent};
ContextCompat.startActivities(context, intents);
So we can start multiple activities at same time, so while pressing Back button it will go to Home Page instead of quiting the application.

How do you build an Android back stack when an activity is started directly from a notification?

I have two activities:
Activity A - list of items
Activity B - detail view of an item
Normally, a user opens the app and Activity A is launched. A user sees a list of items, clicks one, and Activity B is started to display the item detail.
Activity B can also be started directly from clicking on a notification. In this case there is no back stack.
How can I make it so that when Activity B is started directly from a notification, the user can click the Back button and go to Activity A?
You can add an Extra into the Intent launched by the notification to detect when the app has been launched in that way.
Then you can override the onBackPressed() Activity method and handle that scenario, e.g.
#Override
public void onBackPressed()
{
Bundle extras = getIntent().getExtras();
boolean launchedFromNotif = false;
if (extras.containsKey("EXTRA_LAUNCHED_BY_NOTIFICATION"))
{
launchedFromNotif = extras.getBoolean("EXTRA_LAUNCHED_BY_NOTIFICATION");
}
if (launchedFromNotif)
{
// Launched from notification, handle as special case
Intent intent = new Intent(this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
mActivity.startActivity(intent);
finish();
}
else
{
super.onBackPressed();
}
}
You should take care of this when you receive the Notification.
I have a similar situation solved:
Intent intent = new Intent(context,ListDetail.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ListDetail.class);
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotifM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder mBuilder = new Notification.Builder(context);
mNotifM.notify(NotificationId.getID(), mBuilder.setStyle(new Notification.BigTextStyle(mBuilder)
.bigText(bigText)
.setBigContentTitle(title)
.setSummaryText(summaryText))
.setContentTitle(title)
.setSmallIcon(icon)
.setContentText(summaryText)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setTicker(bigText)
.build());
You need to set in your Manifest the hierarchy of the Activities:
<activity
android:name=".ListDetail"
android:label="Detail"
android:parentActivityName=".List" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".List" />
</activity>
I have tried one sample.Please go through with this link
https://github.com/rajajawahar/NotificationBackStack
Activity you want to launch..
Intent launchIntent = new Intent(context, SecondActivity.class).putExtra("Id", id);
Parent Activity, if back pressed
Intent parentIntent = new Intent(context, FirstActivity.class);
Add Both the activity in the taskbuilder
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
PendingIntent resultPendingIntent = stackBuilder.addNextIntentWithParentStack(parentIntent).addNextIntent(launchIntent).getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notificationCompatBuilder =
new NotificationCompat.Builder(context);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, notificationCompatBuilder.build());
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationCompatBuilder.setAutoCancel(true).
setContentTitle("First Notification").
setContentText("Sample Text").
setSmallIcon(R.mipmap.ic_launcher).
setContentIntent(resultPendingIntent);
mNotifyMgr.notify(id, notificationCompatBuilder.build());
catch the back-button-key event with onKeyDown()-method and let the user go to activity A. Don't forget to return true to prevent the event from being propagated further.
http://developer.android.com/reference/android/app/Activity.html#onKeyDown(int, android.view.KeyEvent)

Categories

Resources