1.静态权限 manifest(xml文件未写)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
android:requestLegacyExternalStorage="true"
2.动态权限
boolean isAllGranted = checkPerssionAllGranted(
new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}
);
//查看是否有权限,若有进行下载
if (isAllGranted) {
new Download().execute(IMG_URL);
return;
}
//若没有,请求授权
ActivityCompat.requestPermissions(
DownloadActivity.this,
new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
MY_PERMISSION_CODE
);
private boolean checkPerssionAllGranted(String[] permissions) {
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSION_CODE) {
boolean isAllGranted = true;
for (int grant : grantResults) {
if (grant != PackageManager.PERMISSION_GRANTED) {
isAllGranted = false;
break;
}
}
if (isAllGranted) {
new Download().execute();
} else {
return;
}
}
}
3.自定义内部类继承AsyncTask
public class Download extends AsyncTask<String, Integer, Boolean> {
//开始前 UI线程
@Override
protected void onPreExecute() {
super.onPreExecute();
downloadBtn.setText("开始下载");
txt.setText("");
seekBar.setProgress(0);
}
//下载过程中 子线程
@Override
protected Boolean doInBackground(String... strings) {
if (strings != null && strings.length > 0) {
try {
URL url = new URL(strings[0]);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
int fileLen = conn.getContentLength();
path = Environment.getExternalStorageDirectory()
+ File.separator + FILE_NAME;
File file = new File(path);
if (file.exists()) {
boolean result = file.delete();
if (!result) {
return false;
}
}
OutputStream os = new FileOutputStream(file);
int len = 0;
byte[] b = new byte[1024];
int okLen = 0;
while ((len = in.read(b)) > -1) {
os.write(b, 0, len);
okLen += len;
publishProgress(okLen * 100 / fileLen);
}
in.close();
os.close();
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return false;
}
}
//下载结束 UI线程
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
downloadBtn.setText((aBoolean ? "下载完成" : "下载失败"));
txt.setText( "下载完成" + path );
}
//过程中更新UI 线程
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
seekBar.setProgress(values[0]);
}
}