firebone
firebone

Reputation: 117

Clicking on notification doesn't open Android app

I am using onesignal and firebase to push notifications from wordpress blog to Android app and when I click on notification that just arrived, application will open only if it run in the background. If it is completely closed, clicking on notification will do nothing. How do I achieve clicking on notification opens app even if app is not in the background opened?

Below is the code that handles notifications:

 class nyonNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
        // This fires when a notification is opened by tapping on it.
        @Override
        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("OneSignalnyon", "customkey set with value: " + customKey);
            }

            if (actionType == OSNotificationAction.ActionType.ActionTaken)
                Log.i("OneSignalnyon", "Button pressed with id: " + result.action.actionID);

            // The following can be used to open an Activity of your choice.
            // Replace - getApplicationContext() - with any Android Context.
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

Upvotes: 5

Views: 10743

Answers (5)

Chakib Temal
Chakib Temal

Reputation: 332

I had the same problem

I fixed the problem by going to the AndroidManifest.xml file

I've added these lines: I specify that I'm working on Flutter

<intent-filter>
     <action android:name="FLUTTER_NOTIFICATION_CLICK" />
     <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

j'ai aussi ajouté ces deux lignes :

<meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/notification_channel_id" />

I don't know if these last two lines are compulsory, but personally I work with channel , so add to strings.xml

<string name="notification_service_name_notification_channel">Alert notifications</string>
<string name="notification_channel_id">notification_channel_id</string>

I'm adding the MainActivity code in kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        val importance = NotificationManager.IMPORTANCE_HIGH
        val mChannel = NotificationChannel(getString(R.string.notification_channel_id),
                getString(R.string.notification_service_name_notification_channel),
                importance)

        mChannel.enableLights(true);
        mChannel.lightColor = Color.RED;
        mChannel.enableVibration(true);

        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(mChannel)
    }
}

Upvotes: 0

Admir
Admir

Reputation: 155

Well to solve this problem, first thing is to read documentation more clearly (what I didn't do) so here it is:

By default OneSignal will open or resume your launcher Activity when a notification is tapped on. You can disable this behavior by adding the meta-data tag com.onesignal.NotificationOpened.DEFAULT set to DISABLE inside your application tag in your AndroidManifest.xml.

Make sure that you register it inside android manifest, e.g.:

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

Create handler for opened notifications, e.g.:

public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {

    private final Context context;

    public MyNotificationOpenedHandler(Context context) {
        this.context = context;
    }

    @Override
    public void notificationOpened(OSNotificationOpenResult result) {

        if (result.action.type == OSNotificationAction.ActionType.Opened) {
            JSONObject data = result.notification.payload.additionalData;

            if (data == null) {
                return;
            }

            String category = data.optString("category", null);

            if (category == null) {
                return;
            }

            if (category.equals("global")) {
                Intent intent = new Intent(context, NotificationDetailsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        }
    }
}

Next point is:

Make sure you are initializing OneSignal with setNotificationOpenedHandler in the onCreate method in your Application class. You will need to call startActivity from this callback.

You'll need to extend Application class, e.g.:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .setNotificationOpenedHandler(new MyNotificationOpenedHandler(getApplicationContext()))
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();
    }
}

Set application name inside android manifest, e.g.:

    <application
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme">

And you're ready to handle notifications when app is closed.

Upvotes: 1

Ajay Chauhan
Ajay Chauhan

Reputation: 1561

The code which I am using for opening app on the click of notification, which is working perfectly fine :

 Intent resultIntent = new Intent(getApplicationContext(), YourActivity.class);
 resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 //if you want to send some data
 resultIntent.putExtra(AppConstants.NOTIFICATION, data);

Now you have to create PendingIntent PendingIntent: As per docs by creating pending intent means you are granting it the right to perform the operation you have specified as if the other application was yourself. https://developer.android.com/reference/android/app/PendingIntent

PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

Now when you are creating your Notification set this pending intent setContentIntent(resultPendingIntent) to that notification.

  Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(System.currentTimeMillis() + ""))
            .setSmallIcon(R.drawable.ic_app_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), icon))
            .setContentText(message)
            .setChannelId(CHANNEL_ID)
            .build();

Upvotes: 3

Samin
Samin

Reputation: 587

Set "setNotificationOpenedHandler"

   OneSignal.startInit(this)
            .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
            .setNotificationOpenedHandler(new NotificationOpenedHandler())
            .init();

Add this class to your launcher activity ( make sure notification have "additionalData" )

 public class NotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    // This fires when a notification is opened by tapping on it.
    @Override
    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("Data", null);
            if (customKey != null)
            {
                Log.d("LOGGED", "notificationOpened: " +  customKey);
                if(customKey.equals("Notification"))
                {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                else
                {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                //Toast.makeText(MainActivity.this, "Value is : " + customKey, Toast.LENGTH_SHORT).show();
            }
        }

More Info https://documentation.onesignal.com/docs/android-native-sdk#section--notificationopenedhandler-

Upvotes: 0

Kamran Mammadov
Kamran Mammadov

Reputation: 1

Add the following to your AndroidManifest.xml to prevent the launching of your main Activity

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

Upvotes: -1

Related Questions