以下代码给出了强制关闭错误
public class MainActivity extends Activity {
Button b1;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new loadSomeStuff().execute();
}
});
}
public class loadSomeStuff extends AsyncTask<String, Integer, String> {
ProgressDialog dlg;
protected void onPreExecute() {
dlg = new ProgressDialog(MainActivity.this);
dlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dlg.setMessage("Loding Please Wait");
dlg.setMax(100);
dlg.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(
Environment.getExternalStorageDirectory() + "/"
+ "/bg.pdf"));
document.open();
document.add(new Paragraph("hie"));
Toast.makeText(getApplicationContext(), "Generated",
Toast.LENGTH_LONG).show();
document.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dlg.dismiss();
return null;
}
protected void onProgressUpdated(Integer... progress) {
dlg.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result) {
tv.setText("DONE");
}
}
答案 0 :(得分:1)
您正在尝试从非ui线程中删除对话框,doInBackground
方法可能不调用接口内容。从那里删除dlg.dismiss();
并将其放在onPostExecute
方法上,可以修改ui 。
为了澄清,doInBackground
顾名思义,是一个后台线程,它无法直接控制用户界面,这就是为什么当你试图关闭对话框时,它会失败
需要咖啡。
答案 1 :(得分:1)
在AsynTask中,只有doInBackGround()适用于后台线程
这意味着你可以在其他方法中访问UI元素,如 onPostExceute(),onPreExceute(),onProgressUpdated() 不在doInBackground()
删除了dlg.dismiss()并且它已完成