Phonegap Cordova的Firebase通知 [英] Firebase notification in Phonegap Cordova

查看:321
本文介绍了Phonegap Cordova的Firebase通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在PhoneGap中将通知添加到我的应用程序中。
为此,我使用这个插件( https://github.com/fechanique / cordova-plugin-fcm )。



这似乎起作用。当我在firebase中添加通知时,我使用已设置的参数在手机中获得它。



现在我试图在用户输入时获取参数该应用程序通过一个通知采取一个特殊的行动与该数据。

根据上面的链接中的文档,我应该添加此事件:

$ b (b
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $在设备托盘上并由用户点击
alert(JSON.stringify(data));
} else {
//在前台接收到通知,可能需要通知用户。
alert(JSON.stringify(data));
}
},
function(msg){
console.log('onNotification callback successfully registered:'+ msg);
},
函数(err){
console.log('注册onNotification回调错误: + ERR);
}
)的

但是,不显示警报。我找不到任何方法来调试它,因为它只能在手机上运行(甚至没有模拟,只有真正的)。



有些东西看起来不对?我只需要android。
另外,当应用程序被加载时,我将这个事件包含在 bindEvents 中。

解决方案

我有同样的问题。但是我已经使用了这个插件 firebase-plugin 并对这些文件进行了修改



FirebasePluginMessagingService.java

  package org.apache.cordova.firebase; 

导入android.app.NotificationManager;
导入android.app.PendingIntent;
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.media.RingtoneManager;
导入android.net.Uri;
导入android.os.Bundle;
导入android.support.v4.app.NotificationCompat;
导入android.util.Log;
导入android.text.TextUtils;

导入com.google.firebase.messaging.FirebaseMessagingService;
导入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;

/ **
*收到消息时调用。
*
* @param remoteMessage表示从Firebase云消息收到的消息的对象。
* /

@Override
public void onMessageReceived(RemoteMessage remoteMessage){

// TODO(开发人员):在这里处理FCM消息。
//如果应用程序在前台处理数据和通知消息。
//同样,如果您打算根据收到的FCM
//消息生成您自己的通知,那么这里是应该启动的地方。请参阅下面的sendNotification方法。
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);
尝试{
id = Integer.valueOf(remoteMessage.getData()。get(id));
} catch(Exception e){
// ignore
}
}
Log.d(TAG,From:+ remoteMessage.getFrom());
Log.d(标签,通知消息标题:+标题);
Log.d(TAG,Notification Message Body / Text:+ text);

Log.d(TAG,myNewMessageBody:+ title);
// TODO:向开发者添加选项以配置在前台应用程序显示通知
if(!TextUtils.isEmpty(text)||!TextUtils.isEmpty(title)){
sendNotification (id,title,text,category,remoteMessage.getData());



$ b 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(); (String key:data.keySet()){
bundle.putString(key,data.get(key));


}
bundle.putString(myTitle,title);
bundle.putString(myMessageBody,messageBody);
bundle.putString(myCategory,category); //附加有效载荷数据

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)$ b $ .setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(id,notificationBuilder.build());



$ b $ $ $ $ $ $ $ $ $ $ OnNotificationOpenReceiver.java


  package org.apache.cordova.firebase; 

导入android.app.PendingIntent;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.os.Bundle;
导入android.util.Log;
导入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,通知工作测试:);
// Toast.makeText(context,title ++ text,Toast.LENGTH_LONG).show();
context.startActivity(i);





$ p
$ b

为自定义页面启动添加新文件自定义函数

CustomLaunchUrl.java
$ b $ pre $ package $ org.apache。 cordova.firebase;

导入android.app.Activity;
导入android.content.Context;
导入android.os.Bundle;
导入android.os.Handler;
导入android.util.Log;
导入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);
//载入布局

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); //将html改为你的需要
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
@Override
public void run(){
//在5s = 5000ms之后做某事
loadUrl(javascript: set_ndata('+ x +','+ y +','+ z +'));
}
},2000);




$ p $在平台/ android / AndroidManifest.xml中添加

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

并在您的www / networkStats_2.html中添加此功能

 函数set_ndata(x,y,z)//在html页面获得有效载荷数据
{
alert(x);
alert(y);
alert(z);
}


I'm trying to add notifications to my app in PhoneGap. For that, I'm using this plugin (https://github.com/fechanique/cordova-plugin-fcm).

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.

解决方案

I had the same issue. But I had used this plugin firebase-plugin 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);
}

这篇关于Phonegap Cordova的Firebase通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆