Android PendingIntent take you to an already existing activity?

Tom Fobear picture Tom Fobear · Mar 28, 2011 · Viewed 20.6k times · Source

Wasn't really sure how to search for this...

I have a the following which is called whenever a job is added or removed from my queue to put a notification in the status bar:

private void showNotification()
{
    int jobsize = mJobQueue.size();
    int icon = (jobsize == 0) ? 
        android.R.drawable.stat_sys_upload_done : 
        android.R.drawable.stat_sys_upload;
    Notification notification = 
        new Notification(icon, "Test", System.currentTimeMillis());
    Intent intent = new Intent(this, FileManagerActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    notification.flags = 
        (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL);
    notification.setLatestEventInfo(this, 
        "Uploading to our servers",
        getString((jobsize > 0) ? 
            R.string.notification_active_transfers : 
            R.string.notification_no_transfers),
        pendingIntent);

    mNotifyManager.notify(NOTIFICATION, notification);
}

As it is now the behavior is this:

  • if the user logs out and hits the notification, it will still open a new FileManagerActivity (ops!) I could get around this by starting at my authentication activity and passing the intent up my stack in a natural order, its when the application is already running is where I have difficulties.

  • if the user already has the FileManagerActivity open clicking the notification will put a second instance over it. In this case, I want the currently running FileManagerActivity to recieve focus instead of launching a new instance.

How could I get the correct behavior?

Answer

David Snabel-Caunt picture David Snabel-Caunt · Mar 28, 2011

I've done this before by setting my Activity to use the launch mode 'singleTop' in the Application Manifest. It will achieve the desired function, using the existing activity if one exists. In this case, onNewIntent will be called in your activity.

You'll need to check in your FileManagerActivity for authentication and start a new activity as appropriate if the user is not logged in.