在我的主 activity
中,我需要调用一个内部类,并在该类的方法中显示 AlertDialog
。在其关闭后,当用户按下“OK”按钮时,跳转到 Google Play 进行购买。
大多数情况下都能正常工作,但对于某些用户来说,在调用 builder.show()
时会出现崩溃,从崩溃日志中可以看到 "android.view.WindowManager$BadTokenException:
Unable to add window" 错误提示。请给出建议。
我的代码基本上是这样的:
public class classname1 extends Activity{
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.<view>);
//call the <className1> class to execute
}
private class classNamename2 extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params) {}
protected void onPostExecute(String result){
if(page.contains("error"))
{
AlertDialog.Builder builder = new AlertDialog.Builder(classname1.this);
builder.setCancelable(true);
builder.setMessage("");
builder.setInverseBackgroundForced(true);
builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.dismiss();
if(!<condition>)
{
try
{
String pl = "";
mHelper.<flow>(<class>.this, SKU, RC_REQUEST,
<listener>, pl);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
});
builder.show();
}
}
}
}
我在另一个警告中也看到了这个错误,其中我没有转发到任何其他activity
。 就像这样简单:
AlertDialog.Builder builder = new AlertDialog.Builder(classname1.this);
builder.setCancelable(true);
//if successful
builder.setMessage(" ");
builder.setInverseBackgroundForced(true);
builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
// dialog.dismiss();
}
});
builder.show();
}
//send to some other activity
。我认为如果你在去往新的Activity的部分加上注释,这个错误就会消失。这个错误似乎是因为你的对话框在完全关闭之前,新的Activity已经开始了。在onPostExecute()
中,你有一个警告对话框,并且你正在给出login
Activity 的上下文。但是你正在导航到另一个Activity,所以上下文变得不正确。因此你会得到这个错误!请参考 http://stackoverflow.com/questions/15104677/alertdialog-creating-exception-in-android 相似的问题。 - Shobhit Puri