Up navigation using backstack not working while clicked from notification - android

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.

Related

Going back to main activity after launching activity from notification

I launch an activity from a notification I receive. If that notification is pressed it launches an activity. If there are no previous activities on the back-stack, or only a certain one, I want to remove that certain activity and insert my main activity in there and than the new activity.
I found this Thread but I don't understand how he handles it with two intents and flags.
i.e. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK)
Is it wise to do it the way he did it or should I edit the activity stack for that?
I am fairly new to android dev, so some advice could help me here out.
Thanks a lot ;)
Update: so I went with the stackbuilder but somehow it doesn't get set right ... I don't find my error, my boolean noActivity gets set for sure, but I think somehow I misunderstood how the stack actually puts a previous activity in there.
private void sendNotification(messageType type, Map<String, String> data, boolean noActivities) {
Intent i;
String message = "";
switch (type) {
case newFOLLOWER:
User cur = new User(data.get("other.name"));
User.lookAT = User.getOtherUserByName(cur);
i = new Intent(this, other_profile.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
message = data.get("other.name") + " is following you now. Click to see his profile";
i.putExtra("Notification", data.get("other.name") + " is following you now. Click to see his profile");
break;
default:
i = null;
break;
}
if (i != null) {
TaskStackBuilder stack = TaskStackBuilder.create(this);
if(noActivities){
stack.addParentStack(Photostream.class);
}
stack.addNextIntent(i);
PendingIntent pendingIntent = stack.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("PIC LOC")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Update 2: So after searching quite a lot I found out that I missunderstood how the stack builder works. I found another thread where they described how the adding works. Editing the Manifest in order to have a previous stack.
I was to fast and skipped part of the tutorial you provided me so kindly ...
Thanks for your guys help ;)
You should make stack builder while creating notification like this.
Intent resultIntent = new Intent(this, NotificationTapActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
So whenever user will tap on notification, MainActivity will be inserted in stack.
One more solution in which you can handle the back press of NotoificationTapActivity. In which you can check if noting is there in stack then you can finish the current activity and starts MainActivity from there.
You should use TaskStackBuilder. This is the most efficient way and the TaskStackBuilder structure developed for that reason.
I allways use TaskStackBuilder when Push Notifications are included to my project.
Overriding onBackPress() is not good approach because it requires complex structures in your app and you need to handle many things.
Check this tutorial.
/**Just use below code inside onMessageReceived()**/
PendingIntent pendingIntent;
Uri defaultSoundUri;
Intent notification_intent;
String message = "Your Message";
notification_intent = new Intent(this, YourActivity.class);
notification_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0 , notification_intent, PendingIntent.FLAG_ONE_SHOT);
defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
String[] multilineDescription = new String[]{message};
message = multilineDescription[0];
for (int i=1; i<multilineDescription.length; i++)
{
message += System.getProperty("line.separator");
message += multilineDescription[i];
}
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
/***Above commented is for strecting the big message in Push Notification******/
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)MESSAGE_NOTIFICATION_ID /* ID of notification */, notificationBuilder.build());
You can simply handle that in onBackPressed of notification activity.
With help of flag you may know that your notification activity is opened through notification click and then in onBackPressed go to your mainactivity as following:
Intent intent =new Intent(context,MainActivity.class)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
PendingIntent can implement multi intent. Just create an array intent
Intent[] intents = new Intent[2];
Intent intent1 = new Intent(this, MainActivity.class);
Intent intent2 = new Intent(this, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, intents,PendingIntent.FLAG_ONE_SHOT);
And when you finish YouActivity, it will back to MainActivity.
Intent intent = getIntent();
String data= intent.getStringExtra("from");
if(data.equalsIgnoreCase("notificaton")
{
// call Mainactivity
}
else if(){}

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);

Resume an activity when clicked on a notification

I've made an app which manage sms, I've created the notifications but when I click on them it starts another activity, I would like to know how to check if an activity has been stopped and resume it.
Here is the code used to create the pendingintent:
private void createNotification(SmsMessage sms, Context context){
final NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String contentTitle = "";
// construct the Notification object.
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(contentTitle)
.setContentText(sms.getMessageBody())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(getIconBitmap())
.setNumber(nmessages);
builder.setAutoCancel(true);
//(R.drawable.stat_sample, tickerText,
// System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
//notif.setLatestEventInfo(this, from, message, contentIntent);
/*
// On tablets, the ticker shows the sender, the first line of the message,
// the photo of the person and the app icon. For our sample, we just show
// the same icon twice. If there is no sender, just pass an array of 1 Bitmap.
notif.tickerTitle = from;
notif.tickerSubtitle = message;
notif.tickerIcons = new Bitmap[2];
notif.tickerIcons[0] = getIconBitmap();;
notif.tickerIcons[1] = getIconBitmap();;
*/
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, BasicActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Ritardo in millisecondi
builder.setContentIntent(resultPendingIntent);
nm.notify(R.drawable.ic_drawer, builder.build());
You need to set flags in your PendingIntent's ...like FLAG_UPDATE_CURRENT.
Here is all on it.
http://developer.android.com/reference/android/app/PendingIntent.html
Edit 1: I misunderstood the question.
Here are links to topics that had the same issue but are resolved:
resuming an activity from a notification
Notification Resume Activity
Intent to resume a previously paused activity (Called from a Notification)
Android: resume app from previous position
Please read the above answers for a full solution and let me know if it works.
Add this line to the corresponding activity in manifest file of your app.
android:launchMode="singleTask"
eg:
<activity
android:name=".Main_Activity"
android:label="#string/title_main_activity"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode="singleTask" />
Try with this.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(mContext.getString(R.string.notif_title))
.setContentText(mContext.getString(R.string.notif_msg));
mBuilder.setAutoCancel(true);
// Set notification sound
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
Intent resultIntent = mActivity.getIntent();
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.setAction(Intent.ACTION_MAIN);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
The only solution that actually worked for me after doing a lot of search is to do the following :
here you are simply launching of the application keeping the current stack:
//here you specify the notification properties
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).set...(...).set...(..);
//specifying an action and its category to be triggered once clicked on the notification
Intent resultIntent = new Intent(this, MainClass.class);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//building the notification
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
If the aforementioned solution didn't work, try to change the activity launch mode in your androidManifest.xml file from standard to singleTask.
<activity>
...
android:launchMode="singleTask
...
</activity>
This will prevent the activity from having multiple instances.

Android notification Resume Activity

I'm trying to make a notification when users pause my app. So to make it easier, users can go quickly to the application using notificaction. This is the code i'm using. It works for all versions before android 4 and i don't know which is the problem
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Titulo")
.setContentText("Titulo");
mBuilder.setOngoing(true);
// Creates an explicit intent for an Activity this
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
// put the flags
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
So when i press the notification in android 4.0 and higher, the activity is created again instead of resume. any help please, i can't make it work.
EDIT ( forget about manifest singletop )
android:launchMode="singleTop" same result, not working...
My activity contains a map. I'm using the new version of google maps. v2.
I just tried PendingIntent.FLAG_CANCEL_CURRENT and seems to work for me
public void showNotification(String header,String message){
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(this, MainActivity.class);
//PendingIntent.FLAG_CANCEL_CURRENT will bring the app back up again
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,PendingIntent.FLAG_CANCEL_CURRENT, intent, 0);
Notification mNotification = new Notification.Builder(this)
.setContentTitle(header)
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSound(soundUri)
.addAction(R.drawable.ic_launcher, "View", pIntent)
.addAction(0, "Remind", pIntent)
.setOngoing(true)//optional
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotification);
}
Use android:launchMode="singleTop" in the manifest declaration of MainActivity
The only solution that actually worked for me after doing a lot of search is to do the following :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).set...(...).set...(..);
Intent resultIntent = new Intent(this, MainClass.class);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
this opens your current activiy without creating another one !
SOLUTION provided by #Patrick taken from the question and added as answer:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.txt))
.setContentText(getString(R.string.txt));
mBuilder.setOngoing(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, Activity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.from(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(Activity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.getNotification());

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