我正在阅读AsyncTask,我尝试了下面的简单程序.但它似乎没有用.我怎样才能使它工作?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output); …Run Code Online (Sandbox Code Playgroud) 我试图在我的一个活动的onCreate()方法期间显示进度对话框,完成工作以填充线程中完成的屏幕,然后关闭进度对话框.
这是我的onCreateMethod()
dialog = new ProgressDialog(HeadlineBoard.this);
dialog.setMessage("Populating Headlines.....");
dialog.show();
populateTable();
Run Code Online (Sandbox Code Playgroud)
populateTable方法包含我的线程和解除对话框的代码,但由于某种原因.活动空白大约10秒(执行populateTable()工作),然后我看到屏幕.我从来没有看到对话框显示,任何想法?
这是populateTable()代码:
//Adds a row to the table for each headline passed in
private void populateTable() {
new Thread() {
@Override
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread"); …Run Code Online (Sandbox Code Playgroud) 有没有办法在AsyncTask的doinbackground()中执行UI任务.我很清楚在onPostExecute方法中做得更好.但在我的情况下,因为我需要使用可重复使用的警报,能够访问我的doinbackground中的UI将节省我很多时间.也就是说,我需要在46个地方调整代码,但是能够在doinbackground中执行此操作只需要在一个地方进行更改.
提前致谢