currently I'm trying to download a File with the DownloadManager but that doesn't work, the download starts but there is no File inside the Download Folder after downloading.
Thats my Code:
private void downloadAddon() {
try{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("download");
request.setDescription("apk downloading");
// request.setAllowedOverRoaming(false);
request.setDestinationUri(Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) , "mod.mcpack")));
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(request);
//Just for testing
if (downloadComplete(downloadID)) {
Toast.makeText(this, "Download Status: Completed", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Download Status: Error", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
//Not required, there is no error that crashes the app
Toast.makeText(this, "Error catched: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private boolean downloadComplete(long downloadId){
DownloadManager dMgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
if(c.moveToFirst()){
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(status == DownloadManager.STATUS_SUCCESSFUL){
return true; //Download completed, celebrate
}else{
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.d(getPackageName(), "Download not correct, status [" + status + "] reason [" + reason + "]");
return false;
}
}
return false;
}
The Log says: Download not correct, status [1] reason [0]
Did something changed since Android 11 except the new storage rules?
I found an solution on Stackoverflow (Can't find the link anymore)
private boolean downloadTask(String url) throws Exception {
if (!url.startsWith("http")) {
return false;
}
String name = "temp.mcaddon";
try {
File file = new File(Environment.getExternalStorageDirectory(), "Download");
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
File result = new File(file.getAbsolutePath() + File.separator + name);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationUri(Uri.fromFile(result));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (downloadManager != null) {
downloadManager.enqueue(request);
}
//mToast(mContext, "Starting download...");
MediaScannerConnection.scanFile(DetailsActivity.this, new String[]{result.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
Log.e(">>>>>", e.toString());
//mToast(this, e.toString());
return false;
}
return true;
}
This should work for Android 11
Use this Function it save File in Download folder :
private boolean downloadTask(String url , String name) throws Exception {
try {
File file = new File(Environment.getExternalStorageDirectory(), "Download");
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
File result = new File(file.getAbsolutePath() + File.separator + name);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationUri(Uri.fromFile(result));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setAllowedOverRoaming(false).setTitle(name);//for mp3 title
request.setDescription("Something useful. No, really.");
if (downloadManager != null) {
downloadManager.enqueue(request);
}
//mToast(mContext, "Starting download...");
MediaScannerConnection.scanFile(MainActivity.this, new String[]{result.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("tag >>>>", "on Downlaod check it");
}
});
} catch (Exception e) {
Log.i("tag >>>> ", e.toString());
return false;
}
return true;
}
But in Manifest add some lines.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
>
Add this line in OnCreate :
//check permission
if (Build.VERSION.SDK_INT >= 23) {
Log.i("log ", "if in Build.VERSION.SDK_INT>=23");
checkper(); //<-- this is a function
} else {
Log.i("log ", " else else in Build.VERSION.SDK_INT>=23");
}
This is checkper() Function:
private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private void checkper() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else {
Log.i("log", "else in checkper()");
//your code
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED
&& grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[3] == PackageManager.PERMISSION_GRANTED) {
Log.i("log", "if in onRequestPermissionsResult()");
//dar seri aval har do ra dasti ok kardim amad inja
//your code
} else {
Log.i("log", "else in onRequestPermissionsResult()");
// yeki taiiid kardi
}
}
}//switch
}//onRequestPermissionsResult
Related
I want to show whatsapp statuses in my app.
Till now I have done following:
public final String getStatusPath(boolean z) {
if (Build.VERSION.SDK_INT < 30) {
if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
} else if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
}
}
private ArrayList<WhatStatusData> getStatusList() {
ArrayList<WhatStatusData> arrayList = new ArrayList<>();
File[] listFiles = new File(FileConstants.INSTANCE.getStatusPath(isBusiness)).listFiles();
int i = 0;
if (listFiles != null) {
if (listFiles.length == 0) {
Arrays.sort(listFiles);
}
int length = listFiles.length;
while (i < length) {
File file = listFiles[i];
i++;
String absolutePath = file.getAbsolutePath();
Uri fromFile = Uri.fromFile(file);
String name = file.getName();
if (!name.equals(".nomedia")) {
arrayList.add(new WhatStatusData(absolutePath, fromFile, name));
}
}
}
return arrayList;
}
In manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
But I am not getting data in android 11.In other versions code is working properly.
Got the solution
There are two possibility for getting hidden files access in android 11
give MANAGE_EXTERNAL_STORAGE permission as said by #Subarata Talukder
give particular folder access permission using storage manager as explained below (without using MANAGE_EXTERNAL_STORAGE permission)
Here I am showing how to access whatsapp statuses programmatically
//give permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//give run time permissions
static final int REQUEST_PERMISSION_KEY = 1;
int REQUEST_ACTION_OPEN_DOCUMENT_TREE = 101;
SharedPreferences sharedPreferences;
check if run time permissions are given or not on button click
if(sharedPreferences.getString("WATREE","").equals("")){
if(checkAndRequestPermissions()){
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
}
}else{
callActivity();
}
private boolean checkAndRequestPermissions() {
int writePerm = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPerm = ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (writePerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if(readPerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(GBV_StartActivity.this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_PERMISSION_KEY);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_KEY) {
try {
Map<String, Integer> permsLogin = new HashMap<>();
// Initialize the map with both permissions
permsLogin.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
permsLogin.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
permsLogin.put(permissions[i], grantResults[i]);
// Check for both permissions
if (permsLogin.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& permsLogin.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
// process the normal flow
//else any one or both the permissions are not granted
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialogOK((dialog, which) -> {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(getApplicationContext(), "Go to settings and enable permissions.", Toast.LENGTH_LONG)
.show();
finish();
//proceed with logic by disabling the related features or quit the app.
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void showDialogOK(DialogInterface.OnClickListener okListener) {
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(GBV_StartActivity.this);
alertDialogBuilder.setMessage("You need to allow access to the permissions.")
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener);
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
public void callActivity(){
startActivity(new Intent(GBV_StartActivity.this, MainActivity.class));
}
private String getWhatsupFolder() {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if(new File(newBusinessPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp.w4b%2FWhatsApp Business%2FMedia%2F.Statuses";
}else if(new File(newPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses";
}else if(new File(oldBusinessPath).exists()){
finalPath = "WhatsApp Business%2FMedia%2F.Statuses";
}else {
finalPath = "WhatsApp%2FMedia%2F.Statuses";
}
return finalPath;
}
#RequiresApi(Build.VERSION_CODES.Q)
private void askPermission() {
StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
Intent intent = storageManager.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
String targetDirectory = getWhatsupFolder(); // add your directory to be selected by the user
Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");
String scheme = uri.toString();
scheme = scheme.replace("/root/", "/document/");
scheme += "%3A"+targetDirectory;
uri = Uri.parse(scheme);
Log.w("TAG", "askPermission: uri::"+uri );
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
startActivityForResult(intent, REQUEST_ACTION_OPEN_DOCUMENT_TREE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == this.REQUEST_ACTION_OPEN_DOCUMENT_TREE && resultCode == -1) {
Uri data = intent.getData();
try {
getContentResolver().takePersistableUriPermission(data, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor2 = sharedPreferences.edit();
editor2.putString("WATREE", data.toString());
editor2.apply();
callActivity();
}
}
now after giving all permissions try to get images or videos from storage like below:
if (SDK_INT >= Build.VERSION_CODES.Q) {
DocumentFile[] allFiles = getFromSdcard();
if (allFiles != null) {
for(int i = 0 ; i <allFiles.length ; i++){
if (!allFiles[i].getUri().toString().contains(".nomedia")) {
Log.e("path:",allFiles[i].getUri().toString());
//add data in your arraylist
}
}
}
}else {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if (!new File(oldPath).exists()) {
if (!new File(oldBusinessPath).exists()) {
if (!new File(newPath).exists()) {
if (!new File(newBusinessPath).exists()) {
finalPath = oldPath;
} else {
finalPath = newBusinessPath;
}
} else {
finalPath = newPath;
}
} else {
finalPath = oldBusinessPath;
}
} else {
finalPath = oldPath;
}
File file2 = new File(finalPath);
if (file2.exists()) {
File[] listFiles = file2.listFiles();
if (listFiles != null) {
for (int i = 0; i < listFiles.length; i++) {
Log.e("path:",listFiles[i].getPath()+"");
//add data in your arraylist
}
}
}
}
public DocumentFile[] getFromSdcard() {
DocumentFile fromTreeUri = DocumentFile.fromTreeUri(getContext(), Uri.parse(sharedPreferences.getString("WATREE","")));
if (fromTreeUri == null || !fromTreeUri.exists() || !fromTreeUri.isDirectory() || !fromTreeUri.canRead() || !fromTreeUri.canWrite()) {
return null;
}
return fromTreeUri.listFiles();
}
Hi in the below code When I am trying click it is showing you don't have read and access permission.But in the manifest file I has given those two permission.Both read and write permission are not triggering with my below code.Both the permission I am calling haspermission evry time failing
Can any one help me where I did the mistake.
java:
private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
String modality_name = opportunity.getModality();
if (modality_name.equals("LCS")||modality_name.equals("Ultrasound")||modality_name.equals("DI")) {
// Toast.makeText(mContext, modality_name, Toast.LENGTH_LONG).show();
holder.pdf.setVisibility(View.GONE);
}else {
holder.pdf.setVisibility(View.VISIBLE);
holder.pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!hasPermissions(mContext, PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(mContext, "You don't have read access !", Toast.LENGTH_LONG);
t.show();
} else {
File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // -> filename = maven.pdf
String url_path = opportunity.getPdf_link();
///Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
//Log.d("file_name", file_name);
File pdfFile = new File(d, file_name);
Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());
if(pdfFile!=null) {
Uri path = GenericFileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", pdfFile);
Log.v(TAG, "view() Method path " + url_path);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
mContext.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(mContext, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
// }
}
Log.v(TAG, "view() Method completed ");
// download(v);
//request(v);
}
download(v);
// request(v);
}
public void request(View v) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, 112);
}
public void download(View v) {
Log.v(TAG, "download() Method invoked ");
if (!hasPermissions(mContext, PERMISSIONS)) {
Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
Toast t = Toast.makeText(mContext, "You don't have write access !", Toast.LENGTH_LONG);
t.show();
} else {
Log.v(TAG, "download() Method HAVE PERMISSIONS ");
String url_path = opportunity.getPdf_link();
Log.d("url_path", url_path);
String file_name = url_path.substring(url_path.lastIndexOf('/') + 1);
Log.d("file_name", file_name);
new DownloadFile().execute(url_path, file_name);
}
Log.v(TAG, "download() Method completed ");
}
});
}
}
// public DragListener getDragInstance() {
// if (mlistener != null) {
// return new DragListener(mlistener);
// } else {
// Log.e("Route Adapter: ", "Initialize listener first!");
// return null;
// }
// }
private class DownloadFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
Log.v(TAG, "doInBackground() Method invoked ");
String fileUrl = strings[0];
Log.d("fileurl",fileUrl);
String fileName = strings[1]; // -> maven.pdf
Log.d("fileName",fileName);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File pdfFile = new File(folder, fileName);
Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsolutePath());
Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsoluteFile());
try {
pdfFile.createNewFile();
Log.v(TAG, "doInBackground() file created" + pdfFile);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground() error" + e.getMessage());
Log.e(TAG, "doInBackground() error" + e.getStackTrace());
}
FileDownloader.downloadFile(fileUrl, pdfFile);
Log.v(TAG, "doInBackground() file download completed");
return null;
}
}
First of all, WRITE permission grants you both READ/WRITE access, so you don't need to send a request for both
Check if permission is granted by this method, no need for all of those API checks:
private boolean isPermissionGranted(String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
If permission is not granted first before everything else just request the permission:
requestPermissions(new String[Manifest.permission.WRITE_EXTERNAL_STORAGE], 123);
Check if permission is granted and then continue your work:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 123 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Do your work
}
else {
//Permission is not granted do what you want
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
In your code:
inside holder.pdf.setOnClickListener()'s onCLick()
if (!isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
requestPermissions(new String[Manifest.permission.WRITE_EXTERNAL_STORAGE], 123);
} else {
//Do your job
}
I use this code to download pdf
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("story" + name);
request.setDescription("download " + name);
request.setDestinationInExternalFilesDir(R_arabic.this,"/Rewayat/", name+".pdf");
Long reference = downloadManager.enqueue(request);
it work good and pdf downloaded in app folder in android/data
and i use this code to open pdf
File file = new File ("/data/com.kamal.ahmed.rewaya/files/Rewayat/"+name+".pdf");
Intent target = new Intent (Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createchosser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
}
but when i try to open it i don't get right pdf file and get error file
i think path not right please help me
To download the document to external storage
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(document_url));
// This puts the downloaded document in the Download directory
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my_document.pdf");
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);
Code to open
public void OpenPDF() {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + "my_document.pdf");
if (!file.isDirectory())
file.mkdir();
Intent pdfIntent = new Intent("com.adobe.reader");
pdfIntent.setType("application/pdf");
pdfIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
pdfIntent.setDataAndType(uri, "application/pdf");
startActivity(pdfIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
You need permission to write external storage, check how to get permission in new android version (you have to request permission through code, not only in the manifest)
To request permission from the user in order to write external storage, place these two methods in your main activity
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("PERMISSIONS", "Permission is granted");
return true;
} else {
Log.v("PERMISSIONS","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("PERMISSIONS","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v("PERMISSIONS","Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
and inside onCreate, call the method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
isStoragePermissionGranted();
Inside manifest.xml before <application> tag put these two permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
i try to copy a sqlite database from file in my external storage this worked fine in android version ( 4 and 5 ) but doesn't work in android 6 (marshmallow) why ?? please help , As required, in its manifest, the following permissions are requested :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
here is my code :
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(Main2ActivityAdmin.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(Main2ActivityAdmin.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main2ActivityAdmin.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
} else {
Toast.makeText(Main2ActivityAdmin.this, "permission erreur", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Main2ActivityAdmin.this, "ok", Toast.LENGTH_LONG).show();
}
private boolean copyDatabase(Context context) {
try {
//InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
File sdcard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(sdcard, "sample.sqlite");
InputStream inputStream = null;
inputStream = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
Try this to put the permission
Also change WRITE_EXTERNAL_STORAGE to READ_EXTERNAL_STORAGE for Read permission
public class MyActivity extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (CheckPermission(MyActivity .this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// you have permission go ahead
} else {
// you do not have permission go request runtime permissions
RequestPermission(MyDevIDS.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead
} else {
// you do not have permission show toast.
}
return;
}
}
}
public void RequestPermission(MyActivity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(MyActivity context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
I call the service below to handle the download of a given URL. As you can see in the snippet below I want to assign the current downloading file size to total_size.
However (using the Eclipse debugger) its value remains -1 even though the file is getting properly downloaded. Suggestions?
public class DownloadManagerService extends IntentService {
public final static String ACTION_DOWNLOAD_STARTED= "com.youzik.app.intent.action.ACTION_DOWNLOAD_STARTED";
public static final String DATA = "download";
public static final String URL = "url";
public DownloadManagerService() {
super("DownloadManagerService");
}
#Override
protected void onHandleIntent(Intent service) {
Request request = new Request(Uri.parse(service.getStringExtra(URL)));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(request);
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(downloadId));
if (!cursor.moveToFirst()) {
Log.v("DownloadManagerService", "download list is empty");
return;
}
Download dl = new Download();
dl.setId(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
dl.setName(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)));
dl.setUrl(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
int total_size = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
cursor.close();
}
}
Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
Cursor c = YOUR_DM.query(q);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// process download
title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
// get other required data by changing the constant passed to getColumnIndex
}
}
Make sure you have given required user-permission in Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
Also , give run time permission on android marshmallow and above version.
if (Build.VERSION.SDK_INT >= 23) {
//do your check here
askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXST);
askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXST);
}
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
}
} else {
// Toast.makeText(getActivity(), "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
Log.d("Permission :: ","is already granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(ActivityCompat.checkSelfPermission(getActivity(), permissions[0]) == PackageManager.PERMISSION_GRANTED){
switch (requestCode) {
//Location
case 1:
// askForGPS();
break;
//Call
case 2:
break;
//Write external Storage
case 3:
Log.d("Permission :: ","Write external Storage");
break;
//Read External Storage
case 4:
/* Intent imageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(imageIntent, 11);*/
Log.d("Permission :: ","Read External Storage");
break;
//Camera
case 5:
break;
case 6:
break;
}
Toast.makeText(getActivity(), "Permission granted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
}