文件下载封装

来源:互联网 发布:mac上对u盘格式化 编辑:程序博客网 时间:2024/06/01 08:10
文件下载


import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;


import com.school.thesis.R;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("HandlerLeak")
public class FileDown {


private static boolean state = true;
private static TextView mMessageView;
private static ProgressBar mProgressbar;
private static AlertDialog mProgressDialog;


@SuppressWarnings("deprecation")
public static void downFile(Context context, int posId, String midpath, String fjname, String filePath) {
/*
* posId 文件在列表中的位置; midpath 文件保存目录; fjname 文件名称 filePath 文件在服务器上的路径;
*/
final String loadpath = midpath + URLDecoder.decode(fjname);
if (fileIsExists(loadpath)) {
try {
Intent it = GetUriMime.openFile(new File(loadpath));
context.startActivity(it);
} catch (Exception e) {
e.printStackTrace();
// alertTip5(context);
Toast.makeText(context, "请选择打开方式或安装相关软件打开!", Toast.LENGTH_LONG).show();
return;
}
} else {
state = true;
if (!NetWork.isNetworkConnected(context)) {
alertTip1(context);
} else if (!NetWork.isWifiConnected(context) && !NetWork.isMobileConnected(context)) {
alertTip2(context);
} else if (NetWork.getConnectedType(context) == ConnectivityManager.TYPE_MOBILE) {
alertTip3(context, posId, midpath, fjname, filePath);
} else {
alertTip4(context, posId, midpath, fjname, filePath);
}
}
}


protected static void alertTip1(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
builder.setTitle(R.string.network_connection_tips).setMessage(R.string.open_network_connection)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}


protected static void alertTip2(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
builder.setTitle(R.string.network_connection_tips).setMessage(R.string.network_is_not_available)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}


protected static void alertTip3(final Context context, final int posId, final String midpath, final String fjname,
final String filePath) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
builder.setTitle(R.string.download_confirmation).setMessage(R.string.mobile_network_download_confirmation)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
state = true;
download(context, posId, midpath, fjname, filePath);
dialog.dismiss();
}
}).create().show();
}


protected static void alertTip4(final Context context, final int posId, final String midpath, final String fjname,
final String filePath) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
builder.setTitle(R.string.download_confirmation).setMessage("是否下载文件?文件将保存在" + midpath + "文件夹下")
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
state = true;
download(context, posId, midpath, fjname, filePath);
dialog.dismiss();
}
}).create().show();
}


protected static void alertTip5(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
builder.setTitle(R.string.tip).setMessage(R.string.install_software_open)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}


// 判断本地文件是否存在
public static boolean fileIsExists(String strFile) {
try {
File f = new File(strFile);
if (!f.exists()) {
return false;
}


} catch (Exception e) {
return false;
}
return true;
}


@SuppressWarnings("deprecation")
@SuppressLint({ "HandlerLeak", "InflateParams" })
protected static void download(Context context, int posId, final String midpath, final String fjname,
String filePath) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.Dialog2);
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.progress_load, null);
mMessageView = (TextView) view.findViewById(R.id.download_message);
mProgressbar = (ProgressBar) view.findViewById(R.id.download_progress);
builder.setTitle("文件下载").setView(view).setCancelable(false);


File file = new File(midpath);
// 如果SD卡目录不存在创建
try {
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
e.printStackTrace();
}


// 设置progressBar初始化
mProgressbar.setProgress(0);
int threadNum = 5;
final String loadpath = midpath + URLDecoder.decode(fjname);
final DownloadTask task = new DownloadTask(context, URLDecoder.decode(filePath), threadNum, loadpath);
task.start();
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
// task.interrupt();


task.setStop(true);
state = false;


if (loadpath != null) {
GetUriMime.deleteFile(new File(loadpath));
}
}
});
mProgressDialog = builder.create();
mProgressDialog.show();


}


public static class DownloadTask extends Thread {
private Context context;
private String downloadUrl;// 下载链接地址
private int threadNum;// 开启的线程数
private String filePath;// 保存文件路径地址
private int blockSize;// 每一个线程的下载量
private volatile boolean isStop = false;


Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressbar.setProgress(msg.getData().getInt("size"));
float temp = (float) mProgressbar.getProgress() / (float) mProgressbar.getMax();
int progress = (int) (temp * 100);
if (progress == 100) {
mProgressDialog.dismiss();
Toast.makeText(context, "下载完成!", Toast.LENGTH_LONG).show();
state = false;
try {
Intent it = GetUriMime.openFile(new File(filePath));
context.startActivity(it);
} catch (Exception e) {
e.printStackTrace();
// alertTip5(context);
Toast.makeText(context, "请选择打开方式或安装相关软件打开!", Toast.LENGTH_LONG).show();
return;
}
}


mMessageView.setText("下载进度:" + progress + " %");
}
};


public DownloadTask(Context context, String downloadUrl, int threadNum, String fileptah) {
this.context = context;
this.downloadUrl = downloadUrl;
this.threadNum = threadNum;
this.filePath = fileptah;
System.out.println("----Task的构造方法中" + fileptah);
}


public void setStop(boolean stop) {
this.isStop = stop;
}


@Override
public void run() {


FileDownloadThread[] threads = new FileDownloadThread[threadNum];
try {
// while(!Thread.interrupted()){
while (state && !isStop) {
StringBuffer sb = new StringBuffer();
       for (int i = 0; i < downloadUrl.length(); i++) {
           if ((downloadUrl.charAt(i)+"").getBytes().length>1) {
               sb.append(downloadUrl.charAt(i));
           }
       }
       downloadUrl=downloadUrl.replace(sb.toString(), URLEncoder.encode(sb.toString(), "UTF-8").toString());
URL url = new URL(downloadUrl);
URLConnection conn = url.openConnection();
conn.setReadTimeout(4000);
// 读取下载文件总大小
int fileSize = conn.getContentLength();
if (fileSize <= 0) {
System.out.println("读取文件失败");
return;
}
// 设置ProgressBar最大的长度为文件Size
mProgressbar.setMax(fileSize);
// 计算每条线程下载的数据长度
blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum : fileSize / threadNum + 1;
File file = new File(filePath);
for (int i = 0; i < threads.length; i++) {
// 启动线程,分别下载每个线程需要下载的部分
threads[i] = new FileDownloadThread(url, file, blockSize, (i + 1));
threads[i].setName("Thread:" + i);
threads[i].start();
}
boolean isfinished = false;
int downloadedAllSize = 0;
while (!isfinished) {
isfinished = true;
// 当前所有线程下载总量
downloadedAllSize = 0;
for (int i = 0; i < threads.length; i++) {
downloadedAllSize += threads[i].getDownloadLength();
if (!threads[i].isCompleted()) {
isfinished = false;
}
}
// 通知handler去更新视图组件
Message msg = new Message();
msg.getData().putInt("size", downloadedAllSize);
mHandler.sendMessage(msg);
Thread.sleep(500);// 休息0.5秒后再读取下载进度
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}



package com.school.thesis.file;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;


public class FileDownloadThread extends Thread {


private static final String TAG = FileDownloadThread.class.getSimpleName();


/** 当前下载是否完成 */
private boolean isCompleted = false;
/** 当前下载文件长度 */
private int downloadLength = 0;
/** 文件保存路径 */
private File file;
/** 文件下载路径 */
private URL downloadUrl;
/** 当前下载线程ID */
private int threadId;
/** 线程下载数据长度 */
private int blockSize;


/**

* @param url:文件下载地址
* @param file:文件保存路径
* @param blocksize:下载数据长度
* @param threadId:线程ID
*/
public FileDownloadThread(URL downloadUrl, File file, int blocksize, int threadId) {
this.downloadUrl = downloadUrl;
this.file = file;
this.threadId = threadId;
this.blockSize = blocksize;
}


@Override
public void run() {


BufferedInputStream bis = null;
RandomAccessFile raf = null;


try {
URLConnection conn = downloadUrl.openConnection();
conn.setAllowUserInteraction(true);


int startPos = blockSize * (threadId - 1);// 开始位置
int endPos = blockSize * threadId - 1;// 结束位置


// 设置当前线程下载的起点、终点
conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
System.out.println(Thread.currentThread().getName() + "  bytes=" + startPos + "-" + endPos);


byte[] buffer = new byte[1024];
bis = new BufferedInputStream(conn.getInputStream());


raf = new RandomAccessFile(file, "rwd");
raf.seek(startPos);
int len;
while ((len = bis.read(buffer, 0, 1024)) != -1) {
raf.write(buffer, 0, len);
downloadLength += len;
}
isCompleted = true;
Log.d(TAG, "current thread task has finished,all size:" + downloadLength);


} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


/**
* 线程文件是否下载完毕
*/
public boolean isCompleted() {
return isCompleted;
}


/**
* 线程下载文件长度
*/
public int getDownloadLength() {
return downloadLength;
}


}

0 0