弹出一个AlertDialog,不一定需要Activity级别的Context,而且任何地方都有办法弹出一个AlertDialog,只要是在Application的attachBaseContext之后。
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.WindowManager;
import java.lang.reflect.Method;
public class Alert {
public static void alertDialog() {
Context mAppContext = null;
try {
Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method = clazz.getDeclaredMethod("currentApplication", new Class[0]);
mAppContext = (Context) method.invoke(null, new Object[0]);
} catch (Throwable e) {
e.printStackTrace();
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(mAppContext);
builder.setTitle("Hi")
.setMessage("Hello World");
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
}
dialog.show();
}
private static Handler handler;
public static void alertAnyWhere() {
if (Looper.myLooper() == Looper.getMainLooper()) {
alertDialog();
} else {
if (handler == null) {
handler = new Handler(Looper.getMainLooper());
}
handler.post(new Runnable() {
@Override
public void run() {
alertDialog();
}
});
}
}
}
ContentProvider的onCreate()方法先于Application的onCreate()方法执行,晚于Application的attachBaseContext()方法,所以在ContentProvider的onCreate()时候也是有办法弹出一个AlertDialog的。
BroadCastReceiver回调onReceive(Context context,Intent intent)中的context类型各种场景相差很大,静态注册的receiver回调的Context都是ReceiverRestrictedContext,动态注册的receiver有可能是Activity或Application。