我无法在AsyncTask中创建对话框。有人可以帮忙吗?我收到错误“android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序”。
这是我的代码:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTaskTest at=new AsyncTaskTest();
at.execute();
}
public class AsyncTaskTest extends AsyncTask<Void, String, Void> {
protected Void doInBackground(Void... vd){
try{
String desc = "Show Dialog without error";
publishProgress(desc);
}catch(Exception e){
publishProgress("Error: "+e.toString());
}
return null;
}
protected void onProgressUpdate(String... msg) {
showDialog(msg[0]);
}
private void showDialog(String msg){
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(getApplicationContext(), android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
}).show();
}
}
}
答案 0 :(得分:7)
尝试更改
getApplicationContext()
到:
MainActivity.this
有:
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(getApplicationContext(), android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
}).show();
}
答案 1 :(得分:1)
使用以下代替
final AlertDialog.Builder alertBox = new AlertDialog.Builder(
YourActivity.this,
android.R.style.Theme_Dialog);
答案 2 :(得分:0)
`
Handler handler=new Handler();
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTaskTest at=new AsyncTaskTest();
at.execute();
}
public class AsyncTaskTest extends AsyncTask<Void, String, Void> {
protected Void doInBackground(Void... vd){
try{
String desc = "Show Dialog without error";
publishProgress(desc);
}catch(Exception e){
publishProgress("Error: "+e.toString());
}
return null;
}
protected void onProgressUpdate(String... msg) {
handler.postRunnable(new Runnable(){
showDialog(msg[0]);
});
}
private void showDialog(String msg){
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(getApplicationContext(), android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
}).show();
}
}
}`