編輯:關於Android編程
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);
sendMessage()與post()的區別:http://www.jb51.net/article/120624.htm
4. 內存洩漏
http://www.jb51.net/article/120627.htm
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" 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, "下載失敗!", Toast.LENGTH_SHORT).show(); break; } } } }
總結
以上所述是小編給大家介紹的Handler實現線程之間的通信下載文件動態更新進度條,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對本站網站的支持!
1 背景不能只分析源碼呀,分析的同時也要整理歸納基礎知識,剛好有人微博私信讓全面說說Android的動畫,所以今天來一發Android應用的各種Animation大集合。
??最新的android studio2.2引入了cmake可以很好地實現ndk的編寫。ffmpeg編譯??進入正題,既然是ffmpeg的移植編譯,那麼就先下載ffmpe
greenDAO 是一個將對象映射到 SQLite 數據庫中的輕量且快速的 ORM 解決方案。 官方網站http://greendao-orm.com/ 讓我們開始吧
筆者近2天在 Android Studio上玩了一下百度地圖,碰到了常見的230錯誤 APP Scode校驗失敗,下面我來介紹一下具體的解決辦法. 1.在andriod