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"/>
Related
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
I tried to delete the image file from the gallery, but it won't. Image files are output normally, and sharing functions are done. It can't write and delete in my App. Files are deleted from the default app.
I tried to delete it use File class and ContentResolver. but file has not been deleted.
Android targetSdkVersion is 26 and compileSdkVersion is 28.
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I get SDcard path from getSDcardPath()
public String getSDcardPath(Context context) {
File[] storage = ContextCompat.getExternalFileDirs(context, null);
if(storage.length > 1 && storage[0] != null && storage[1] != null)
return storage[1].toString();
else
return "";
}
File Class code Used
public void useFileClass() {
File mFile = new File("file Parent + file NAME");
if (mFile.exists()) {
mFile.delete();
}
}
ContentResolver code Used
public void useContentResolver(Context context, File mFile) {
ContentResolver contentResolver = context.getContentResolver();
Uri mUri = getUri(context, mFile);
contentResolver.delete(mUri, null, null);
}
public Uri getUri(Context context, File mFile) {
Uri mUri;
mUri = FileProvider.getUriForFile(context, "MyApplication", mFile);
return mUri;
}
share code
public void shareImage() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, getUri(this, mFile));
startActivity(Intent.createChooser(shareIntent, "Share image too..."));
}
You need request Permission before access into storage. Try this:
private static final int MY_WRITE_STORAGE_PERMISSION_CODE = 200;
private void checkPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_WRITE_STORAGE_PERMISSION_CODE);
} else {
// Todo (Add, Delete, Edit, ...)
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_WRITE_STORAGE_PERMISSION_CODE)
{
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Todo (Add, Delete, Edit, ...)
} else {
// Permission Deny
}
}
}
Hope this help you.
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.
DIRECTORY_DOWNLOADS, nameOfFile)
To open it
File file = new File(Environment.
DIRECTORY_DOWNLOADS, nameOfFile);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
But I am getting an error message that file cannot be accessed.Check the location
Try using read permission:
android.permission.READ_EXTERNAL_STORAGE
Here is a working solution. Note: Dont use DownloadManager.COLUMN_LOCAL_FILENAME as it is deprecated in API 24. Use DownloadManager.COLUMN_LOCAL_URI instead.
Create fields downlaod manager and a long variable to hold the download id.
DownloadManager dm;
long downloadId;
String pendingDownloadUrl = url;
fial int storagePermissionRequestCode = 101;
Create download manager
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
register the broadcast receiver for download complete
BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));
if (c != null) {
c.moveToFirst();
try {
String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File mFile = new File(Uri.parse(fileUri).getPath());
String fileName = mFile.getAbsolutePath();
openFile(fileName);
}catch (Exception e){
Log.e("error", "Could not open the downloaded file");
}
}
}
};
//register boradcast for download complete
registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Start the download
Start the download
private void onDownloadStart(String url) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
downloadFile(url);
} else {
pendingDownloadUrl = url;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionRequestCode);
} }
//Download file using download manager
private void downlaodFile(String url){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
String filename = URLUtil.guessFileName(url, null, null);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename);
downloadId = dm.enqueue(request);//save download id for later reference }
//Permission status
#Override public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == storagePermissionRequestCode){
boolean canDownload = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
canDownload = false;
break;
}
}
if(canDownload){
downlaodFile(pendingDownloadUrl);
}
} }
Open the downloaded file
private void openFile(String file) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file)), "application/pdf");//this is for pdf file. Use appropreate mime type
startActivity(i);
} catch (Exception e) {
Toast.makeText(this,"No pdf viewing application detected. File saved in download folder",Toast.LENGTH_SHORT).show();
}
}
Now try download your file by calling downladFile(String url); method
Try like this...
protected void openFile(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"MIME-TYPE");
startActivity(install);
}
here is my Logcat message
java.lang.SecurityException: No permission to write to /storage/0F0D-0A0C/Download/notice.php: Neither user 10082 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
I am trying to download a file from the external storage, I gave the path of the file, My downloading file code is
TextView downloadlink = (TextView)findViewById(R.id.downloadlink);
downloadlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myHTTPUrl = "http://192.168.122.1/notice.php";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("File download");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myHTTPUrl,null, MimeTypeMap.getFileExtensionFromUrl(myHTTPUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
manifest file permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
please check your app is currently running in MarshMallow or higher, then need to check dangerous permissions on runtime. Please include it on MainActivity. and you can call it from anywhere.
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
android.support.v7.app.AlertDialog.Builder alertBuilder = new android.support.v7.app.AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("To download a file it is necessary to allow required permission");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
android.support.v7.app.AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
here check permission is already granted or not, if app is currently running in marshmallow or higher then check it as. here i changeed your code like this.
TextView downloadlink = (TextView)findViewById(R.id.downloadlink);
downloadlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkPermission()){
downloadFile();
}
}
});
your downloading code is put in a method as
downloadFile(){
String myHTTPUrl = "http://192.168.122.1/notice.php";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("File download");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myHTTPUrl,null, MimeTypeMap.getFileExtensionFromUrl(myHTTPUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
if already granted permission then download code will work otherwise it then call to the override method 'onRequestPermissionsResult()'
here below give that override method
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
downloadFile();
} else {
//code for deny
}
break;
}
}
please try this, then it will work
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();
}
}