1、DownloadUtils类
public class DownloadUtils {
private static ProgressDialog mDialog = null;
/**
* 显示下载进度条
*
* @param aty
*/
public static void showProgressDialog(Activity aty) {
if (mDialog == null) {
mDialog = new ProgressDialog(aty);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
mDialog.setMessage(aty.getResources().getString(R.string.msg_downloading));
mDialog.setIndeterminate(false);//设置进度条是否为不明确
mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
mDialog.setCanceledOnTouchOutside(false);
mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mDialog = null;
}
});
mDialog.show();
}
}
/**
* 关闭下载进度条
*/
public static void closeProgressDialog() {
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
/**
* 获取打开文档意图
*
* @param file
* @return
*/
public static Intent getFileIntent(Activity activity, File file) {
Uri uri = Uri.fromFile(file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//通过FileProvider创建一个content类型的Uri
uri = FileProvider.getUriForFile(activity, "com.invt.fileprovider", file);
}
String type = getMIMEType(file);
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, type);
return intent;
}
/**
* 下载文件到sdcard
*
* @param fileName
* @param input
*/
public static void writeToSDCard(String fileName, InputStream input) {
// 判断是否挂载了SD卡
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String directory = getDownloadPath();
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(directory, fileName);
if(file.exists()){
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[2048];
int j = 0;
while ((j = input.read(b)) != -1) {
fos.write(b, 0, j);
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取下载路径
*
* @return
*/
public static String getDownloadPath() {
String compName = AppString.getCompanyName();
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + compName + "/Doc/";
}
/**
* 获取文档类型,并打开
*
* @param f
* @return
*/
private static String getMIMEType(File f) {
String type = "";
String fName = f.getName();
/* 取得扩展名 */
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
/* 依扩展名的类型决定MimeType */
if (end.equals("pdf")) {
type = "application/pdf";
} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
type = "audio/*";
} else if (end.equals("3gp") || end.equals("mp4")) {
type = "video/*";
} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
end.equals("jpeg") || end.equals("bmp")) {
type = "image/*";
} else if (end.equals("apk")) {
type = "application/vnd.android.package-archive";
} else if (end.equals("pptx") || end.equals("ppt")) {
type = "application/vnd.ms-powerpoint";
} else if (end.equals("docx") || end.equals("doc")) {
type = "application/vnd.ms-word";
} else if (end.equals("xlsx") || end.equals("xls")) {
type = "application/vnd.ms-excel";
} else {
//如果无法直接打开,就跳出软件列表给用户选择
type = "*/*";
}
return type;
}
}
2、activity中调用
DownloaderTask task = new DownloaderTask();
task.execute(mDownloadUrl);
/**
* 下载使用说明
*/
private void downloadInstructions() {
//判断是否挂载SD卡
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
ToastUtils.showShortToast(this, R.string.msg_storage_nosdcard);
return;
}
//获取下载的文件名
String mDownloadUrl = "http://iot.ss.com/upload/66001-00568-SSP_V1.0.pdf";
String fileName = mDownloadUrl.substring(mDownloadUrl.lastIndexOf("/") + 1);
//获取文件下载路径
String directory = DownloadUtils.getDownloadPath();
File dir = new File(directory);
if (dir.exists()) {
File file = new File(directory, fileName);
if (file.exists()) {
//直接打开
Intent intent = DownloadUtils.getFileIntent(this, file);
startActivity(intent);
return;
}
}
DownloaderTask task = new DownloaderTask();
task.execute(mDownloadUrl);
}
/**
* 任务类
*/
private class DownloaderTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String url = params[0];
String fileName = url.substring(url.lastIndexOf("/") + 1);
try {
fileName = URLDecoder.decode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MyLogger.i("download", "fileName=" + fileName);
try {
URL resUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) resUrl.openConnection();
conn.connect();
InputStream input = conn.getInputStream();
DownloadUtils.writeToSDCard(fileName, input);
input.close();
return fileName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
DownloadUtils.closeProgressDialog();
if (result == null) {
ToastUtils.showShortToast(StartActivity.this, R.string.msg_downloaderror);
return;
}
ToastUtils.showShortToast(StartActivity.this, R.string.msg_downloadsuccess);
String dir = DownloadUtils.getDownloadPath();
File file = new File(dir, result);
Intent intent = DownloadUtils.getFileIntent(StartActivity.this, file);
//自动打开
startActivity(intent);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
DownloadUtils.showProgressDialog(StartActivity.this);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
完!!!