4 多線程下載的原理是這樣的:通常服務(wù)器同時與多個用戶連接,用戶之間共享帶寬。如果N個用戶的優(yōu)先級都相同,那么每個用戶連接到該服務(wù)器上的實際帶寬就是服務(wù)器帶寬的N分之一??梢韵胂螅绻脩魯?shù)目較多,則每個用戶只能占有可憐的一點帶寬,下載將會是個漫長的過程。如果你通過多個線程同時與服務(wù)器連接,那么你就可以榨取到較高的帶寬了。 實現(xiàn)的效果如下:當文件下載完成之后,提示下載完成,當用戶再次下載的時候,檢查文件的版本,如果內(nèi)容沒有更新,則提示不同下載
package com.xzh.ui; import java.io.File; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.xzh.androiddownload.R; import com.xzh.imp.DownloadProgressListener; import com.xzh.imp.FileDownloader; public class MainActivity extends Activity { private ProgressBar downloadbar; private EditText pathText; private TextView resultView; private Handler handler = new Handler(){ @Override//信息 public void handleMessage(Message msg) { switch (msg.what) { case 1: int size = msg.getData().getInt("size"); downloadbar.setProgress(size); float result = (float)downloadbar.getProgress()/ (float)downloadbar.getMax(); int p = (int)(result*100); resultView.setText(p+"%"); if(downloadbar.getProgress()==downloadbar.getMax()) Toast.makeText(MainActivity.this, R.string.success, 1).show(); break; case -1: Toast.makeText(MainActivity.this, R.string.error, 1).show(); break; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)this.findViewById(R.id.button); downloadbar = (ProgressBar)this.findViewById(R.id.downloadbar); pathText = (EditText)this.findViewById(R.id.path); resultView = (TextView)this.findViewById(R.id.result); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String path = pathText.getText().toString(); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File dir = Environment.getExternalStorageDirectory();//文件保存目錄 download(path, dir); }else{ Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show(); } } }); } //對于UI控件的更新只能由主線程(UI線程)負責(zé),如果在非UI線程更新UI控件,更新的結(jié)果不會反映在屏幕上,某些控件還會出錯 private void download(final String path, final File dir){ new Thread(new Runnable() { @Override public void run() { try { FileDownloader loader = new FileDownloader(MainActivity.this, path, dir, 3); int length = loader.getFileSize();//獲取文件的長度 downloadbar.setMax(length); loader.download(new DownloadProgressListener(){ @Override public void onDownloadSize(int size) {//可以實時得到文件下載的長度 Message msg = new Message(); msg.what = 1; msg.getData().putInt("size", size); handler.sendMessage(msg); }}); } catch (Exception e) { Message msg = new Message();//信息提示 msg.what = -1; msg.getData().putString("error", "下載失敗");//如果下載錯誤,顯示提示失敗! handler.sendMessage(msg); } } }).start();//開始 } } </div |