Dialog is built by ui context. The approach to show dialog without ui context (activity) in some case: call dialog in rest api, show dialog after own activity finish, call dialog in first activity and want to show it in the next activity also.
First: use Broadcast receiver
Assume: We call open dialog after delay timeout and run TestActivity concurrently in MainActivity.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import java.util.HashMap;
/**
* Created by nhancao on 10/31/16.
*/
public class Alerts {
public static void register(Activity activity) {
AlertReceiver.register(activity);
}
public static void unregister(Activity activity) {
AlertReceiver.unregister(activity);
}
public static void displayError(Context context, String msg) {
Intent intent = new Intent("MyApplication.INTENT_DISPLAYERROR");
intent.putExtra(Intent.EXTRA_TEXT, msg);
context.sendOrderedBroadcast(intent, null);
}
private static void displayErrorInternal(Context context, String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Error").setMessage(msg).setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog…