Android 开发工具类 15_ MyAsyncTask

时间:2023-12-10 20:13:50

AsyncTask 对于生命周期较短且需要在UI上显示进度和结果的后台操作是很好的解决方案。然而,当 Activity 重新启动时,这种操作将不会持续进行,也就是说,AsyncTask 在设备的方向变化而导致 Activity 被销毁和重新创建时会被取消。对于生命周期较长的后台操作,如从 Internet 下载数据,使用 Service 组件是更好的选择。

 private class MyAsyncTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... parameter) {
// Moved to a background thread.
String result = "";
int myProgress = 0; int inputLength = parameter[0].length(); // Perform background processing task, update myProgress]
for (int i = 1; i <= inputLength; i++) {
myProgress = i;
result = result + parameter[0].charAt(inputLength-i);
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
publishProgress(myProgress);
} // Return the value to be passed to onPostExecute
return result;
} @Override
protected void onProgressUpdate(Integer... progress) {
// Synchronized to UI thread.
// Update progress bar, Notification, or other UI elements
asyncProgress.setProgress(progress[0]);
} @Override
protected void onPostExecute(String result) {
// Synchronized to UI thread.
// Report results via UI update, Dialog, or notifications
asyncTextView.setText(result);
}
}

执行异步任务。每一个 AsyncTask 实例只能执行一次。如果试图第二次调用 execute,则会抛出一个异常。

 private void executeAsync() {
/**
* Listing 9-12: Executing an asynchronous task
*/
String input = "redrum ... redrum";
new MyAsyncTask().execute(input);
}