在onMessageReceived中没有显示ToMessageReceived的FireBase Colud消息服务

问题描述:

我已经使用了下面的代码来制作Log,Toast并从onMessageReceived发送广播到服务。在onMessageReceived中没有显示ToMessageReceived的FireBase Colud消息服务

我能够在日志中看到使用Firebase控制台发送的数据。但吐司不显示,广播也不发送。

代码如下:

class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 

     Log.d(TAG, "From: " + remoteMessage.getFrom()); 
     Toast.makeText(getApplicationContext(),"From: " + remoteMessage.getFrom(),Toast.LENGTH_SHORT).show(); 

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

     } 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
      Toast.makeText(getApplicationContext(),"Toast shown",Toast.LENGTH_LONG).show(); 
      Intent i = new Intent(); 
      i.setAction("firebase.message.combinedthings"); 
      sendBroadcast(i); 
     } 
    } 
} 

我遇到这个问题很长一段时间,也有一些值得注意的建议: 首先请确保您要添加的服务,您的应用程序的清单文件:

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

其次确保您已添加:

classpath 'com.google.gms:google-services:3.0.0' 

到buildscript在你的项目级的build.gradle>依赖关系以及:

apply plugin: 'com.google.gms.google-services' 

到您的应用级的build.gradle的底部。 最后没有人推荐这个,但我试过它作为最后的手段,我确信我的每一个Firebase编译都是v9.4.0。有一次,我改变了它为我工作,所以一定要检查您的应用程序级的build.gradle以及(这是我的样子:)

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    testCompile 'junit:junit:4.12' 

    compile 'com.android.support:appcompat-v7:24.1.1' 
    compile 'com.android.support:support-v4:24.1.1' 
    compile 'com.firebase:firebase-client-android:2.4.0' 
    compile 'com.google.firebase:firebase-crash:9.4.0' 
    compile 'com.google.firebase:firebase-core:9.4.0' 
    compile 'com.google.firebase:firebase-messaging:9.4.0' 
    compile 'com.google.firebase:firebase-auth:9.4.0' 
    compile 'com.android.support:recyclerview-v7:24.1.1' 
} 

希望这有助于!

+0

感谢您的回答。我解决了问题我现在可以发送广播,而Toast现在发出错误,所以我删除了敬酒的代码。 –

未显示敬酒,因为没有被主线程执行onMessageReceived()的代码...为了显示吐司你应该做的UI线程调用:

Handler handler = new Handler(Looper.getMainLooper()); 
    handler.post(new Runnable() { 
     public void run() { 
     Toast.makeText(getApplicationContext(), "Toast on UI thread", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

我有同样的麻烦,希望它有帮助。