您的位置:首页 > 其它

自定义下载的封装实现

2017-08-29 22:51 267 查看
DownloadHelper.java

package com.studio.asynctaskproject;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* 1. download方法 url localPath listener
* 2.listener:start success fail progress
* 3.用asynctask封装的
* Created by Administrator on 2017/8/29.
*/

class DownloadHelper {

static void download(String url, String localPath, OnDownloadListener listener) {

DownloadAsyncTask task = new DownloadAsyncTask(url, localPath, listener);
task.execute();
}

private static class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {

String mUrl;
String mFilePath;
OnDownloadListener onDownloadListener;

DownloadAsyncTask(String mUrl, String mFilePath, OnDownloadListener onDownloadListener) {
this.mUrl = mUrl;
this.mFilePath = mFilePath;
this.onDownloadListener = onDownloadListener;
}

/**
* 在异步任务之前,在主线程中
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
//可操作UI  之前的准备工作
if (onDownloadListener != null) {
onDownloadListener.onStart();
}
}

/**
* 在另外一个线程中处理事件
*
* @param strings 入参
* @return 结果
*/
@Override
protected Boolean doInBackground(String... strings) {
String apkUrl = mUrl;

try {
//构造URL
URL url = new URL(apkUrl);
//构造链接,并打开
URLConnection urlConnection = url.openConnection();

InputStream inputStream = urlConnection.getInputStream();
//获取了下载内容的总长度
int contentLength = urlConnection.getContentLength();

//对下载地址进行处理
File apkFi
4000
le = new File(mFilePath);
if (apkFile.exists()) {
boolean result = apkFile.delete();
if (!result) {
if (onDownloadListener != null) {
onDownloadListener.onFail(-1, apkFile, "文件删除失败");
}
return false;
}
}

//已下载的大小
int downloadSize = 0;

//byte数组
byte[] bytes = new byte[1024];

int length;

//创建一个输入管道
OutputStream outputStream = new FileOutputStream(mFilePath);

//不断的从网络读取字节到byte数组再写入文件中
while ((length = inputStream.read(bytes)) != -1) {
//读取的字节放到文件管道里
outputStream.write(bytes, 0, length);
//累加下载进度
downloadSize += length;
//发送进度
publishProgress(downloadSize * 100 / contentLength);
}
inputStream.close();
outputStream.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
if (onDownloadListener != null) {
onDownloadListener.onFail(-2, new File(mFilePath), e.getMessage());
}
return false;
}

if (onDownloadListener != null) {
onDownloadListener.onSuccess(0, new File(mFilePath));
}
return true;
}

@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
//在UI线程中,执行结果 处理

}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//收到进度,然后处理:  在UI线程中
if (values != null && values.length > 0) {
if (onDownloadListener != null) {
onDownloadListener.onProgress(values[0]);
}
}

}

}

public interface OnDownloadListener {
void onStart();

void onSuccess(int code, File file);

void onFail(int code, File file, String message);

void onProgress(int progress);

abstract class SimpleDownloadListener implements OnDownloadListener {

@Override
public void onStart() {

}

@Override
public void onProgress(int progress) {

}
}
}
}


MainActivity.java

package com.studio.asynctaskproject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* 1. 网络上请求数据:申请网络权限 读写存储权限
* 2. 布局我们的layout
* 3. 下载前我们要做什么?  UI
* 4. 下载中我们要做什么?  数据
* 5. 下载后我们要做什么?  UI
*/

public class MainActivity extends AppCompatActivity {

public static final int INIT_PROGRESS = 0;
public static final String APK_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
private ProgressBar mProgressBar;
private Button mDownloadButton;
private TextView mResultTextView;
private String FILE_NAME;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//初始化视图
initView();

//初始化UI数据
setData();

//设置点击监听
setListener();

DownloadHelper.download(APK_URL, "", new DownloadHelper.OnDownloadListener.SimpleDownloadListener() {
@Override
public void onSuccess(int code, File file) {

}

@Override
public void onFail(int code, File file, String message) {

}
});
}

/**
* 初始化视图
*/
private void initView() {

mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDownloadButton = (Button) findViewById(R.id.button);
mResultTextView = (TextView) findViewById(R.id.textView);
}

private void setListener() {

mDownloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: 2017/8/20 下载任务
DownloadAsyncTask asyncTask = new DownloadAsyncTask();
asyncTask.execute(APK_URL);
}
});
}

private void setData() {

mProgressBar.setProgress(INIT_PROGRESS);
mDownloadButton.setText(R.string.click_download);
mResultTextView.setText(R.string.download_text);
}

/**
* String 入参
* Integer 进度
* Boolean 返回值
*/
private class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {

private String mFilePath;

/**
* 在异步任务之前,在主线程中
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
//可操作UI  之前的准备工作
mDownloadButton.setText(R.string.downloading);
mResultTextView.setText(R.string.downloading);
mProgressBar.setProgress(INIT_PROGRESS);
}

/**
* 在另外一个线程中处理事件
*
* @param strings 入参
* @return 结果
*/
@Override
protected Boolean doInBackground(String... strings) {
if (strings != null && strings.length > 0) {
String apkUrl = strings[0];

try {
//构造URL
URL url = new URL(apkUrl);
//构造链接,并打开
URLConnection urlConnection = url.openConnection();

InputStream inputStream = urlConnection.getInputStream();
//获取了下载内容的总长度
int contentLength = urlConnection.getContentLength();

//下载地址准备,File.separator是斜线
FILE_NAME = "imooc.apk";
mFilePath = Environment.getExternalStorageDirectory()
+ File.separator + FILE_NAME;

//对下载地址进行处理
File apkFile = new File(mFilePath);
if (apkFile.exists()) {
boolean result = apkFile.delete();
if (!result) {
return false;
}
}

//已下载的大小
int downloadSize = 0;

//byte数组
byte[] bytes = new byte[1024];

int length;

//创建一个输入管道
OutputStream outputStream = new FileOutputStream(mFilePath);

//不断的从网络读取字节到byte数组再写入文件中
while ((length = inputStream.read(bytes)) != -1) {
//读取的字节放到文件管道里
outputStream.write(bytes, 0, length);
//累加下载进度
downloadSize += length;
//发送进度
publishProgress(downloadSize * 100 / contentLength);
}
inputStream.close();
outputStream.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}

return true;
}

@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
//在UI线程中,执行结果 处理
mDownloadButton.setText(aBoolean ? getString(R.string.download_finish) : getString(R.string.download_fail));
mResultTextView.setText(aBoolean ? getString(R.string.download_finish) + mFilePath : getString(R.string.download_fail));

}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//收到进度,然后处理:  在UI线程中
if (values != null && values.length > 0) {
mProgressBar.setProgress(values[0]);
}

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐