Basically, I'm browsing the internet in chrome or looking at another app. I get a notification that opens my application. I do some stuff and it finishes. My application closes and i'm back on the launcher. How can I get my app to finish and return me to whatever previous app/chrome page i was browsing?
AndroidManifest section for this activity:
<activity
android:name=".AcceptRejectActivity"
android:label="#string/title_activity_accept_reject"
android:screenOrientation="portrait" >
</activity>
Notification code:
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(this, AcceptRejectActivity.class);
resultIntent.putExtra("message","Do you choose to accept this message?");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AcceptRejectActivity.class);
// Adds the Intent that starts the Activity to the top of the stack //
stackBuilder.addNextIntent(resultIntent);
PendingIntent contentIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
String msg = "You have a message"
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("Message")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
android.app.Notification note = mBuilder.build();
note.defaults |= android.app.Notification.DEFAULT_VIBRATE;
note.defaults |= android.app.Notification.DEFAULT_SOUND;
mNotificationManager.notify(0, note);
Fragment's close function
private void allDone() {
Log.i(TAG, "The choice has been made");
getActivity().finish();
//NavUtils.navigateUpFromSameTask(getActivity());
}
Well that´s a little bit weird, but like an option you can open the browser after the finish your application.
private void allDone() {
Log.i(TAG, "The choice has been made");
getActivity().finish(); //finish your app!.
//NavUtils.navigateUpFromSameTask(getActivity());
try { //Open browser!.
Uri uri = Uri.parse("googlechrome://navigate?url=");
Intent i = new Intent(Intent.ACTION_VIEW, uri);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Chrome is not installed
}
}
Then you will return to your Chrome session ;).
I managed to solve my issue.
Android Manifest:
<activity
android:name=".AcceptRejectActivity"
android:label="#string/title_activity_accept_reject"
android:screenOrientation="portrait"
android:launchMode="singleInstance"
android:excludeFromRecents="true">
</activity>
Notification code:
Changed how the pendingIntent was created.
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(this, AcceptRejectActivity.class);
resultIntent.putExtra("message","Do you choose to accept this message?");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String msg = "You have a message"
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("Message")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
android.app.Notification note = mBuilder.build();
note.defaults |= android.app.Notification.DEFAULT_VIBRATE;
note.defaults |= android.app.Notification.DEFAULT_SOUND;
mNotificationManager.notify(0, note);
Now when I'm done my processing I can just call finish() or getActivity().finish() and it will take me back to whatever app/browser page you were on before clicking the notification.
Related
I have an activity named A which start from a broadcast receiver. Activity A triggered a notification but it disappear automatically when activity destroy(finish). But I want to keep this notification until the user click or manually clear the notification.
How activity start from broadcast receiver
Intent i = new Intent(context,A.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
i.putExtras(intent.getExtras());
context.startActivity(i);
Notification
Intent notificationIntent = new Intent();
notificationIntent.setClass(context,B.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setFlags( Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_small)
.setContentTitle(status)
.setTicker(status)
.setAutoCancel(false)
.setContentText(message)
.setDefaults(Notification.DEFAULT_SOUND)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.build();
manifest options
<activity android:name="com.example.activity.A"
android:screenOrientation="portrait"
android:launchMode="singleTask"
android:taskAffinity=""
android:excludeFromRecents="true"/>
Note: I also tried singleInstance but no luck.
Edit(Fixed)
I made a silly mistake. I called clearAll() instead of cancel a specific notification in onDestroy() function.
I think you are cancelling all the notification in your app when the activity is destroyed.
remove autocancel() totally and try this,
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MenuActivity.class), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon).setContentTitle(" ").
setStyle(new NotificationCompat.BigTextStyle().bigText(bundle.get("").toString())).
setContentText(bundle.get("").toString());
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
I want to auto cancel my notification when user clicks on notification. The following code works good in all the devices except Android lollipop device. In Lollipop device, notification goes only when user swipes it off.
#SuppressWarnings("deprecation")
public void sendNotification(int id){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test")
.setContentText("Jump to next screen")
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, 0);
//PendingIntent.FLAG_UPDATE_CURRENT
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// id, if there is a need to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
Log.v(TAG, "Notification ID value " + id);
//mNotificationManager.cancel(id);
}
What is missing in this code?
Looks good to me. My auto cancel still works on 5.0.2. Let me give you a portion of my code:
public static void notif(int id, String title, String text, Context context, Class activity) {
// get an instance of the NotificationManager service
if (mNotifyMgr == null)
mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, activity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.launcher)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(notifIntent);
mNotifyMgr.notify(id, mBuilder.build());
}
modify following:
setAutoCancel(true) -> setAutoCancel(false);
then on action activity do the following
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
if you want to set special condition you can set by
intent.putExtra("key", "value")
I am having trouble having a notification open the app. I've followed the instructions on the Android docs, but to no avail. It creates the notification no problem, but clicking on it just dismisses it.
Please help! Thanks in advance!
Why is clicking the notification not opening the app?
Intent intent = new Intent(this, MainActivity.class);
String type = "";
if (extras.containsKey(KEY_TYPE)) type = extras.getString(KEY_TYPE);
String text = "";
if (type.equalsIgnoreCase(TYPE_MATCH_FOUND)) {
// TODO: send intent with all variables, trigger matched fragment when user goes into app
text = getResources().getString(R.string.msg_found_match);
intent.putExtra(KEY_TYPE, TYPE_MATCH_FOUND);
}
else if (type.equalsIgnoreCase(TYPE_MESSAGE)) {
// TODO: trigger chat fragment when user goes into app
text = getResources().getString(R.string.msg_new_message_from);
intent.putExtra(KEY_TYPE, TYPE_MESSAGE);
}
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("LFDate")
.setContentText(text)
.setAutoCancel(true)
.setLights(Color.parseColor("#0086dd"), 2000, 2000);
if (prefs.getNotificationVibrate()) mBuilder.setVibrate(new long[] {1000, 1000, 1000});
if (prefs.getNotificationSound()) mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
I faced this same problem earlier today, if you are using kitkat you will have to change to:
// Have pending intent use FLAG_CANCEL_CURRENT, cause on
// kitkat you get a permission denied error
PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
or you can add the flag to your receiver, or activity launched from the notification in XML:
android:exported="true"
Below is my block of code which should open NotificationActivity when the notification is tapped on. But its not working.
private void setNotification(String notificationMessage) {
Uri alarmSound = getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager = getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity2.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logo)
.setContentTitle("My Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationMessage))
.setContentText(notificationMessage).setAutoCancel(true);
mBuilder.setSound(alarmSound);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
try this:
private void setNotification(String notificationMessage) {
//**add this line**
int requestID = (int) System.currentTimeMillis();
Uri alarmSound = getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager = getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity2.class);
//**add this line**
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//**edit this line to put requestID as requestCode**
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.logo)
.setContentTitle("My Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationMessage))
.setContentText(notificationMessage).setAutoCancel(true);
mBuilder.setSound(alarmSound);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
You might be using a notification id equal to 0. There is known issue with notification id being 0. If you will use any other id, it should work.
I added task builder and the below block code worked for me
Intent intent = new Intent(context, HomeActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(SplashActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Try checking your AndroidManifest.xml, double check if you are navigating to an activity with an intent-filter main action, launcher category
For example,
I couldn't make my pending intent to navigate to HomeActivity but it works when navigating to SplashScreen
Hope this helps.
If the app is already running then you need to handle it in onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Handle intent here...
}
Added the requestid, but the intent was still not opening.
This is the solution that worked for me:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Setting those flags to clear the activities below the intent activity.
I am using GCM in my application and also using NotificationManager to Create a Notification whenever GCM message is received.Till now everything is working perfectly and GCM message is showing correctly in Notification area, but when I click on the notification it should start an activity of my application which will display the message detail which is not happening. Every-time I click on notification it does not start any activity and it remains as is.My code for creating Notification is :
private void sendNotification(String msg) {
SharedPreferences prefs = getSharedPreferences(
DataAccessServer.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, WarningDetails.class);
Bundle bundle = new Bundle();
bundle.putString("warning", msg);
bundle.putInt("warningId", NOTIFICATION_ID);
intent.putExtras(bundle);
// 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(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WarningDetails.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.weather_alert_notification)
.setContentTitle("Weather Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
String selectedSound = prefs.getString("selectedSound", "");
if (!selectedSound.equals("")) {
Uri alarmSound = Uri.parse(selectedSound);
mBuilder.setSound(alarmSound);
} else {
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
}
if (prefs.getBoolean("isVibrateOn", false)) {
long[] pattern = { 500, 500, 500, 500, 500, 500, 500, 500, 500 };
mBuilder.setVibrate(pattern);
}
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
I updated my code to support Preserving Navigation when Starting an Activity just like it happens in Gmail application using the Android developers website since then it stopped working.Someone Please guide me what I am missing or doing wrong in this code.
My problem got solved I just have to add PendingIntent.FLAG_ONE_SHOT flag as well , so I replaced :
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
to
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
I encountered the same issue and resolved it by adding android:exported="true" to the activity declaration in AndroidManifest.xml.
Here you just passed your Intent into pendingintent: see below
Intent notificationIntent = new Intent(context, Login.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
and set this contentintent into your Notification:
Notification noti = new NotificationCompat.Builder(context)
.setSmallIcon(icon_small)
.setTicker(message)
.setLargeIcon(largeIcon)
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setContentIntent(**contentIntent**)
.setAutoCancel(true).build();
This may help you.
if you launch the intended activity using Action String dont forget to add
<intent-filter>
<action android:name="YOUR ACTION STRING"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
inside <activity></activity> tag
The activity that you want to launch has to be designated as a LAUNCHER activity in your manifest - otherwise it won't launch via a Pending Intent. Add the following to your in the AndroidManifext.xml
<activity
...
android:exported="true">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Otherwise you will need to use an Activity that is already designated as a LAUNCHER (such as your MAIN activity)
Do some thing like this on generateNotification() method ..
Replace your activity with Splash.Java class in it.
/**
* Issues a notification to inform the user that server has sent a message.
*/
#SuppressWarnings("deprecation")
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
//message = "vivek";
// Log.d("anjan", message.split("~")[0]);
//Toast.makeText(context, message, Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Log.d("anjan1", title);
String text_message = context.getString(R.string.title_activity_main);
Log.d("anjan1", text_message);
Intent notificationIntent = new Intent(context, Splash.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Try this instead of the last line :
mNotificationManager.notify(0, mBuilder.getNotification());