5

I am sending push notification to devices using below code.

      var nTitle = "New message from " + $rootScope.clients_firstName;
      var to = "DeviceToken is here";
      var notification = {
        'title': nTitle,
        //'body': 'Click here to more details...',
        'icon': 'firebase-logo.png',
        'click_action': 'openapp'
      };

      var key = 'your key';
      fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
        'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify({
        'notification': data,
        'to': to
      })
      }).then(function(response) {
        //console.log("res ", response);
      }).catch(function(error) {
        console.error("err ", error);
     });

push notification sends on device successfully.

But when I click on notification the specific page should be open.

For example 'click_action' : 'openapp/somepage'

Then the 'somepage' should be open when I click on pushnotification.

AndroidManifest.xml

<activity android:name="MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

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

</activity>

My project structure

--platforms
--plugins
--www
  --app
    --about
      --about.html
      --about.ctrl.js
    --product
      --product.html
      --product.ctrl.js
  --css
  --js
  --lib
  index.html

If I click on notification and I want to open product or about page then what I have to do?

What is wrong here? Please tell me the proper solution.

Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49

5 Answers5

4

For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

Edit after question update :-

Instead of putting that <intent-filter> in MainActivity, put the filter in the <activity> tag of the activity that you want to open when the notification is clicked. An example is the following :-

<activity android:name="ProductDetailsActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

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

Now that your specified activity opens, you can get information from the data part of your notification using getIntent().

For example, if your notification payload has the following structure,

payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification without using any additional frameworks.

Rohan Stark
  • 2,346
  • 9
  • 16
  • my above code is working. and when i clicked on notification the app is also opened. but i want to open a particular page. means if the notification is "product" related then the "product" page will open, if the notification is "chat" related then the "chatting" page will open. understand? – Harish Mahajan Jul 07 '17 at 03:53
  • You posted only the `` part of your manifest. Tell me which `Activity` that filter belongs to. Or just post the `` part of the manifest in your answer. – Rohan Stark Jul 07 '17 at 08:00
  • now i got an error Uncaught ReferenceError: getIntent is not defined. – Harish Mahajan Jul 07 '17 at 09:11
  • Use this `this.cordova.getActivity().getIntent(); ` – Rohan Stark Jul 07 '17 at 09:23
  • again error `Uncaught TypeError: this.cordova.getActivity is not a function` – Harish Mahajan Jul 07 '17 at 09:54
  • Try this.getActivity().getIntent(); – Rohan Stark Jul 07 '17 at 09:55
  • error `Uncaught TypeError: this.getActivity is not a function` – Harish Mahajan Jul 07 '17 at 09:57
  • Look, I do not know your entire code or how well versed you are with ionic, Cordova and Android. So I really can't suggest you a pin-pointed method. But, since you're using ionic with Android, there has got to be a way for you to access your activity context and retrieve the intent details, because activities and intents are fundamental to Android. – Rohan Stark Jul 07 '17 at 10:06
2

I know that you ask about Ionic 1. But I only know for Ionic 2. Hope this will help you.

I think you should add information about what page you need to open in additional data section of your notice. Something like this:

'body': JSON.stringify({
        'notification': data,
        'to': to,
        'data' : {
           'action' : 'Needed page'
        }
      })

And then you should catch it on the subscribe method. Something like that:

fcm.onNotification().subscribe(data=>{
  console.log("data", data);
  if (data['action'] && data['action'] == 'Needed page'){
    this.navCtrl.push('Needed page'); //Use Navigation controller to open needed page
  }
})

For native cordova FCM plugin:

FCMPlugin.onNotification(function(data){
    console.log("data", data);
    if (data['action'] && data['action'] == 'Needed page'){
      this.navCtrl.push('Needed page'); //Use Navigation controller to open needed page
    }
});
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Alexander Zakusilo
  • 1,466
  • 3
  • 16
  • 34
  • i am usign firebase api. will this work? see my code, it is very simple. – Harish Mahajan Jul 04 '17 at 11:08
  • You need to try and use console log. I think first example about push notice body will work. Second no because I wrote example for Ionic 2. But the algoritm is the the same for ionic 1. You just need to subscribe on notification via fcm cordova plugin https://github.com/fechanique/cordova-plugin-fcm. Use onNotification method. – Alexander Zakusilo Jul 04 '17 at 19:29
  • Updated the answer. – Alexander Zakusilo Jul 04 '17 at 19:32
1

If you are using Ionic Push Plugin you can receive using

$scope.$on('cloud:push:notification', function(event, data) {
        var msg = data.message;
        var appState = msg.app;
        var appAsleep = appState.asleep;
        var appClosed = appState.closed;


        if (appAsleep || appClosed) {               
            $state.go("your state");
        } else {
           //if app is open while receiving push
        }

    });
HGK
  • 181
  • 9
0

Pass your url in the push payload and use the following code to open the the specific screen referred by that url:

$rootScope.$on("$cordovaLocalNotification:click", function(notification, state) {
    var data = JSON.parse(state.data);
    window.location.href = data.url;
});
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Mahendra Liya
  • 12,912
  • 14
  • 88
  • 114
0

You asked me here. If you use my solution and creating notifications manually in onReceive(Context context, Intent intent) method, you must put pending intent to notification builder.

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//init builder with icon, text, any other params

Intent activityIntent = new Intent(context, Activity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); //it is needed if you creating an activity from not activity context
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pendingIntent);

Notification notification = builder.build();
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
NotificationManagerCompat.from(context).notify(notificationId, notification);
Ufkoku
  • 2,384
  • 20
  • 44
  • Right now, if i close the app from any page/view. and when i received a notification then app opens from a default page( the page that last open). but i want to open my own page, not the default page. – Harish Mahajan Jul 04 '17 at 14:50