8506

Firebase notification in Phonegap Cordova

Question:

I'm trying to add notifications to my app in PhoneGap. For that, I'm using this plugin (<a href="https://github.com/fechanique/cordova-plugin-fcm" rel="nofollow">https://github.com/fechanique/cordova-plugin-fcm</a>).

This seems to work. When I add a notification in firebase, I get it in the phone with the parameters I have set.

Now I'm trying to get the parameters when the user entered into the app through a notification to take an special action with that data.

According the the documentation in the link above, I should add this event:

FCMPlugin.onNotification( function(data){ if(data.wasTapped) //Notification was received on device tray and tapped by the user. alert( JSON.stringify(data) ); }else{ //Notification was received in foreground. Maybe the user needs to be notified. alert( JSON.stringify(data) ); } }, function(msg){ console.log('onNotification callback successfully registered: ' + msg); }, function(err){ console.log('Error registering onNotification callback: ' + err); } );

However, no alert is displayed. And I don't find any way to debug it, since it only runs in mobile (not even emulated, only real one).

Something seems wrong? I only need for android. Also I'm including that event in the bindEvents when the app is loaded.

Answer1:

I had the same issue. But I had used this plugin <a href="https://github.com/arnesson/cordova-plugin-firebase" rel="nofollow">firebase-plugin</a> and made changes in these files

FirebasePluginMessagingService.java

package org.apache.cordova.firebase; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.text.TextUtils; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.searchtrade.demo.MainActivity; import java.util.Map; public class FirebasePluginMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebasePlugin"; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // If the application is in the foreground handle both data and notification messages here. // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. String title = null; String text = null; String category = null; int id = 0; if (remoteMessage.getNotification() != null) { title = remoteMessage.getNotification().getTitle(); text = remoteMessage.getNotification().getBody(); } else { title = remoteMessage.getData().get("title"); text = remoteMessage.getData().get("text"); category = remoteMessage.getData().get("category"); try { id = Integer.valueOf(remoteMessage.getData().get("id")); } catch (Exception e) { // ignore } } Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Title: " + title); Log.d(TAG, "Notification Message Body/Text: " + text); Log.d(TAG, "myNewMessageBody: " + title); // TODO: Add option to developer to configure if show notification when app on foreground if (!TextUtils.isEmpty(text) || !TextUtils.isEmpty(title)) { sendNotification(id, title, text, category,remoteMessage.getData()); } } private void sendNotification(int id, String title, String messageBody,String category, Map<String, String> data) { Intent intent = new Intent(this, OnNotificationOpenReceiver.class); Bundle bundle = new Bundle(); for (String key : data.keySet()) { bundle.putString(key, data.get(key)); } bundle.putString("myTitle",title); bundle.putString("myMessageBody",messageBody); bundle.putString("myCategory",category); // additional payload data Log.d(TAG, "myMessageBody: " + messageBody); intent.putExtras(bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getApplicationInfo().icon) .setContentTitle(title) .setContentText(messageBody) .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id, notificationBuilder.build()); } }

OnNotificationOpenReceiver.java

package org.apache.cordova.firebase; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class OnNotificationOpenReceiver extends BroadcastReceiver { String title,text,category; private static final String TAG = "BroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { // Toast.makeText(context,"test6",Toast.LENGTH_SHORT).show(); Intent i = new Intent(context, CustomLaunchUrl.class); /////////////// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ////////////// Bundle data = intent.getExtras(); title = data.getString("myTitle"); text = data.getString("myMessageBody"); category = data.getString("myCategory"); Bundle dt = new Bundle(); dt.putString("finalTitle",title); dt.putString("finalBody",text); dt.putString("finalCategory",category); i.putExtras(dt); Log.d(TAG,"Notification working test: "); // Toast.makeText(context,title+" "+text,Toast.LENGTH_LONG).show(); context.startActivity(i); } }

Adding new file for custom page launch with custom function

CustomLaunchUrl.java

package org.apache.cordova.firebase; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Toast; import org.apache.cordova.CordovaActivity; public class CustomLaunchUrl extends CordovaActivity { String x,y,z; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // load the layout Bundle d = getIntent().getExtras(); x = d.getString("finalTitle"); y = d.getString("finalBody"); z = d.getString("finalCategory"); //Toast.makeText(CustomLaunchUrl.this, x+" "+y, Toast.LENGTH_SHORT).show(); loadUrl("file:///android_asset/www/networkStats_2.html"); // change html as your need final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after 5s = 5000ms loadUrl("javascript:set_ndata('"+x+"','"+y+"','"+z+"')"); } }, 2000); } }

Add this in Platforms/android/AndroidManifest.xml

<activity android:name="org.apache.cordova.firebase.CustomLaunchUrl"> </activity>

And in your www/networkStats_2.html add this function

function set_ndata(x,y,z) //got payload data in html page { alert(x); alert(y); alert(z); }

Recommend

  • Real Time Notification for Angular 2 web app with asp.net web API back end [closed]
  • How to write a JSONObject to a file, which has JSONArray inside it, in Java?
  • Angular2: Central Session Service?
  • how do i convert unix timestamp in integer to human readable format in django template?
  • Why does Scala Try not catching java.lang.StackOverflowError?
  • How to read local variables with gdb?
  • How to calculate the points between two given points and given distance?
  • NSOutlineView with NSTreeController bindings with core data
  • Reversibly encode two large integers of different bit lengths into one integer
  • Trying to create and loop through matrix of unbalanced data in R
  • java.io.IOException: [JSR82] while connecting to a bluetooth device
  • How to iterate through a Firebird Database without having to completely load it inside my program?
  • Can I augment images and masks in Keras just using flow() instead of flow_from_directory?
  • How to get mouseover event from android emulator
  • How do I get Unity to inject a reference to HttpSessionState to a service
  • Rebuilding again and again to view the imported QML file changes
  • Rails Template Error with Heroku
  • Get an image from the video
  • How to make responsive images in flutter?
  • Thick underline when hover AND when active
  • Custom Timeline items in Glimpse
  • Why do you need 2 Javascript files for cross-platform Cordova plugin?
  • What does “T extends Junk” mean in a generic class in Java?
  • How to use array in autohotkey?
  • Generate and export point cloud from Project Tango
  • How do I use libcurl to printf a remote FTP directory listing?
  • Java .policy file - how to prevent java.util.Date() from being accessible
  • PHPMailer return to AJAX
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • How to clear a browser cache in Protractor
  • How to turn off notice reporting in xampp?
  • jQuery scrollTop if URL has hash
  • `$http:badreq Bad Request Configuration` - from angular post method, what is wrong here?
  • Call Microservice from another Microservice within Docker
  • Creating random wired topology for given arbitrary number of nodes on NS2
  • ReferenceError: TextEncoder is not defined