I try to use AlertDialog in onMessageReceived, but I have this error.
05-04 11:27:40.038 30721-31424/com.xxx.xxx E/AndroidRuntime: FATAL EXCEPTION: pool-4-thread-1
Process: com.xxx.xxx, PID: 30721
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.Dialog.<init>(Dialog.java:108)
at android.app.AlertDialog.<init>(AlertDialog.java:125)
at android.app.AlertDialog$Builder.create(AlertDialog.java:967)
at android.app.AlertDialog$Builder.show(AlertDialog.java:986)
at com.xxx.xxx.util.FirebaseMessagingService.optionalAlert(FirebaseMessagingService.java:78)
at com.xxx.xxx.util.FirebaseMessagingService.onMessageReceived(FirebaseMessagingService.java:38)
at com.google.firebase.messaging.FirebaseMessagingService.zzl(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.zzJ(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(Unknown Source)
at com.google.firebase.iid.zzb$1.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
This is my code:
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String msg=remoteMessage.getNotification().getBody();
Map<String, String> params = remoteMessage.getData();
String Valuekey = remoteMessage.getData().get("key");
if (Valuekey.equals("true")) {
optionalAlert();
}else {
Util.Alert(this,getString(R.string.ConsignmentNoFound));
}
// Util.Alert(getBaseContext(),msg);
}
private void optionalAlert () {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
TextView textView = new TextView(this);
textView.setText(getString(R.string.ConsignmentFound));
textView.setTextSize(24);
adb.setCustomTitle(textView);
//adb.setTitle(getString(R.string.ConsignmentFound));
adb.setIcon(android.R.drawable.ic_dialog_alert);
adb.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent nextActivity = new Intent(FirebaseMessagingService.this, MainActivity.class);
nextActivity.putExtra("act", "PinValidate");
startActivity(nextActivity);
} });
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
} });
adb.show();
}
}
You can't show dialog in Receiver because Receive has different 'Context' which is not for showing any User Interface.
If you want to show Dialog then start an Activity which will have Dialog Theme.