Pra*_*yap 3 firebase-cloud-messaging
我使用以下代码制作Log,Toast并从onMessageReceived发送广播到服务。
我可以在日志中看到使用Firebase控制台发送的数据。但是Toast没有显示,Broadcast也没有发送。
代码如下:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于未在主线程上执行onMessageReceived()代码,因此未显示Toast。要显示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();
}
});
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的麻烦,希望对您有所帮助。
归档时间: |
|
查看次数: |
2335 次 |
最近记录: |