我正在尝试在onMessageReceived
课程的MyFirebaseMessagingService
中显示提醒消息,但我收到错误消息:
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();
}
有关如何在onMessageReceived中打开警报对话框的任何建议。
由于 [R
答案 0 :(得分:1)
这是我的问题的两分钱:
使用Activity
上下文显示对话框或任何与UI相关的内容。你开始活动的方式也不是它的开放方式。您可以选择在顶部栏上显示通知并在其上设置PendingIntent
,以便点击它可以打开所需的活动。 Open specific Activity when notification clicked in FCM
不要从BaseActivity
获取对onMessageReceived
的引用,而是将它们分开。使用LocalBroadcastManager
或Handler
向活动发送消息以显示对话框。这样,如果活动打开,它将对其采取行动,否则它将不会做任何事情。查看GCM IntentService how to display a pop up on notification receive
答案 1 :(得分:0)
问题是这一行:BaseActivity baseActivity = new BaseActivity(); 您不应该创建Activity的实例,它应该由系统通过Intent创建。当您通过“new”命令创建实例时,它被视为普通类,并且所有上下文都是错误的。
想法是开始一项活动并让活动处理对话。 快速解决方法是这样的:
@覆盖 public void onMessageReceived(RemoteMessage remoteMessage){
if (remoteMessage.getData().size() > 0) {
Intent intent = new Intent(this, BaseActivity.class);
startActivity(intent);
}
}
在BaseActivity.class上,在onCreate()方法中调用showDialog()。