Everything is working fine with my GcmListenerService if the activity is not already running.
I click on the notification and the app starts with the righ activity, actually EventHistoryActivity.
But, if EventHistoryActivity is already running, nothing happens.
I expect a call to onCreate but it does not happen.
I'm doing this in the sendNotification method:
resultIntent = new Intent(this, EventHistoryActivity.class);
resultIntent.putExtra("reload", true);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
I tried also PendingIntent.FLAG_UPDATE_CURRENT and PendingIntent.FLAG_ONE_SHOT but with no luck.
Where is the problem ?
Again, if the app is running but EventHistoryActivity is not, all is ok.
Am I doing something wrong or is not onCreate the method I should expect to be called ?
You're probably getting the call to onNewIntent
This is called for activities that set launchMode to "singleTop" in
their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag
when calling startActivity(Intent). In either case, when the activity
is re-launched while at the top of the activity stack instead of a new
instance of the activity being started, onNewIntent() will be called
on the existing instance with the Intent that was used to re-launch
Related
I have an Activity with following special properties set in manifest
<activity
android:name=".LightUp"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:noHistory="true"
android:process=":listener"
android:taskAffinity="" >
</activity>
Inside this activity, I'm scheduling an AlarmManager to use this PendingIntent to call itself after sometime. AlarmManager is necessary because phone will go to sleep while this activity is on screen, and I don't want to hold a wakelock.
pendingIntent = PendingIntent.getActivity(this, 10,
new Intent(this, LightUp.class)
.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_UPDATE_CURRENT);
So when Alarm manager fires, I'm getting the new Intent in onNewIntent() function as usual. Which means intent is coming to same activity.
Problem is the activity gets destroyed after onNewIntent. Even if I have absolutely no code in onNewIntent, I can see from logs that onDestroy is getting called anyway.
So question is why is Destroy being called? What can I do to keep the activity running?
try this
Activity in Manifest
<activity
android:name=".LightUp"
android:launchMode="singleTop"
</activity>
Java Code
Intent notificationintent = new Intent(context, LightUp.class);
notificationintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationintent, PendingIntent.FLAG_UPDATE_CURRENT);
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
System.out.println("new intent received");
// do what ever you want to do here
}
Looks like I found the culprit. It's the noHistory property causing the problem.
Official documentation says
android:noHistory :: Whether or not the activity should be removed from the activity stack and finished (its finish() method called) when the user navigates away from it and it's no longer visible on screen
Well, technically I didn't leave the screen while calling PendingIntent, weird that finish is being called. After removing noHistory, it's not destroying.
Try this:-
<activity
android:launchMode="singleTask" >
</activity>
By default, if you call an activity with an intent, a new instance of that activity will be created and displayed, even if another instance is already running. To avoid this the activity must be flagged that, it should not be instantiated multiple times. To achieve this you have to set the launchMode of the activity to singleTask.
I know we can launch activities on notification open like this:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
Intent targetIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
//...
But what if, instead of lunch an activity, I want to run a callback, like some onPushOpen, so to choose there how to handle the notification click?
You can declare an activity in your manifest, call it NotificationClickHandlerActivity, which you will set as the target for the pending intent of your notification instead of MainActivity.
In the onCreate method of this new activity, just call getIntent, based on the information in the intent (action, categories, extras) determine what needs to be opened next, start the new target activity which you determined or do some other action, then call finish from inside onCreate and return immediately.
If an activity calls finish in onCreate like this handler, it will never be shown to the user, so he will not be aware that it even exists, all he'll see is the other activity which you potentially launch from it.
Also, keep in mind that you should not do long running operations in the onCreate method of this handler activity as they will be executed on the UI thread and will block your app from responding to user input. If you have to do something longer running, put it inside an async task subclass (either STATIC nested class of the handler activity, or completely separate class), then start an instance of this task from the onCreate method, and call finish right after the task is started. The task will continue running in the background. If the task needs a context to do whatever it has to do, make sure you pass it an application context by calling getApplicationContext, and don't pass the activity itself otherwise you will have memory leaks.
You could use EventBus to achive that. Just post some event like onPushOpen() and catch it anywhere you want. Make smth like:
Intent targetIntent = new Intent(this, NaughtyActivity.class);
And make NaughtyActivity use no layout. Use it just to post the event and finish.
I've been doing a lot of research on this and I've hit a wall. I've read what seems like all of the material on this topic (inluding this, this, and this as well as the docs) and nothing is helping me in what I want to do.
Basically, in the case that the app is open on the user's phone, I just want a notification to redirect the user to the already-existing Activity in my app. I use a pattern like this:
private PendingIntent buildPendingIntentForNotification(String type) {
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.setAction(Intent.ACTION_VIEW);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);// have tried without this and with Intent.FLAG_ACTIVITY_CLEAR_TOP
resultIntent.putExtra(CommonUtils.NOTIFICATION_TYPE, type);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return resultPendingIntent;
}
I've also tried declaring all 4 types of launchModes in the Android Manifest within the activity tag. No matter what I do, clicking on the notification (even if the app is the active foreground app on the screen and MainActivity is the active activity) always seems to restart the activity from onCreate. From what I can see during debugging, onDestroy is not called at any time between getting the notification and clicking on it. However, after the notification is clicked, onCreate is called and THEN onDestroy is called even though my activity is not being destroyed, which is very strange. I'm hoping someone can help me make sense of this because all of the launchMode and Intent.setFlags suggestions are not working for me. Thanks a lot!
Just for info's sake, here's the code I used to fix my problem (with credit to David's solution):
private PendingIntent buildPendingIntentForNotification(String type) {
Intent resultIntent = new Intent(this, MainActivity.class);
//resultIntent.setAction(Intent.ACTION_VIEW);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.putExtra(CommonUtils.NOTIFICATION_TYPE, type);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return resultPendingIntent;
}
There are 2 ways of doing this:
Notification to restore a task rather than a specific activity?
Resume application and stack from notification
However, you may also be seeing this nasty Android bug.
You cannot control and cannot be sure about the state of your activities on the Android, meaning (in your context) you can only start an activity that has been paused not one that has been destroyed. The OS decides which activities will keep paused and which will destroy and you have no control over that. When your activity leaves the foreground successive callbacks are being invoked at undefined times and to the OS's
What you can simply do is to save your activity's instance state in the onPause() method (which we know for sure that will be called as soon as the activity leaves the foreground) and the on onCreate() you can restore the activity with the data as it previously was.
Note: If you have for example Activity A and activity B and you start activity B from within activity A, then on activity B's onCreate() method you can getIntent().getExtras()
There are a lot of questions/answers about how to start an application from within your application in Android. But those solutions do not produce the same flow as if an icon was tapped in Android launcher.
For example, I do this (this is used with notifications):
intent = context.getPackageManager().getLaunchIntentForPackage("com.test.startup");
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Then when I tap on notification the app is started, however, it is started somewhat differently than when I tap the icon in the App drawer. Specifically: with this approach my main Activity is always created (i.e. onCreate() then onResume() is called). However, if application was already started and then put in background, then starting it from Launcher will only cause onResume() of currently shown activity to be called (not onCreate() on the main one). Is there a way to trigger the same resume flow programmatically from within my app?
To summarize the task: when user taps on notification I need my app to be either started (if it's not already), or brought to the foreground in its current state (if it's in background) and have some data passed to it. The app will then take care of handling/rendering that data.
Your app is behaving the way it supposed to. Even if you try the launch the app from App drawer it will call the same callback. You have to understand the lifecycle. As your activity is in the background onCreate will not get called. But for the handling the data from the notification intent you should utilize callback method OnNewIntent() in activity. You should override this method and extract the data the from the new intent and should update UI. After onNewIntent onresume will be called.
I hope this solves your problem.
Here is my onPause code which works the way you expected i.e when user clicks on the notification it doesnt call onCreate again:
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(getApplicationContext(), PlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(getBaseContext(), 0, intent,0);
NotificationCompat.Builder noti =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentTitle("Nepali Music And more")
.setContentText("Playing");
noti.setContentIntent(pIntent);
noti.setAutoCancel(true);
noti.setOngoing(true);
Notification notification = noti.getNotification();
notificationManager.notify(1, notification);
Focus mainly on the intent flags
You want to use the intent flags Intent.FLAG_ACTIVITY_CLEAR_TOP to find your activity and clear the stack above it. You also need the Intent.FLAG_ACTIVITY_SINGLE_TOP flag to prevent your activity from being recreated (to resume).
The Intent.FLAG_ACTIVITY_SINGLE_TOP is necessary since by default, the launch mode is "standard" which lets you create multiple instances of your activity. If you were to set your launch mode to SingleTop, then this flag own't be necessary
The service creates a persistent Notification and starts the main activity on click via PendingIntent. Here is the code.
Intent notificationIntent = new Intent(getApplicationContext(), ViewPagerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(StreamingService.this, 0, notificationIntent, 0);
However, if the main activity is started when I press notification, it will be started again, and again and...
In the end, I have the same activity pilled up, one on the top of another. I can see this by pressing the back button, which will kill the Main activity once and then get me back to the same activity until I close the last one.
How can I prevent this to happen? Can PendingIntent detect that aiming activity is running so it does not create the same activity again, but rather start the running one?
PS. I apologize if not being able to explain this well. If this is the case, let me know and I will rephrase the problem.
I also found this solution. Add this attribute to Manifest
<activity android:name=".MyActivity"
android:label="#string/app_name"
android:launchMode="singleTop" // <-- THIS LINE
>
for each Activity you need this feature. So far it work with no errors at all.
Which solution is better? Mine is easier, if nothing.
Depending on the exact behaviour you want to implement, you could pass one of these flags as the last param of getActivity():
FLAG_ACTIVITY_REORDER_TO_FRONT
FLAG_ACTIVITY_SINGLE_TOP
Try using another value in REQUEST_CODE. don't use default value 0 in REQUEST_CODE.
or your pendingIntent will restart your activity.
if you want to use normal activity cycle, input request value when creating PendingIntent.
PendingIntent resultPendingIntent = PendingIntent.getActivity(
context, REQUEST_CODE,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);