Android開發高級進階——多線程(實現簡單下載器)
每個Android應用在被啓動時都會創建一個線程,這個線程稱爲主線程或UI線程,Android應用的所有操作都會運行在這個線程中。但是爲了保證UI的流暢性,通常會將耗時操作放到子線程中,例如IO操作、網絡請求等。而幾乎每個Android應用都會涉及到網絡請求等耗時操作,所以多線程對於Android來說變得至關重要。
什麼是多線程?
線程:是進程中單一的連續控制流程/執行路徑。
多線程:多個線程並行執行。
二.爲什麼要使用多線程?
使用多線程可以提高效率,並且不會使程序出現卡頓現象(比如ANR)。
三.什麼時候使用多線程?
Android3.0以及以後的版本中,禁止在主線程執行網絡請求,否則會拋出異常,可見在UI線程中執行耗時操作是不推薦的行爲。所以,在進行與耗時操作同步進行的操作時(即並行)使用多線程。
四.如何使用多線程?
我們經常說Android中的主線程是線程不安全的,所以只能在主線程中更新UI。那麼如何更新主線程且保證線程是安全的呢?
Android中提供了保證線程安全的幾種解決方案:
- 使用Handler實現線程之間的通信。
- Activity.runOnUiThread(Runnable):一般在Activity的Thread中運用。
- View.post(Runnable)
- View.postDelayed(Runnable, long)
Android中的線程分爲主線程(UI線程)和工作線程。
- 主線程(UI線程):程序運行時被創建的線程。
- 工作線程:自己創建的線程。
以上兩個線程之間的通信最基本的有兩種:
Thread和Runnable
這裏通過實現一個簡單的下載器來學習Thread和Runnable。
這個下載器就一個界面,包含一個輸入框,一個進度條,用來顯示下載進度,用來輸入下載地址,一個按鈕,用來開始下載。
界面代碼如下:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
tools:context="com.trampcr.downloaddemo.MainActivity">
<EditText
android:id="@+id/et_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="請輸入下載地址" />
<ProgressBar
android:id="@+id/pb_down_load"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/et_url"
android:layout_marginTop="30dp"
android:max="100" />
<TextView
android:id="@+id/tv_progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/pb_down_load"
android:layout_marginTop="20dp"
android:text="下載進度"
android:textColor="#000000" />
<Button
android:id="@+id/btn_start_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_progress"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:background="@drawable/btn_style"
android:text="開始下載"
android:textColor="#000000" />
</RelativeLayout>
細心的人可能會注意到這裏的按鈕用了一個背景@drawable/btn_style,這裏是自定義按鈕的形狀。代碼如下:btn_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:topLeftRadius="10dp"
android:radius="8dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp" />
<stroke android:color="#000000"
android:width="0.7dp"/>
</shape>
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//public static final String DOWNLOAD_URL = "http://psoft.33lc.com:801/small/rootexplorer_33lc.apk";
private Button mBtnStartDownload;
private EditText mEtUrl;
private String mUrl;
private ProgressBar mPbDownload;
private TextView mTvProgress;
private Handler mHandler = new DownloadHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtUrl = (EditText) findViewById(R.id.et_url);
mBtnStartDownload = (Button) findViewById(R.id.btn_start_download);
mPbDownload = (ProgressBar) findViewById(R.id.pb_down_load);
mTvProgress = (TextView) findViewById(R.id.tv_progress);
mBtnStartDownload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
mUrl = mEtUrl.getText().toString().trim();
new Thread(new Runnable() {
@Override
public void run() {
download(mUrl);
}
}).start();
}
private void download(String mUrl) {
try {
URL url = new URL(mUrl);
URLConnection urlConnection = url.openConnection();
int contentLength = urlConnection.getContentLength(); //下載文件大小
InputStream inputStream= urlConnection.getInputStream();
String downloadFolderName = Environment.getExternalStorageDirectory() + File.separator + "trampcr" + File.separator;
File file = new File(downloadFolderName);
if (!file.exists()){
file.mkdir();
}
String fileName = downloadFolderName + "zxm.apk";
File apkFile = new File(fileName);
if (apkFile.exists()) {
apkFile.delete();
}
int downloadSize = 0;
byte[] buff = new byte[1024];
int length = 0;
OutputStream outputStream = new FileOutputStream(fileName);
while ((length = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, length);
downloadSize += length;
int progress = downloadSize * 100 / contentLength;
Message msg = mHandler.obtainMessage();
msg.what = 0;
msg.obj = progress;
mHandler.sendMessage(msg);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static class DownloadHandler extends Handler{
public final WeakReference<MainActivity> weakRefActivity;
public DownloadHandler(MainActivity mainActivity) {
weakRefActivity = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MainActivity activity = weakRefActivity.get();//判斷是否被回收
switch (msg.what){
case 0:
int progress = (int) msg.obj;
activity.mPbDownload.setProgress(progress);
activity.mTvProgress.setText("下載進度:" + progress + "%");
if (progress == 100){
Toast.makeText(activity, "下載完成", Toast.LENGTH_LONG).show();
}
break;
}
}
}
}
所需要的權限:
<uses-permission android:name="android.permission.INTERNET"/>
效果如如下:
注:這裏面用到了一個我不太熟悉的知識:WeakReference的理解與使用
文/trampcr(簡書作者)
原文鏈接:http://www.jianshu.com/p/6a558a23084a
著作權歸作者所有,轉載請聯繫作者獲得授權,並標註“簡書作者”。