我一直在尝试各种示例来熟悉 AsyncTask。到目前为止,我看到的所有示例都将 AsyncTask 包含在主要活动的 onCreate 方法中。我不太喜欢,所以我想看看将它分成自己的类有多难。到目前为止,我有这个:
主要活动
package com.example.asynctaskactivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.asynctaskactivity.ShowDialogAsyncTask;
public class AsyncTaskActivity extends Activity {
Button btn_start;
ProgressBar progressBar;
TextView txt_percentage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_start = (Button) findViewById(R.id.btn_start);
progressBar = (ProgressBar) findViewById(R.id.progress);
txt_percentage= (TextView) findViewById(R.id.txt_percentage);
Log.v("onCreate","Attempt set up button OnClickListener");
btn_start.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
btn_start.setEnabled(false);
new ShowDialogAsyncTask().execute();
}
});
Log.v("onCreate","Success!");
}
}
新的单独AsyncTask 类
package com.example.asynctaskactivity;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void>{
int progress_status;
@Override
protected void onPreExecute() {
// update the UI immediately after the task is executed
Log.v("onPreExecute","1");
super.onPreExecute();
Log.v("onPreExecute","2");
//Toast.makeText(AsyncTaskActivity.this,"Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
progress_status = 0;
Log.v("onPreExecute","3");
txt_percentage.setText("downloading 0%");
Log.v("onPreExecute","4");
}
@Override
protected Void doInBackground(Void... params) {
Log.v("doInBackground","1");
while(progress_status<100){
progress_status += 2;
publishProgress(progress_status);
SystemClock.sleep(300);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
txt_percentage.setText("downloading " +values[0]+"%");
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Toast.makeText(AsyncTaskActivity.this,"Invoke onPostExecute()", Toast.LENGTH_SHORT).show();
txt_percentage.setText("download complete");
btn_start.setEnabled(true);
}
}
最初这一切都在主要活动中,因此提到了异步任务理论上应该更新的元素。显然目前这会导致运行时错误,这让我开始思考。我怎样才能让文件分开但仍然更新 UI 线程。
对不起,如果这是一个愚蠢的问题,特别是对于 android 开发和后台线程来说是全新的。