Let's say that we have Activity which displays funny picture and name it FunnyActivity. This Activity can be launched from MainActivity, which is base Activity in out application, after clicking button. We want also to push some notifications sometimes and when user clicks on notification this FunnyActivity should be launched. So we add this part of code:
Intent notificationIntent = new Intent(this, FunnyActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0);
and this PendingIntent is using in notification builder
setContentIntent(intent)
Of course FunnyActivity is beautifully launching, but we want to open MainActivity when user clicks back button on FunnyActivity.
How can we achieve that? Please remember that when user came back to MainActivity he can open FunnyActivity again from button.
Try this:
// 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)
.addNextIntent(detailsIntent);
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pendingIntent);
Source: Create back stack when starting the activity
You can try this:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
Intent resultIntent = new Intent(this, FunnyActivity.class);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
Intent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)/*.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))*/
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(msg)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true);
This is how you can achieve solution to your problem. Hope this helps you
Related
I need heads-up notification which will be not cancelable from notification drawer so I created Heads-up Ongoing notification:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo_notification)
.setContentTitle("Title")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setGroup(KEY)
.setGroupSummary(true)
.setOngoing(true)
.setColor(context.getResources().getColor(R.color.tab_indicator_color));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, Activity.class);
// 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.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WActivity.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) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent pIntent = new Intent(context, PService.class);
pIntent.setAction("ACTION");
PendingIntent piPause = PendingIntent.getService(context, NOTIFICATION_ID, pIntent, 0);
mBuilder.addAction(icon, title, piPause);
Intent sIntent = new Intent(context, SService.class);
sIntent.setAction("ACTION");
PendingIntent piDismiss = PendingIntent.getService(context, NOTIFICATION_ID, sIntent, 0);
mBuilder.addAction(icon2, title2, piDismiss);
The problem is that After notification shows on the top of screen it does not hide to notification drawer. But if notification is not ongoing, it hides. I need heads-up notification which will hide to notification drawer.
AFAIK, a notification needs the following properties to be set to be shown as a heads-up notification.
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
setOngoing() means that the Notification is ongoing and cannot be hidden by the user. I believe that is probably why your Notification stays on the top and doesn't hide. Remove setOngoing(true) and it should work.
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);
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.
I have an application that shows a play pause notification.I want to when a user tap on the notification a service in the app be called and I do my stuff in that service.
I have done it for my notification item widgets like buttons but now I want to handle user tap on whole of notification bar.any help?
This is my code for handling on items click:
Intent intent = new Intent(context , MyNotificationService.class);
intent.putExtra("ID","play");
PendingIntent pendingIntent = PendingIntent.getService(context,0,intent,0);
myRemoteView.setOnClickPendingIntent(R.id.myButton);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(this, YourActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(YourActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(resultPendingIntent);
There you go :) This will open 'YourActivity' when the notification is tapped.
I like to launch one of my activities in my application on clicking the notification.
I designed a pending intent as discussed in the link Notifications.
But when i click the notification, an activity is launched but that is not the activity supposed to launch from my application. Just the activity that has same class name as my activity is launched. I set a break point in my activity and the break point is never hit.
What is wrong? NotificationListActivity is the one I like to launch. Now the activity titled with NotificationListActivity is launched, but not my activity.
Intent resultIntent = new Intent(thisclasscontext, NotificationListActivity.class);
resultIntent.putExtra("MOBILENUMBER", tel);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(thisclasscontext);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(NotificationListActivity.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);
You can use the below as a reference it works
public void notification()
{
int mId=1;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(MainActivity.this, SecondActivity.class);
// 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.create(MainActivity.this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(SecondActivity.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());
}