Jack Jack - 1 year ago 163
Android Question

Push notification open a new activity

I am using OneSignal push notification service.
When user clicking on the push notification it is open automaticlly a new activity called "Main2Activity.java".
When the user clicking on the notification, the code is working and open a new acvtivity. But if I am sending another push notification, when the user is clicking on the notification the application firstly open the "MainActivity.java". Only when the user click the previus button on the phone, it opening the "MainActicity2.java".
This is my code

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())

class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String customKey;

if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
Log.i("OneSignalExample", "customkey set with value: " + customKey);
Toast.makeText(MainActivity.this,"My Custom Key is:"+customKey,Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);




Thank you!

Answer Source

When you open activity from notification then you put some data which is identify user came from notification

And when user press back button from mainactivity2 then check, user came from notification or any other place, if came from notification then close app.

Add below code in your menifest.xml

<activity ..
      android:launchMode= "singleInstance" />