我正在后台线程中从互联网下载一个文件。我声明了权限,也在运行时请求了权限,但我仍然得到了这个例外。我搜索了很多关于它的信息,得到的只是请求运行时许可,我照做了这是我的点击功能
String[] permission ={Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityCompat.requestPermissions(MainActivity.this, permission, 1);
}
} else
{
new DownloadFileFromURL().execute(url,name);
}
这是我的异步任务
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Resources res =getResources();
Drawable drawable = res.getDrawable(R.drawable.circular);
mProgress.setProgress(0); // Main Progress
mProgress.setSecondaryProgress(100); // Secondary Progress
mProgress.setMax(100); // Maximum Progress
mProgress.setProgressDrawable(drawable);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
String name= f_url[1];
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ name+".apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(final String... progress) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (pStatus < 100) {
pStatus = Integer.parseInt(progress[0]);
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mProgress.setProgress(pStatus);
tv.setText(pStatus + "%");
}
});
}
}
}).start();
}
@Override
protected void onPostExecute(String file_url) {
}
}
我认为还有一些其他问题,我已经声明在清单中读取external和写入external存储太
您应该更换
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+ name+".apk");
把这个写在你的代码中
OutputStream output = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), name+".apk"));