gpt4 book ai didi

android - 将 Firebase 通知的 MessageBody 显示为 Toast

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:49 25 4
gpt4 key购买 nike

我在显示 Toast 消息时遇到运行时异常

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

当用户从应用中的任何位置收到推送通知时,我想将消息正文显示为 Toast 消息。

有什么帮助吗?

public class MyAppFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "FCM Service";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
if (AppConfig.SYSTEM_WIDE_DEBUG) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}

sendNotification(remoteMessage.getNotification().getBody());
}

}

private void sendNotification(String messageBody) {
Toast.makeText(getApplicationContext(),messageBody,Toast.LENGTH_LONG).show();

Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pushnotify);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon( R.mipmap.ic_launcher)
.setContentTitle("My APP")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

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

notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

最佳答案

如果你想在 UI Thread 上显示 Toast.Run 是最好的方法;

例子:

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

另一种方式:

if (Looper.myLooper() == null) {
Looper.prepare();
Toast.makeText(getApplicationContext(), "xxxxxxxxx", Toast.LENGTH_SHORT).show();
Looper.loop();
}

因为源码中Toast使用了Handler,但是当前Thread没有初始化Looper。

关于android - 将 Firebase 通知的 MessageBody 显示为 Toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41729152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com