Toast未显示在FireBase云消息传递服务的onMessageReceived中

时间:2016-08-16 17:09:06

标签: firebase-cloud-messaging

我使用下面的代码来制作Log,Toast并从onMessageReceived向服务发送广播。

我可以在日志中看到使用Firebase控制台发送的数据。但Toast没有显示,广播也没有发送。

以下代码:

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

2 个答案:

答案 0 :(得分:4)

Toast未显示,因为onMessageReceived()代码未在主线程上执行...要显示Toast,您应该在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();
      }
    });

我遇到了同样的麻烦,希望它有所帮助。

答案 1 :(得分:0)

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

<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&gt;下的项目级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'
}

希望这有帮助!