user1590595
user1590595

Reputation: 805

OneSignal SDK: How to open MainActivity after user taps on notification

How can I open Main Activity if user taps on push notification sent from OpenSignal. I wanted to override the default behaviour which was causing some issue when App was active. I added following line as per the doc

<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />

Now if app is closed, how can i open MainActivity, and let it execute NotificationOpenedHandler.

Thank you.

Upvotes: 0

Views: 2297

Answers (1)

jkasten
jkasten

Reputation: 3948

If you still always want your launcher / main Activity to open / resume when tapping on a OneSignal notification add the following code to your Activity intead.

private static boolean activityStarted;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  if (   activityStarted
      && getIntent() != null
      && (getIntent().getFlags() & Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
    finish();
    return;
  }

  activityStarted = true;
}

See Resume last Activity when opening a Notification instructions for more details.

If you need to do something more custom keep the manifest entry you noted above and add a OneSignal NotificationOpenedHandler to OneSignal.startInit in your Application class.

import com.onesignal.OneSignal;

public class YourAppClass extends Application {
   @Override
   public void onCreate() {
      super.onCreate();

      OneSignal.startInit(this)
        .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
        .init();
   }

  // This fires when a notification is opened by tapping on it or one is received while the app is running.
  private class ExampleNotificationOpenedHandler implements NotificationOpenedHandler {
    @Override
    public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
      // The following can be used to open an Activity of your choice.
      /*
      Intent intent = new Intent(getApplication(), YourActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(intent);
      */
      // Follow the instructions in the link below to prevent the launcher Activity from starting.
      // https://documentation.onesignal.com/docs/android-notification-customizations#changing-the-open-action-of-a-notification
    }
}

See 4. Add Optional NotificationOpenedHandler for more details on this callback.

Upvotes: 4

Related Questions