更新适配Android 7.0 文件访问
/-------------------------------------------/
看到一篇介绍DownloadManger的文章 ,记得以前自己也写过,中午找出来,整理了一下
/**
* 创建下载对象,传入界面的context与下载的url,文件默认保存在/download目录下
*/
new Download(context).execute(url);
package cn.ljt.download;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by jiangtao on 2017/3/13 13:04
* E-mail:[email protected]
*/
public final class Download extends AsyncTask {
private File file;
private Context context;
private String fileName;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
public Download(Context context) {
this.context = context;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(context);
builder.setTicker("下载开始了...")
.setContentTitle("Download")
.setSmallIcon(R.mipmap.ic_launcher);
}
@Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection conn;
BufferedInputStream bis = null;
FileOutputStream fos = null;
try {
url = new URL(params[0]);
Log.i("TAG", url.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int fileLength = conn.getContentLength();
bis = new BufferedInputStream(conn.getInputStream());
fileName = getFileName(params[0]);
builder.setContentTitle(fileName);
String fileDir = Environment.getExternalStorageDirectory().getPath() + "/Download/" + fileName;
file = new File(fileDir);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
if (file.getParentFile().mkdirs()) {
file.createNewFile();
}
}
} else {
return "文件已存在";//可以删除或者忽略,自己处理
}
fos = new FileOutputStream(file);
byte data[] = new byte[4 * 1024];
long total = 0;
int count;
while ((count = bis.read(data)) != -1) {
total += count;
Log.i("TAG", "total:" + total);
publishProgress((int) (total * 100 / fileLength));
fos.write(data, 0, count);
fos.flush();
}
fos.flush();
return "下载成功";
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "网络错误";
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (progress[0] == 100) {
builder.setTicker("下载完成!");
}
builder.setProgress(100, progress[0], false);
builder.setContentText("正在下载..." + progress[0] + "%");
notificationManager.notify(1, builder.build());
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
builder.setContentText(s);
builder.setProgress(0, 0, false);
notificationManager.notify(1, builder.build());
if (fileName.endsWith(".apk")) {
openFile(file);
}
}
public static String getFileName(String url) {
String filename = "";
boolean isOk = false;
// 从UrlConnection中获取文件名称
try {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
if (conn == null) {
return null;
}
Map> hf = conn.getHeaderFields();
if (hf == null) {
return null;
}
Set key = hf.keySet();
if (key == null) {
return null;
}
for (String stringKey : key) {
List values = hf.get(stringKey);
for (String value : values) {
String result;
try {
result = new String(value.getBytes("ISO-8859-1"), "GBK");
int location = result.indexOf("filename");
if (location >= 0) {
result = result.substring(location + "filename".length());
filename = result.substring(result.indexOf("=") + 1);
isOk = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}// ISO-8859-1 UTF-8 gb2312
}
if (isOk) {
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 从路径中获取
if (filename == null || "".equals(filename)) {
filename = url.substring(url.lastIndexOf("/") + 1);
}
return filename;
}
private void openFile(File file) {
if (file != null) {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
Uri apkUri = FileProvider.getUriForFile(context, "com.ljt.download.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
}
}
定义自己的fileprovider:
首先在AndroidManifest.xml文件中注册一个provider
创建filepaths.xml
放在xml文件夹下,如果res目录下没有就自己创建一个