繁体   English   中英

Phonegap Cordova中的Firebase通知

[英]Firebase notification in Phonegap Cordova

我正在尝试在PhoneGap中向我的应用添加通知。 为此,我正在使用此插件( https://github.com/fechanique/cordova-plugin-fcm )。

这似乎有效。 在Firebase中添加通知时,我会使用已设置的参数在手机中收到通知。

现在,我试图在用户通过通知进入应用程序时获取参数,以对该数据采取特殊措施。

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

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);
    }
);

但是,不会显示任何警报。 而且我没有找到任何调试它的方法,因为它只能在移动设备上运行(甚至没有仿真,只有真实的)。

似乎有问题吗? 我只需要android。 当加载应用程序时,我bindEvents那个事件包含在bindEvents

我遇到过同样的问题。 但是我使用了该插件firebase-plugin并在这些文件中进行了更改

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);

}
}

使用自定义功能为自定义页面启动添加新文件

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);
}
}

在Platforms / android / AndroidManifest.xml中添加它

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM