AsyncTask异步任务
程序员文章站
2024-01-28 09:12:46
...
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ProgressDialog mDialog;
private TextView textView;
@SuppressLint("StaticFieldLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv);
mDialog = new ProgressDialog(this);
mDialog.setMax(100);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setCancelable(true);
mDialog.setMessage("正在加载");
new AsyncTask<Void, Integer, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
textView.setText("数据开始加载...");
mDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("数据正在加载中...");
}
});
for (int i = 0; i <= 100; i++) {
SystemClock.sleep(50);
publishProgress(i);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Void aVoid) {
mDialog.dismiss();
textView.setText("数据加载完毕");
super.onPostExecute(aVoid);
}
}.execute();
}
}
下一篇: C++函数模板与分离编译模式