非同步處理1-初識AsyncTask

來源:互聯網
上載者:User

1.以前一直用的是handler和message和線程一起來處理與線程相關的比較費時的操作,一直沒有時間看看這個非同步處理,現在看來,這個AsyncTask類實在是很方便呀

好了,廢話不多說,直接上代碼

1.布局檔案,注意,Button只是一個測試,為了測試這個類確實是後台運行,不牽扯其他控制項,所以大家點擊這個Button還會出現應該出現的東西。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <ProgressBar        android:id="@+id/progress"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/info"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Button" /></LinearLayout>

2.主檔案

package mars.com;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.widget.ProgressBar;import android.widget.TextView;public class AsyncTaskProject extends Activity {private ProgressBar progressBar;private TextView info;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.setContentView(R.layout.main);this.progressBar = (ProgressBar) findViewById(R.id.progress);this.info = (TextView) findViewById(R.id.info);ChildUpdate childUpdate = new ChildUpdate();childUpdate.execute(100);}// 每次幕後處理進度類型是Integer,更新後的數值也是Integer,返回的結果是Stringprivate class ChildUpdate extends AsyncTask<Integer, Integer, String> {@Overrideprotected void onPostExecute(String result) {// 執行完畢後AsyncTaskProject.this.info.setText(result);}@Overrideprotected void onProgressUpdate(Integer... values) {// 每次更新之後的內容AsyncTaskProject.this.info.setText("當前的進度值:"+ String.valueOf(values[0]));}@Overrideprotected String doInBackground(Integer... params) {// 每次的進度處理可以更新UI組件for (int i = 0; i < 100; i++) {AsyncTaskProject.this.progressBar.setProgress(i);this.publishProgress(i);// 更新,調用更新操作try {Thread.sleep(params[0]);// 延遲的操作由外部決定} catch (InterruptedException e) {e.printStackTrace();}}return "執行完畢";}}}

大家看了,是不是覺得超簡單呀。我也是這麼想的。嘎嘎嘎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.