国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Handler實現線程之間的通信下載文件動態更新進度條

2019-10-22 18:30:27
字體:
來源:轉載
供稿:網友

1. 原理

每一個線程對應一個消息隊列MessageQueue,實現線程之間的通信,可通過Handler對象將數據裝進Message中,再將消息加入消息隊列,而后線程會依次處理消息隊列中的消息。

2. Message

初始化:一般使用Message.obtain()方法獲取一個消息對象,該方法會檢查Message對象池中是否存在可重復利用的對象,若無,才會new一個新對象。

what:相當于Message的標識符,區別于其它消息。

arg1、arg2:int類型,可傳遞整數。

obj:object類型,可傳遞任意對象。

3. 發送消息

在子線程中可調用主線程的handler.sendMessage(msg)進行發送消息,經過一系列方法調用,會觸發handler的handleMessage方法,從而進行消息處理。

發送消息的主要方法:

handler.sendMessage(Message msg);handler.sendMessageAtTime(Message msg, int time);handler.sendMessageDelayed(Message msg, int time);

sendMessageAtTime()sendMessageDelayed()區別在于前者是在指定時間發送消息,可配合SystemClock.uptimeMillis()使用;而后者則是延時發送消息。

除了SendMessage()方法以外,還可以通過post()方法發送消息:

handler.post(Runnable r);handler.postDelayed(Runnable r, int time);

 

4. 內存泄漏

 

5. 通過Handler對象實現下載文件動態更新進度條

AndroidManifest加入權限聲明:

<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp" tools:context="com.studying.network.DownloadActivity"> <ProgressBar android:id="@+id/progress_bar" style="?android:progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" /> <Button android:id="@+id/download" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="@string/download" /></LinearLayout>

Activity:

public class DownloadActivity extends Activity { private static final int DOWNLOAD_MESSAGE_CODE = 100001; private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002; private static final String APP_URL = "http://clfile.imooc.com/class/assist/119/1328281/Android%20Studio%20教輔%20.pdf"; private MyHandler mHandler; private ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); findViewById(R.id.download).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //開啟子線程 new Thread(new Runnable() {  @Override  public void run() {  download(APP_URL);  } }).start(); } }); mProgressBar = (ProgressBar) findViewById(R.id.progress_bar); mHandler = new MyHandler(this); } private void download(String appUrl) { try { URL url = new URL(appUrl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); int contentLength = conn.getContentLength();//獲取文件總大小 String downloadPath = Environment.getExternalStorageDirectory() + File.separator + "imooc" + File.separator; File file = new File(downloadPath); if (!file.exists()) { file.mkdir(); } String fileName = downloadPath + "test.pdf"; File apkFile = new File(fileName); if (apkFile.exists()) { apkFile.delete(); } int downloadSize = 0;//記錄已經下載的大小 byte[] bytes = new byte[1024]; int length = 0; OutputStream out = new FileOutputStream(fileName); while ((length = in.read(bytes)) != -1) { out.write(bytes, 0, length); downloadSize += length; Message msg = Message.obtain(); msg.obj = downloadSize / contentLength * 100;//progress的值為0到100,因此得到的百分數要乘以100 msg.what = DOWNLOAD_MESSAGE_CODE; mHandler.sendMessage(msg); } in.close(); out.close(); } catch (IOException e) { notifyDownloadFailed(); e.printStackTrace(); } } private void notifyDownloadFailed() { Message msg = Message.obtain(); msg.what = DOWNLOAD_MESSAGE_FAIL_CODE; mHandler.sendMessage(msg); } private static class MyHandler extends Handler{ private WeakReference<DownloadActivity> weakReference; MyHandler(DownloadActivity activity) { this.weakReference = new WeakReference<>(activity);//以弱引用的形式傳遞Activity,避免內存泄漏 } @Override public void handleMessage(Message msg) { super.handleMessage(msg); DownloadActivity activity = weakReference.get(); //消息處理 switch (msg.what) { case DOWNLOAD_MESSAGE_CODE:  activity.mProgressBar.setProgress((Integer) msg.obj);  break; case DOWNLOAD_MESSAGE_FAIL_CODE:  Toast.makeText(activity, "下載失?。?quot;, Toast.LENGTH_SHORT).show();  break; } } }}

總結

以上所述是小編給大家介紹的Handler實現線程之間的通信下載文件動態更新進度條,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丘北县| 洛川县| 齐河县| 鄂托克前旗| 临泉县| 陈巴尔虎旗| 建水县| 米脂县| 邮箱| 牙克石市| 宁都县| 蓝田县| 南雄市| 台中县| 武平县| 涿州市| 鄢陵县| 福州市| 镇平县| 方城县| 昭苏县| 汝州市| 两当县| 建瓯市| 盐源县| 建昌县| 竹北市| 肥乡县| 沙湾县| 垦利县| 西青区| 尼木县| 泸溪县| 庄河市| 交口县| 阿鲁科尔沁旗| 松桃| 内江市| 八宿县| 安化县| 松溪县|