android中實(shí)現(xiàn)OkHttp下載文件并帶進(jìn)度條
OkHttp是比較火的網(wǎng)絡(luò)框架,它支持同步與異步請(qǐng)求,支持緩存,可以攔截,更方便下載大文件與上傳文件的操作。下面我們用OkHttp來(lái)下載文件并帶進(jìn)度條!
相關(guān)資料:
官網(wǎng)地址:http://square.github.io/okhttp/
github源碼地址:https://github.com/square/okhttp
一、服務(wù)器端簡(jiǎn)單搭建
可以參考搭建本地Tomcat服務(wù)器及相關(guān)配置 這篇文章。
新建項(xiàng)目OkHttpServer,在WebContent目錄下新建downloadfile目錄,將要下載的jpg文件放在項(xiàng)目下。如下圖:
啟動(dòng)服務(wù)器,文件下載地址為http://localhost:8080/OkHttpServer/download/2.jpg 。這樣我們服務(wù)器就搭好了。
二、Android端
下面我們進(jìn)入正題。
1.build.gradle的dependencies配置如下
compile 'com.android.support:appcompat-v7:24.1.1' compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.okio:okio:1.7.0'
2.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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.huang.myokhttp.MainActivity">
<Button
android:id="@+id/ok_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下載文件" />
<TextView
android:id="@+id/download_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0" />
<ProgressBar
android:id="@+id/download_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100" />
</RelativeLayout>
3.編寫(xiě)OkHttpUtil如下:
private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
.readTimeout(10000,TimeUnit.MILLISECONDS)
.writeTimeout(10000,TimeUnit.MILLISECONDS).build();
//下載文件方法
public static void downloadFile(String url, final ProgressListener listener, Callback callback){
//增加攔截器
OkHttpClient client = okHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response.newBuilder().body(new ProgressResponseBody(response.body(),listener)).build();
}
}).build();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
4.上面代碼中的ProgressResponseBody是自己編寫(xiě)的類(lèi),ProgressListener 是監(jiān)聽(tīng)的接口:
ProgressListener 接口
public interface ProgressListener {
//已完成的 總的文件長(zhǎng)度 是否完成
void onProgress(long currentBytes, long contentLength, boolean done);
}
ProgressResponseBody繼承ResponseBody ,返回監(jiān)聽(tīng)進(jìn)度
public class ProgressResponseBody extends ResponseBody {
public static final int UPDATE = 0x01;
public static final String TAG = ProgressResponseBody.class.getName();
private ResponseBody responseBody;
private ProgressListener mListener;
private BufferedSource bufferedSource;
private Handler myHandler;
public ProgressResponseBody(ResponseBody body, ProgressListener listener) {
responseBody = body;
mListener = listener;
if (myHandler==null){
myHandler = new MyHandler();
}
}
/**
* 將進(jìn)度放到主線程中顯示
*/
class MyHandler extends Handler {
public MyHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE:
ProgressModel progressModel = (ProgressModel) msg.obj;
//接口返回
if (mListener!=null)mListener.onProgress(progressModel.getCurrentBytes(),progressModel.getContentLength(),progressModel.isDone());
break;
}
}
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource==null){
bufferedSource = Okio.buffer(mySource(responseBody.source()));
}
return bufferedSource;
}
private Source mySource(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
totalBytesRead +=bytesRead!=-1?bytesRead:0;
//發(fā)送消息到主線程,ProgressModel為自定義實(shí)體類(lèi)
Message msg = Message.obtain();
msg.what = UPDATE;
msg.obj = new ProgressModel(totalBytesRead,contentLength(),totalBytesRead==contentLength());
myHandler.sendMessage(msg);
return bytesRead;
}
};
}
}
5.MainActivity的代碼:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static final String TAG = MainActivity.class.getName();
private ProgressBar download_progress;
private TextView download_text;
public static String basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okhttp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download_progress = (ProgressBar) findViewById(R.id.download_progress);
download_text = (TextView) findViewById(R.id.download_text);
findViewById(R.id.ok_download).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.ok_download:
String url = "http://192.168.0.104:8080/OkHttpServer/download/2.jpg";
final String fileName = url.split("/")[url.split("/").length - 1];
Log.i(TAG, "fileName==" + fileName);
OkHttpUtil.downloadFile(url, new ProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength, boolean done) {
Log.i(TAG, "currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
int progress = (int) (currentBytes * 100 / contentLength);
download_progress.setProgress(progress);
download_text.setText(progress + "%");
}
}, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null) {
InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(new File(basePath + "/" + fileName));
int len = 0;
byte[] buffer = new byte[2048];
while (-1 != (len = is.read(buffer))) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
is.close();
}
}
});
break;
}
}
}
6.最后不要忘了添加權(quán)限:
<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"/>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android 七種進(jìn)度條的樣式
- android自定義進(jìn)度條漸變色View的實(shí)例代碼
- Android中實(shí)現(xiàn)Webview頂部帶進(jìn)度條的方法
- Android文件下載進(jìn)度條的實(shí)現(xiàn)代碼
- Android編程之ProgressBar圓形進(jìn)度條顏色設(shè)置方法
- android ListView和ProgressBar(進(jìn)度條控件)的使用方法
- Android中自定義進(jìn)度條詳解
- Android實(shí)現(xiàn)進(jìn)度條(ProgressBar)的功能與用法
- 實(shí)例詳解Android自定義ProgressDialog進(jìn)度條對(duì)話框的實(shí)現(xiàn)
- Android自定義View實(shí)現(xiàn)進(jìn)度條動(dòng)畫(huà)
相關(guān)文章
Android?PowerManagerService?打開(kāi)省電模式
這篇文章主要介紹了Android?PowerManagerService打開(kāi)省電模式,文章通告省電模式的打開(kāi)過(guò)程、什么是?battery?saver?sticky?模式兩部分展開(kāi)詳情,感興趣的朋友可以參考一下2022-08-08
Flutter交互并使用小工具管理其狀態(tài)widget的state詳解
這篇文章主要為大家介紹了Flutter交互并使用小工具管理其狀態(tài)widget的state詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
Android不顯示開(kāi)機(jī)向?qū)Ш烷_(kāi)機(jī)氣泡問(wèn)題
這篇文章主要介紹了Android不顯示開(kāi)機(jī)向?qū)Ш烷_(kāi)機(jī)氣泡問(wèn)題,需要的朋友可以參考下2019-05-05
Android 指紋識(shí)別詳解及實(shí)現(xiàn)方法
本文主要介紹Android 指紋識(shí)別的知識(shí),這里整理了詳細(xì)的資料和簡(jiǎn)單實(shí)現(xiàn)代碼,有開(kāi)發(fā)這部分的朋友可以參考下2016-09-09
Android UI設(shè)計(jì)系列之自定義DrawView組件實(shí)現(xiàn)數(shù)字簽名效果(5)
這篇文章主要介紹了Android UI設(shè)計(jì)系列之自定義DrawView組件實(shí)現(xiàn)數(shù)字簽名效果,具有一定的實(shí)用性和參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
Android Studio和Gradle使用不同位置JDK的問(wèn)題解決
這篇文章主要介紹了Android Studio和Gradle使用不同位置JDK的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Android制作登錄頁(yè)面并且記住賬號(hào)密碼功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android制作登錄頁(yè)面并且記住賬號(hào)密碼功能的實(shí)現(xiàn)代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04

