FireBase云消息服务中onMessageReceived中的Toast不显示问题

3

我已经使用以下代码来记录日志、显示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个回答

6
请注意,不建议仅将服务数据直接发布到主线程(至少不考虑所有可能的后果)...但是,为了测试的目的:
Toast未显示是因为onMessageReceived()代码没有在主线程上执行...要显示Toast,您应该在UI线程上进行调用:
Kotlin版本:
Handler(Looper.getMainLooper()).post {
            Toast.makeText(getApplicationContext(), "FCM!!", Toast.LENGTH_SHORT).show()
}

Java版本:

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

我也遇到了同样的问题,希望这能有所帮助。

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'

在您的项目级别的 build.gradle 文件中,找到 buildscript > dependencies 部分,并添加以下内容:

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'
}

希望这能帮到你!


感谢您的回答。我的问题得到解决,我现在能够发送广播,但是 Toast 现在出现了错误,所以我已经删除了 Toast 的代码。 - Prashant Kashyap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接