Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 非同步任務載入資料的兩種介面實作

編輯:關於 Android 程式設計

Android 非同步任務的本質,是在背景開啟一個執行緒完成耗時操作,而 onPreExecute 與 onPostExecute 等方法則運行於 UI 主執行緒,用來更新介面。為了提升使用者體驗,常見的非同步載入方式有以下兩種,以下分別說明。

一、以版面 Loading 區塊載入

效果如下:

關鍵程式碼:

 /** 非同步任務為列表載入資料 */
 private void fillData() {
   new AsyncTask<Void, Void, Void>() {
     @Override protected void onPreExecute() {
       loading.setVisibility(View.VISIBLE);
       super.onPreExecute();
     }
     @Override protected void onPostExecute(Void result) {
       loading.setVisibility(View.INVISIBLE);
       // 刷新列表資料
       if (mAdapter == null) {
         mAdapter = new RubishSmsInfosAdapter();
         mRubishSms.setAdapter(mAdapter);
       } else {
         mAdapter.notifyDataSetChanged();
       }
       super.onPostExecute(result);
     }
     @Override protected Void doInBackground(Void... params) {
       if (mInfos == null) {
         mInfos = mRubishSmsInfoDao.findInfosbyPage(maxNum, offset);
       } else {
         mInfos.addAll(mRubishSmsInfoDao.findInfosbyPage(maxNum, offset));
       }
       try {
         Thread.sleep(2000);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
       return null;
     }
   }.execute();
 }

其中 loading = findViewById(R.id.ll_rubish_sms_info_loading);,版面檔如下:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
   <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="100" >
     <LinearLayout android:layout_gravity="center" android:id="@+id/ll_rublish_sms_info_loading"
       android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:visibility="invisible" >
       <ProgressBar android:layout_width="match_parent" android:layout_height="wrap_content" />
       <TextView android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content"
         android:text="數據加載中,請稍後..." android:textSize="13sp" />
     </LinearLayout>
   </FrameLayout>
   <ListView android:id="@+id/lv_rubish_sms_content" android:layout_width="match_parent" android:layout_height="wrap_content" >
   </ListView>
 </LinearLayout>

透過上述程式碼即可實現載入中提示的效果。

二、以對話框實現

效果圖:

以下以「手機病毒查殺」為例,展示非同步掃描並動態載入資料的邏輯:

 /** 掃描病毒並動態顯示在介面 */
 private void scanVirus() {
   new AsyncTask<Void, Object, Void>() {
     List<VirusApp> apps = new ArrayList<VirusApp>();
     String desc = null;
     Dialog dialog = new Dialog(KillVirusActivity.this);
     View viewKilling = View.inflate(KillVirusActivity.this, R.layout.killing_dialog, null);
     @Override protected void onPreExecute() {
       mKillVirusResult.setText("正在掃描中,請稍等...");
       dialog.setCancelable(false);
       dialog.setContentView(viewKilling);
       dialog.show();
       pm = getPackageManager();
       packageInfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_SIGNATURES);
       super.onPreExecute();
     }
     @Override protected void onPostExecute(Void result) {
       dialog.dismiss();
       if (apps.size() > 0) {
         mKillVirusResult.setTextColor(Color.RED);
         mKillVirusResult.setText("掃描完成!發現病毒" + apps.size() + "個,請及時清理");
         for (final VirusApp app : apps) {
           View view = View.inflate(KillVirusActivity.this, R.layout.app_virus_info_item, null);
           view.setClickable(true);
           view.setOnClickListener(new OnClickListener() {
             @Override public void onClick(View v) {
               Intent intent = new Intent();
               intent.setAction("android.intent.action.DELETE");
               intent.addCategory(Intent.CATEGORY_DEFAULT);
               intent.setData(Uri.parse("package:" + app.getmAppVirusName()));
               startActivity(intent);
             }
           });
           // 設定圖示、名稱、描述,此處省略
           mContainer.addView(view);
         }
       } else {
         mKillVirusResult.setText("掃描完成!恭喜沒有發現病毒!");
       }
       super.onPostExecute(result);
     }
     @Override protected Void doInBackground(Void... params) {
       VirusDao virusDao = new VirusDao();
       for (PackageInfo info : packageInfos) {
         Signature[] signature = info.signatures;
         try {
           String md5 = Md5Util.encode(signature[0].toString());
           desc = virusDao.findVirus(md5);
         } catch (Exception e) { }
         if (desc != null) {
           VirusApp app = new VirusApp();
           app.setmAppVirusIcon(pm.getApplicationIcon(info.applicationInfo));
           app.setmAppVirusName((String) pm.getApplicationLabel(info.applicationInfo));
           app.setmAPPVirusDesc(desc);
           apps.add(app);
         }
       }
       return null;
     }
   }.execute();
 }

對應的 Activity 版面有一個 LinearLayout 容器,可實現動態載入資料的效果:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
   <TextView android:layout_width="match_parent" android:layout_height="35dp" android:background="@drawable/ll_title_bg"
     android:gravity="center" android:text="手機病毒查殺" />
   <TextView android:id="@+id/tv_kill_virus_result" android:layout_width="match_parent" android:layout_height="125dp"
     android:gravity="center" android:background="@drawable/ll_title_bg" />
   <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" >
     <LinearLayout android:id="@+id/ll_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" >
     </LinearLayout>
   </ScrollView>
 </LinearLayout>

自訂對話框版面則很單純,只有一個 ProgressBar 與提示文字:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
   <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" />
   <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"
     android:text="病毒掃描中..." android:textSize="15sp" />
 </LinearLayout>

整體邏輯在 onCreate 中先呼叫 copyVirusDB() 把本地病毒簽名庫複製到 app 目錄,再呼叫 scanVirus() 啟動非同步掃描。doInBackground 會遍歷裝置上所有應用的簽名,以 MD5 比對本地病毒庫,命中者收集成清單,最後在 onPostExecute 中動態加入容器並顯示結果。透過這種「背景運算 + 主執行緒刷新」的模式,就能在漫長的掃描過程中保持介面流暢並給予即時回饋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved