0

My app creates a Notification from an IntentService. When tapped, the Notification opens MainActivity of type Activity. MainActivity's onCreate() method is called every time a newNotification is tapped, irrespective of whether an instance ofMainActivity is already created or not. Tapping the Notification always creates a new instance that replaces the old one.

Is there a way to call onCreate() only if the Activity doesn't exist and call e.g. onNewIntent() if MainActivity already exists (or another appropriate method) ?

The Notification is currently created like this:

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(com.exampleapp.myclient.R.drawable.dummy_notification_icon, "Notification!", System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    notification.setLatestEventInfo(context, notificationTitle, "test", pendingIntent);
    notificationManager.notify(1, notification);

MainActivity in Manifest:

<activity android:name="com.exampleapp.myclient.MainActivity"  
    singleTop="true">
 </activity>
Pierre Rymiortz
  • 1,127
  • 3
  • 15
  • 31

2 Answers2

3

You can set the activity as singleInstance in manifest of the application and when the activity is lauched again the onCreate() method will not be called instead of onNewIntent() is called. where you can decide what to do next.

Ali Imran
  • 8,927
  • 3
  • 39
  • 50
2

Your simply looking for the android:launchmode attribute in the manifest. For your case it should be set to singleTask. Then you'll be able to handle the onNewIntent(); and you'll only have 1 instance.

Warpzit
  • 27,966
  • 19
  • 103
  • 155