安卓Dialog

运用反射来显示dialog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

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");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});

builder.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();
}
});
}
}


}