2017-07-18 93 views
-1

我没有收到任何通知。我正在使用Firebase功能。该功能正常工作。我在Firebase日志中获得成功消息。未收到通知Firebase

我index.js功能:

let functions = require('firebase-functions'); 

let admin = require('firebase-admin'); 

admin.initializeApp(functions.config().firebase); 


exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}') 
    .onWrite(event => { 
    if (!event.data.current.val()) { 
    return console.log('User '); 
} 
     const message = event.data.current.val(); 
     const senderUid = message.from; 
     const receiverUid = message.to; 
     const promises = []; 

     if (senderUid == receiverUid) { 
      //if sender is receiver, don't send notification 
      promises.push(event.data.current.ref.remove()); 
      return Promise.all(promises); 
     } 

     const getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/instanceId`).once('value'); 
     const getSenderUidPromise = admin.auth().getUser(senderUid); 

     return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results => { 
      const instanceId = results[0].val(); 
      const sender = results[1]; 
      console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid); 

      const notification = { 
       data: { 
        title: sender.displayName, 
        body: message.body, 
        //icon: sender.photoURL 
       } 
      }; 

      return admin.messaging().sendToDevice(instanceId, payload) 
       .then(function (response) { 
       console.log("Successfully sent message:", payload); 
        console.log("Successfully sent message:", response); 
       }) 
       .catch(function (error) { 
        console.log("Error sending message:", error); 
       }); 
     }); 
    }); 

我得到令牌和数据库也是正确的。 MyFirebaseMessaging类

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 
     @Override 
     public void onMessageReceived(RemoteMessage remoteMessage) { 

      // Check if message contains a data payload. 
      if (remoteMessage.getData().size() > 0) { 
       Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 

       String title = remoteMessage.getData().get("title"); 
       String message = remoteMessage.getData().get("text"); 
       String username = remoteMessage.getData().get("username"); 
       String uid = remoteMessage.getData().get("uid"); 
       String fcmToken = remoteMessage.getData().get("fcm_token"); 

       // Don't show notification if chat activity is open. 
       if (!ChatMainApp.isChatActivityOpen()) { 
        sendNotification(title, 
          message, 
          username, 
          uid, 
          fcmToken); 
       } else { 
        EventBus.getDefault().post(new PushNotificationEvent(title, 
          message, 
          username, 
          uid, 
          fcmToken)); 
       } 
      } 
     } 

     /** 
     * Create and show a simple notification containing the received FCM message. 
     */ 

     private void sendNotification(String title, 
             String message, 
             String receiver, 
             String receiverUid, 
             String firebaseToken) { 
      Intent intent = new Intent(this, chat.class); 
      intent.putExtra("receiver", receiver); 
      intent.putExtra("receiverid", receiverUid); 
      intent.putExtra("firebasetoken", firebaseToken); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
        PendingIntent.FLAG_ONE_SHOT); 

      Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
      NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.ic_notifications_black_24dp) 
        .setContentTitle(title) 
        .setContentText(message) 
        .setAutoCancel(true) 
        .setSound(defaultSoundUri) 
        .setContentIntent(pendingIntent); 

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

      notificationManager.notify(0, notificationBuilder.build()); 
     } 

    } 

我的清单

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.main.food"> 

    <application 
     android:allowBackup="true" 

     android:icon="@mipmap/ic_launcher" 
     android:largeHeap="true" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar"> 
     </activity> 

     <activity 
      android:name=".firebaselogin" 
      android:screenOrientation="portrait" 
      android:configChanges="orientation|keyboardHidden" 
      android:theme="@style/Theme.AppCompat.NoActionBar"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
      </activity> 
     <activity android:name="com.facebook.FacebookActivity" 
      android:configChanges= 
       "keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
      android:label="@string/app_name" /> 
     <activity 
      android:name="com.facebook.CustomTabActivity" 
      android:exported="true"> 
      <intent-filter> 
       <action android:name="android.intent.action.VIEW" /> 
       <category android:name="android.intent.category.DEFAULT" /> 
       <category android:name="android.intent.category.BROWSABLE" /> 
       <data android:scheme="@string/fb_login_protocol_scheme" /> 
      </intent-filter> 
     </activity> 
     <service android:name=".MyFirebaseMessagingService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.MESSAGING_EVENT"/> 
      </intent-filter> 
     </service> 
     <service android:name=".FirebaseIdService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> 
      </intent-filter> 
     </service> 
     <meta-data android:name="com.facebook.sdk.ApplicationId" 
      android:value="@string/facebook_app_id"/> 
     <meta-data android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 
    </application> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.USE_CREDENTIALS" /> 
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
    <uses-permission android:name="android.permission.CAMERA" /> 
    <uses-feature android:name="android.hardware.camera" /> 
    <uses-feature android:name="android.hardware.camera.autofocus" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
</manifest> 

我指定的服务清单中的应用程序标记中,我得到令牌,我已经存储在用户表中的相同。

OnMessageReceived从未被调用,我试着调试它。

请有人可以帮助我这个。

+0

你有没有在'AndroidMenifest.xml'中指定你的服务类? – Ninja

+0

请查看https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ – Ninja

回答

0

看看这个Set Up a Firebase Cloud Messaging Client App on Android

也许你错过了FirebaseInstanceIdService的设置。

的Manifest.xml

<service android:name=".MyFirebaseInstanceIDService"> 
<intent-filter> 
    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> 
</intent-filter> 

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 

private static final String TAG = "MyFirebaseIIDService"; 

/** 
* Called if InstanceID token is updated. This may occur if the security of 
* the previous token had been compromised. Note that this is called when the InstanceID token 
* is initially generated so this is where you would retrieve the token. 
*/ 
@Override 
public void onTokenRefresh() { 
    // Get updated InstanceID token. 
    String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
    Log.d(TAG, "Refreshed token: " + refreshedToken); 
}} 

您需要注册目的这项服务使FCM可以找到您的设备。