public class HelpOpenFileUtils {
/**
* 读写权限
*/
protected static final int WRITE_PERMISSION = 20003;
protected static final String[] WRITEPERMISSION = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final String TAG = "TAG_HelpOpenFileUtils";
public static void nativeDownloadFile(final Activity context, String url, final File downloadFile) {
OkHttpClient httpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).get().build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG_文件下载", "onFailure");
ToastUtil.showToast("下载文件失败!!!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
int code = response.code();
if (code >= 500) {
Log.e("TAG_文件下载", "code=" + code);
ToastUtil.showToast("下载文件失败!!!");
} else if (code >= 200 && code < 300) {
InputStream is = response.body().byteStream();
byte[] buf = new byte[8 * 1024];
int len = 0;
long sum = 0;
OutputStream fos = null;
try {
Log.e("TAG_文件下载", "downloadFile=" + downloadFile);
fos = new FileOutputStream(downloadFile);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
}
fos.flush();
// 通知图库更新
LocalBroadcastManager.getInstance(MyApplication.getInstance()).sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(downloadFile.getAbsolutePath())));
ToastUtil.showToast("图片保存成功!");
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG_文件下载", "IOException=");
ToastUtil.showToast("下载文件失败!!!");
} finally {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
}
}
}
});
}
//文件下载
public static File createFile(FragmentActivity context, String url) {
if (url.indexOf(".") != -1) {
String type = url.substring(url.lastIndexOf(".") + 1);
Log.e(TAG, "createFile===type=" + type);
PermissionsChecker mChecker = new PermissionsChecker(context);
if (mChecker.lacksPermissions(WRITEPERMISSION)) {
// 请求权限
PermissionsActivity.startActivityForResult((Activity) context, WRITE_PERMISSION, WRITEPERMISSION);
} else {
// 全部权限都已获取
Log.e(TAG, "createFile===url=" + url);
if (TextUtils.isEmpty(url)) {
Log.e(TAG, "downloadFile: url下载地址为空!!!");
return null;
}
try {
int indexOf = url.indexOf("file_name=");
if (indexOf != -1) {
url = url.substring(0, indexOf + 10) + URLEncoder.encode(url.substring(indexOf + 10), "UTF-8");
Log.e(TAG, "createFile===url=" + url);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
File downloadFile = createDefaultTimeFile(type);
if (null == downloadFile) {
Log.e(TAG, "downloadFile: 文件创建失败!!!");
return null;
}
return downloadFile;
}
}
return null;
}
//文件下载
public static void downloadFile(Activity context, String url) {
if (url.indexOf(".") != -1) {
int dian = url.lastIndexOf(".") + 1;
String type = "";
if (url.indexOf("/?") != -1) {
int i = url.lastIndexOf("/?");
type = url.substring(dian, i);
} else if (url.indexOf("?") != -1) {
int i = url.lastIndexOf("?");
type = url.substring(dian, i);
} else {
type = url.substring(dian);
}
downloadFile(context, url, type);
}
}
public static void downloadFile(Activity context, String url, String type) {
Log.e(TAG, "type=" + type);
PermissionsChecker mChecker = new PermissionsChecker(context);
if (mChecker.lacksPermissions(WRITEPERMISSION)) {
// 请求权限
PermissionsActivity.startActivityForResult((Activity) context, WRITE_PERMISSION, WRITEPERMISSION);
} else {
// 全部权限都已获取
Log.e(TAG, "url=" + url);
if (TextUtils.isEmpty(url)) {
Log.e(TAG, "downloadFile: url下载地址为空!!!");
return;
}
try {
int indexOf = url.indexOf("file_name=");
if (indexOf != -1) {
url = url.substring(0, indexOf + 10) + URLEncoder.encode(url.substring(indexOf + 10), "UTF-8");
Log.e(TAG, "url=" + url);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
File downloadFile = createDefaultTimeFile(type);
if (null == downloadFile) {
Log.e(TAG, "downloadFile: 文件创建失败!!!");
return;
}
nativeDownloadFile(context, url, downloadFile);
}
}
public static String dateFormat(long times, String dateformat) {
if (times <= 0)
return "";
SimpleDateFormat dateformat1 = new SimpleDateFormat(dateformat);
String dateStr = dateformat1.format(times);
return dateStr;
}
private static File createDefaultTimeFile(String type) {
String fileName = dateFormat(System.currentTimeMillis(), "yyyyMMddHHmmss");
String mDownloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "download";
File downloadFile = new File(mDownloadDir, fileName + "." + type);
return createFile(downloadFile);
}
public static File createFile(File file) {
Log.e(TAG, "file=" + file.toString());
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
Log.e(TAG, "createFile: 目录创建失败!!!");
return null;
}
}
try {
file = new File(file.toString());
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return file;
}
public static String dateFormat(long times, String dateformat) {
if (times <= 0)
return "";
SimpleDateFormat dateformat1 = new SimpleDateFormat(dateformat);
String dateStr = dateformat1.format(times);
return dateStr;
}
}
这是下载文件工具类,使用时直接HelpOpenFileUtils.downloadFile(this,url);即可
附带一个实用工具类ToastUtil
public class ToastUtil {
private static Toast toast;
private static Handler mHandler = new Handler(Looper.getMainLooper());
public static void showToast(String text) {
showToast(text, Toast.LENGTH_SHORT);
}
public static void showToast(int text) {
showToast(BaseApp.getAppContext().getString(text), Toast.LENGTH_SHORT);
}
private static void showToast(final String text, final int duration) {
if (Looper.myLooper() == Looper.getMainLooper()) {
show(text, duration);
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
show(text, duration);
}
});
}
}
private static void show(String text, int duration) {
if (toast != null) {
toast.cancel();
}
Log.e("TAG_Toast","text="+text);
if (!TextUtils.isEmpty(text)){
toast = Toast.makeText(BaseApp.getAppContext(),text, duration);
toast.show();
}
}
}
|