所以我试图通过创建一个文件夹然后存储它来将 PDF 文件存储在用户的 android 设备上。我正在使用 getExternalStorageDir() 但这在 API29 下已被弃用。问题是 Andriod 指南说要选择退出范围存储我必须把它放在 list 文件中
<manifest xmlns:android="http://schemas.android.com/apk/res/android
....
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:requestLegacyExternalStorage="true"
....
</application>
这不再有效了。我可以在装有 andriod M 的设备上下载,但在最近的 9/10 设备上无法下载。
public class FinalActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
private static final int WRITE_REQUEST_CODE = 300;
private static final String TAG = MainActivity.class.getSimpleName();
private String url;
SessionManagement sessionManagement;
String userID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final);
sessionManagement = new SessionManagement(this);
HashMap<String, String> user = sessionManagement.getUserDetail();
userID = user.get(sessionManagement.ID);
TextView submit = findViewById(R.id.download);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (EasyPermissions.hasPermissions(FinalActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//Get the URL entered
url = F.url1 + userID + "/FPO.pdf";
new DownloadFile().execute(url.replaceAll(" ", "%20"));
} else {
//If permission is not present request for the same.
EasyPermissions.requestPermissions(FinalActivity.this, "This app needs access to your file storage so that it can write files.", WRITE_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, FinalActivity.this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
//Download the file once permission is granted
url = F.url1 + userID + "/FPO.pdf";
new DownloadFile().execute(url.replaceAll(" ", "%20"));
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
Log.d(TAG, "Permission has been denied");
}
private class DownloadFile extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog;
private String fileName;
private String folder;
private boolean isDownloaded;
@Override
protected void onPreExecute() {
super.onPreExecute();
this.progressDialog = new ProgressDialog(FinalActivity.this);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
//Extract file name from URL
fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());
//External directory path to save fileb n
folder = Environment.getExternalStorageDirectory() + File.separator + "FPO/";
//Create LSK folder if it does not exist
File directory = new File(folder);
if (!directory.exists()) {
directory.mkdirs();
}
// Output stream to write file
OutputStream output = new FileOutputStream(folder + fileName.replaceAll("%20", " "));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
Log.d(TAG, "Progress: " + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "Downloaded at: " + folder + fileName.replaceAll("%20", " ");
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
Log.i("error123", e.getMessage());
return e.getMessage();
}
// return "Something went wrong";
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String message) {
// dismiss the dialog after the file was downloaded
this.progressDialog.dismiss();
Intent intent = new Intent(FinalActivity.this, Welcome_screen1.class);
startActivity(intent);
// Display File path after downloading
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
}
最佳答案
“使用 getExternalFilesDir()、getExternalCacheDir() 或 getExternalMediaDirs()(上下文方法)而不是 Environment.getExternalStorageDirectory()。”
检查这个;
关于android - 尝试使用 getExternalStorageDir() 函数在用户 android 设备上存储 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65626114/