WindowManager$BadTokenException: Unable to add window
1、http://tech.shantanugoel.com/2010/07/08/badtokenexception-android-dialog-getapplicationcontext.html
logcat输出:
Uncaught handler: thread main exiting due to uncaught exception
android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application
这里是这样解释的
It isn’t apparent immediately that what is causing this error. The very first line in the code “Context mContext = getApplicationContext();” is the culprit.
Solution: Just replace “getApplicationContext()” with “this” (i.e. “Context mContext = this;” ) and it will work fine.
Explanation: As to why this is exactly an issue, I’m a bit fuzzy about it myself but this much I’m sure that the contexts that you get with getApplicationContext and this are different. On reading about this function from Android SDK help:
这不是明显的直接的原因引起这个错误。第一行代码“上下文mContext = getApplicationContext();“是罪魁祸首。
解决方案:更换“getApplicationContext()”与“this”(即“上下文mContext =这;”),它会正常工作。
解释:为什么这就是一个问题,我有点模糊自己但这一点我敢肯定,你获得的getApplicationContext上下文是不对的。 阅读有关该函数从Android SDK帮助:
2、http://zoulu1.blog.163.com/blog/static/46733149201212711929363/
// 退出主程序dialog public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
dialog();
return false; }
return super.onKeyDown(keyCode, event); }
protected void dialog() {
AlertDialog.Builder builder = new Builder(FindwebActivity.this);
builder.setMessage("确定要退出心愿吗?"); builder.setTitle("提示");
builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AgentApp.getInstance().onTerminate(); } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); } });
builder.create().show(); }
//改成AlertDialog.Builder builder = new Builder(FindwebActivity.this);
即可AlertDialog.Builder builder = new Builder(getParent());