android.view.WindowManager$BadTokenException: Unable to add window – token [email protected]
程序员文章站
2022-06-05 14:20:47
...
异常:
android.view.WindowManager$BadTokenException: Unable to add window – token [email protected] is not valid; is your activity runing?
异常打印日志:
-
FATAL EXCEPTION: main
-
Process: dianshi.matchtrader, PID: 27499
-
android.view.WindowManager$BadTokenException: Unable to add window – token [email protected]43cf0778 is not valid; is your activity running?
-
at android.view.ViewRootImpl.setView(ViewRootImpl.java:594)
-
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:269)
-
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
-
at android.app.Dialog.show(Dialog.java:323)
异常出现原因:
异常定位在我弹出对话框的时候,为什么会在弹出对话框的时候出现崩溃了呢?
这个异常的意思是:无法弹出窗口,确认你要弹出的这个窗口基于的activity是当前的运行的activity吗?
原因是:
1.点击登录按钮,登录成功后会LoginActivity自动跳转到MainActivity,
2.我在登录的页面做了一个是否有异地登录的检测,如果检测到有异地登录就弹出提示的对话框,对话框的创建时基于LoginActivity的
3.这一次刚好我刚登录上去跳转的时候,弹出了提示框。此时显示的activity是MainActivity,不是LoginActivity
解决方法:
让这个对话框不要依附于某个Activity弹出,而是基于栈顶的Activity,也就是当前显示的activity弹出
1.获取栈顶的Activity的名称
-
/**
-
* 得到栈顶Activity的名称
-
* @param context
-
* @return
-
*/
-
public String getTopActivity(Context context){
-
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
-
List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(1);
-
-
-
if (list != null){
-
ComponentName componentName = list.get(0).topActivity;
-
-
//包名
-
String packName = componentName.getPackageName();//packName=com.dr.dr_testappmanager
-
-
//包名+类名,这是是我们需要的
-
String className = componentName.getClassName();//className=com.dr.dr_testappmanager.MainActivity
-
-
String nameStr = componentName.toString();//ComponentInfo{com.dr.dr_testappmanager/com.dr.dr_testappmanager.MainActivity}
-
-
-
return className;
-
-
}
-
-
return null;
-
-
}
2.通过获取到的类名,使用反射,可以得到该类的实例
-
try {
-
//创建一个Class类的引用,调用Class类的静态方法forName(String),参数为类的绝对路径
-
Class clazz = Class.forName("com.dr.dr_testappmanager.MainActivity");
-
-
//现在我们有了一个Class类的实例了。下面就是
-
Object object = clazz.newInstance();
-
-
//获取一个Object类的实例对象
-
Activity activity = (Activity)object;
-
-
//使用该类创建Dialog
-
Dialog dialog = new Dialog(activity);
-
-
-
} catch (ClassNotFoundException e) {
-
e.printStackTrace();
-
} catch (InstantiationException e) {
-
e.printStackTrace();
-
} catch (IllegalAccessException e) {
-
e.printStackTrace();
-
}