1.Unable to add window --token null is not valid; is your activity running
- 2.Unable to add window --token null is not for an application
- 3.Unable to add window -- token android.os.BinderProxy@XXX is not valid;
is your activity running - Unable to add window -- token android.app.LocalActivityManager
$LocalActivityRecord @xxx is not valid; is your activity running
该异常多见于Popup Window组件的使用中抛出。
原因:错误在PopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM,0,0); popwindow必须依附于某一个view,而在oncreate中view还没有加载完毕,必须要等activity的生命周期函数全部执行完毕,你需要依附的view加载好后才可以执行popwindow。
解决办法1:showAtLocation()函数可以这样改:
//修正后代码
总结: PopupWindow必须在某个事件中显示或者是开启一个新线程去调用,不能直接在onCreate方法中显示一个Popupwindow,否则永远会有以上的错误。
参考:
http://stackoverflow.com/questions/4187673/problems-creating-a-popup-window-in-android-activity
原因:错误在PopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM,0,0); popwindow必须依附于某一个view,而在oncreate中view还没有加载完毕,必须要等activity的生命周期函数全部执行完毕,你需要依附的view加载好后才可以执行popwindow。
解决办法1:showAtLocation()函数可以这样改:
//修正后代码
findviewById(R.id.mView).post(new Runnable() {
@Override
public void run() {
popwindow.showAtLocation(mView, Gravity.CENTER, 0, 0);
}
});
总结: PopupWindow必须在某个事件中显示或者是开启一个新线程去调用,不能直接在onCreate方法中显示一个Popupwindow,否则永远会有以上的错误。
参考:
http://stackoverflow.com/questions/4187673/problems-creating-a-popup-window-in-android-activity
解决办法2:修改弹窗时机
1、移到事件中(比如一个button的click事件中);
2、移到子线程中;另起一线程,在线程中不断循环,直到判断控件是否渲染完毕(如长宽大于0),不推荐。。。
3、移到重写的控件(parent)中,在控件ondraw()完后生成pop。
ps:1、2绝对没问题,3没测试过。
2、移到子线程中;另起一线程,在线程中不断循环,直到判断控件是否渲染完毕(如长宽大于0),不推荐。。。
3、移到重写的控件(parent)中,在控件ondraw()完后生成pop。
ps:1、2绝对没问题,3没测试过。
代码如下:
Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
showPopupWindow(getApplicationContext());
}
}
情形2.android.view.WindowManager$BadTokenException: Unable to add window --token null is not for an application ?异常处理。$BadTokenException: Unable to add window -- token null is not for an application E/AndroidRuntime(1412): at android.view.ViewRootImpl.setView(ViewRootImpl.java:538) ......该异常多见于AlertDialog组件的使用中抛出。//抛异常代码原因:导致报这个错是在于new AlertDialog.Builder(mcontext),虽然这里的参数是AlertDialog.Builder(Context context),但我们不能使用getApplicationContext()获得的Context,而必须使用Activity,因为只有一个Activity才能添加一个窗体。解决方法:将new AlertDialog.Builder(Context context)中的参数用Activity.this(Activity是你的Activity的名称)或者getActivity()来填充就可以正确的创建一个Dialog了。//修正后代码
new AlertDialog.Builder(getActivity()) //不能用getApplicationContext()
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Warnning")
.setPositiveButton("Yes", positiveListener)
.setNegativeButton( "No", negativeListener)
.create().show();
参考:
http://stackoverflow.com/questions/20779377/android-custom-dialog-gives-an-error