我试图在MyFirebaseMessagingService
类的onMessageReceived
中显示一条警报消息,我会发现一个错误:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Activity.<init>(Activity.java:846)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:38)
at android.support.v4.app.BaseFragmentActivityApi14.<init>(BaseFragmentActivityApi14.java:28)
at android.support.v4.app.BaseFragmentActivityApi16.<init>(BaseFragmentActivityApi16.java:34)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:67)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at com.dopay.onboarding.activity.BaseActivity.<init>(BaseActivity.java:51)
at com.dopay.onboarding.FMS.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:75)
at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(Unknown Source)
at com.google.firebase.iid.zzc.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
02
我尝试过的。
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
BaseActivity baseActivity = new BaseActivity();
baseActivity.showDialog();
}
}
baseactivity
public void showDialog(){
this.runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
DialogUtil.showAlert(getApplicationContext(), R.string.message_complete_required_fields);
}
});
}
dialogutil
public static void showAlert(Context context, int messageId) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(messageId)
.setCancelable(true)
.setPositiveButton(context.getResources().getString(R.string.label_ok), null);
builder.create().show();
}
关于如何在OnMessageRecevered中打开警报对话框的任何建议。
谢谢r
这是我问题的两美分:
-
使用
Activity
上下文显示对话框或与UI相关的任何内容。同样,您开始活动的方式,这不是开放的方式。您可以选择在顶部栏上显示通知并在其上设置PendingIntent
,以便单击它可以打开所需的活动。单击FCM
的通知时打开特定活动 ,而不是从
onMessageReceived
获取对BaseActivity
的引用,而是将其解耦。使用LocalBroadcastManager
或Handler
将消息发送到活动以显示对话框。这样,如果活动开放,它将对此作用,否则不会做任何事情。检查GCM IntentService如何在通知接收中显示弹出
问题是该行:baseeactivity baseactivity = new BaseActivity((;您不应创建活动实例,应该通过系统来创建它。当您通过" new"命令创建实例时,它被视为正常类,所有上下文都是错误的。
这个想法是启动活动并让活动处理对话框。快速修复是这样的:
@Override public void onMessageReceived(remotemessage remotemessage({
if (remoteMessage.getData().size() > 0) {
Intent intent = new Intent(this, BaseActivity.class);
startActivity(intent);
}
}
在baseactivity.class上,increate((方法中的showdialog((。