Can download, can't read - android

I'm using this to download a file:
String url = "https://File To Download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("My File To Download");
request.setTitle("Downloading");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, context.getString(R.string.dloded_latest_numbers));
// get download service and enqueue file
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Which all works great. Puts the file in the standard Downloads directory which I confirm is there.
Then I try to read the file into a BufferedReader like so:
File latestNumbersFile;
latestNumbersFile = new File(Environment.DIRECTORY_DOWNLOADS, getString(R.string.dloded_latest_numbers));
TextView displayArray = (TextView) findViewById(R.id.currentNumbers);
String tmp = latestNumbersFile.toString(); // Converts type (File) to string type
displayArray.setText(tmp);
BufferedReader buffedReader = new BufferedReader(new FileReader(latestNumbersFile));
Then display the file location in a TextView, which works and gives the dir /Download/File To Download
Note the leading "/" not sure if that's important...
My question is:
Using File(Environment.DIRECTORY_DOWNLOADS, getString(R.string.dloded_latest_numbers) allows me to download to a dir I expect the file to be in, but using the exact same reference to read the file from I get java.io.FileNotFoundException open failed: ENOENT (No such file or directory)
Can anyone help??

ok you have only asked for android.permission.WRITE_EXTERNAL_STORAGE permission but you dont have the permission to read from the SD Card. you also need to add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Related

Open a Downloaded file (pdf) from the Downloads folder in the INTERNAL STORAGE

I have downloaded a file (133465.pdf) using the Download manager and now it is stored in the Downloads folder of the mobile phone (Internal storage).
How should i try and retrieve the downloaded pdf from the Downloads folder?
I am using the below code to try and retrieve the pdf from the downloads folder but i am getting an error on the Toast, saying "Cannot display PDF (133465.pdf cannot be opened)" .
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "133465.pdf";
Log.i("Fragmentadapter1", file);
File videoFile2Play = new File(file);
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "application/pdf");
imageContext.startActivity(i);
I don't know if i am using the right file location to access the file.
Any help or suggestion will be appreciated.
If you are working for Lollopop and Below: You don't have to ask the user for permission on run-time. The manifest Permissions will do.
If you are working for Marshmellow and up: You have to ask the user for permission on run-time and act according to the users output.
Remember: You still have to give the Permissions on the Manifest too.
To Download a PDF on users Downloads folder :
DownloadManager downloadmanager;
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
downloadmanager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
String url = hardcode + bb ;
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(bb )
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
bb)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Log.i("Download1", String.valueOf(request));
downloadmanager.enqueue(request);
Reference
To View the Downloaded PDF from the Downloads folder of the Users device:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator +
"YOUR FILE NAME");
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
}
Note: Make sure u get the permission granted before downloading the Viewing the PDF file for Marshmellow and UP.

How to store files generated from app in "Downloads" folder of Android?

I am generating an excelsheet in my app which when generated should be automatically saved in the "Downloads" folder of any android device where all the downloads are typically saved.
I have the following which saves the file under "My Files" folder -
File file = new File(context.getExternalFilesDir(null), fileName);
resulting in -
W/FileUtils﹕ Writing file/storage/emulated/0/Android/data/com.mobileapp/files/temp.xls
I rather want to save the generated file automatically in the "Downloads" folder when the excel sheet is generated.
Update # 1: Please see the snapshot here. What I want is the one circled in red and what you suggested gets stored in the one circled blue (/storage/emulated/0/download) if that makes sense. Please advise on how I can save a file in the one circled red i.e., "Downloads" folder which is different from /storage/emulated/0/Download under "MyFiles"
Use this to get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
And don't forget to set this permission in your manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Now from your question edit I think understand better what you want.
Files shown on the Downloads menu from the one circled in red are ones that are actually downloaded via the DownloadManager, though the previos steps I gave you will save files in your downloads folder but they will not show in this menu because they weren't downloaded. However to make this work, you have to initiate a download of your file so it can show here.
Here is an example of how you can start a download:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
request.allowScanningByMediaScanner();// if you want to be available from media players
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);
This method is used to download from a Uri and i have not used it with a local file.
If your file is not from the internet you could try saving a temporary copy and get the Uri of the file for this value.
Just use the DownloadManager to download your generated file like this:
File dir = new File("//sdcard//Download//");
File file = new File(dir, fileName);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
downloadManager.addCompletedDownload(file.getName(), file.getName(), true, "text/plain",file.getAbsolutePath(),file.length(),true);
The "text/plain" is the mime type you pass so it will know which applications can run the downloadedfile. That did it for me.
I used the following code to get this to work in my Xamarin Droid project with C#:
// Suppose this is your local file
var file = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
var fileName = "myFile.pdf";
// Determine where to save your file
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, fileName);
// Create and save your file to the Android device
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, file);
// Notify the user about the completed "download"
var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
downloadManager.AddCompletedDownload(fileName, "myDescription", true, "application/pdf", filePath, File.ReadAllBytes(filePath).Length, true);
Now your local file is "downloaded" to your Android device, the user gets a notification, and a reference to the file is being added to the downloads folder. Make sure, though, to ask the user for permission before you write to the file system, otherwise an 'access denied' exception will be thrown.
For API 29 and above
According to documentation, it is required to use Storage Access Framework for Other types of shareable content, including downloaded files.
System file picker should be used to save file to External storage directory.
Copy file to external storage example:
// use system file picker Intent to select destination directory
private fun selectExternalStorageFolder(fileName: String) {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
putExtra(Intent.EXTRA_TITLE, name)
}
startActivityForResult(intent, FILE_PICKER_REQUEST)
}
// receive Uri for selected directory
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
FILE_PICKER_REQUEST -> data?.data?.let { destinationUri ->
copyFileToExternalStorage(destinationUri)
}
}
}
// use ContentResolver to write file by Uri
private fun copyFileToExternalStorage(destination: Uri) {
val yourFile: File = ...
try {
val outputStream = contentResolver.openOutputStream(destination) ?: return
outputStream.write(yourFile.readBytes())
outputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
As Oluwatumbi have answered this question correctly but First you need to check for permission is granted for WRITE_EXTERNAL_STORAGE by following code:
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Request for permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}else{
Uri uri = Uri.parse(yourUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
request.allowScanningByMediaScanner();// if you want to be available from media players
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);
}
This is running code download files using DownloadManager for Xamarin android api version 29
public bool DownloadFileByDownloadManager(string imageURL)
{
try
{
string file_ext = Path.GetExtension(imageURL);
string file_name = "MyschoolAttachment_" + DateTime.Now.ToString("yyyy MM dd hh mm ss").Replace(" ", "") + file_ext;
var path = global::Android.OS.Environment.DirectoryDownloads;
Android.Net.Uri uri = Android.Net.Uri.Parse(imageURL);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.SetDestinationInExternalPublicDir(path, file_name);
request.SetTitle(file_name);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted); // to notify when download is complete
// Notify the user about the completed "download"
var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
var d_id = downloadManager.Enqueue(request);
return true;
}
catch (Exception ex)
{
UserDialogs.Instance.Alert("Error in download attachment.", "Error", "OK");
System.Diagnostics.Debug.WriteLine("Error !" + ex.ToString());
return false;
}
}
WORKING ON API 29 AND 30
To get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Set this permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add requestLegacyExternalStorage to your application tag in AndroidManifest.xml (for API 29):
<application
...
android:requestLegacyExternalStorage="true">

How I can download video in my application like we download or install apk file on google play?

I want to download video from URL in background like we install apk file in background from Google play. I want to show downloading indicator on notification bar same like it showing while we download or install apk file. if any suggestion or idea then suggest me how I can achieve this task in my project.
You can prefer android DownLoadManager. somehow want to do like this in your activity
String mUrl="your video url";
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(mUrl));
request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, your_fileName);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
request.setAllowedOverRoaming(false);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
manager.enqueue(request);
setNotificationVisibility() -> show download notification in notification bar(window) with download progress also.
below are three methods where you can choose destination for your downloaded file path.
1. setDestinationInExternalFilesDir(Context context, String dirType, String subPath)
Set the local destination for the downloaded file to a path within the application's external files directory (as returned by getExternalFilesDir(String).
2. setDestinationInExternalPublicDir(String dirType, String subPath)
Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).
3. setDestinationUri(Uri uri)
Set the local destination for the downloaded file.
Use Download Manager,
private void for_call_download() {
File folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdirs();
}
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(APK_URL));
request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);
request.setTitle(SessionName);
request.setDescription("" + SessionDesc);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(false);
request.setMimeType("application/cn.trinea.download.file");
downloadId = downloadManager.enqueue(request);
} catch (IllegalStateException i) {
showAlert(context, "Sorry Some Problem");
i.printStackTrace();
}
updateView();
status_download = true;
}

Downloading .cer file from Webview

I am wondering since 2 days but not be able to fix it.
I have a URL opened inside on WebView.
there is one Button in website which to download a .cer file .
My problem is when i click on that Button it starts to download file and notified me in Notification Bar.
I am trying below code to do this:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(sourceURL));
// appears the same in Notification bar while downloading
request.setTitle("Downloading");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
//DownloadManager.Request request = new DownloadManager.Request(source);
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// Use the same file name for the destination
File destinationFile = new File(directory, "/Download/test.cer");
if (destinationFile.exists()) {
destinationFile.delete();
}
request.setDestinationUri(Uri.fromFile(destinationFile));
// Add it to the manager
referencepath = manager.enqueue(request);
the same is happening with default browser of Device but i am able to downloading file when
i open the url in firefox browser.
i have also added permissions
<!-- Permission so that application can access Internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission so that application can write on device storage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file.
please help me.
Hi finally I succeeded to download .cer file.
The code which worked for me is as:
String sourceURL = url;
String directoryPath = directoryPath;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(sourceURL);
try {
/**
* getting Session Id from URL which is in Webview
*/
String sessionId = CookieManager.getInstance().getCookie(
sourceURL.toString());
if (sessionId != null)
httpPost.addHeader("Cookie", sessionId);
HttpResponse execute = client.execute(httpPost);
String certResponseBody = EntityUtils.toString(execute
.getEntity());
and I got my .cer file as a string in certResponseBody which I saved as a .cer file in device storage.
Cheers....

How to save downloaded file on sd card from download manager programmatically on android

In my application i have download(Image) feature which is used to download file from urls. The download happen should be shown in notification bar so that i used Download Manager class to download file. This is working fine but the downloaded image does not stored no where in the sdcard.
i have referred the url for the download manager.
my requirement is i need to save the download image to sdcard with notification bar indication. What to modify on the code to get save image on sdcard on the above link
i have some doubts regards the code in the above link is Can i use the same code to download audio or video file?
please help me.
Edited question:
I have tried
filepath = Environment.getExternalStorageDirectory().getPath()+"/download/cm.png";
Uri destinationUri = Uri.parse(filepath);
request.setDestinationUri(destinationUri);
before the preference manger on the button click. but i could not get the file on sdcard.
This is what i used.
Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setDescription("Downloading a file");
long id = downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("File Downloading...")
.setDescription("Image File Download")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "cm.png"));
In the code you refer to, the file is opened at the end. At this point, you can consider copying it to the SDCard.
Otherwise (better) use http://developer.android.com/reference/android/app/DownloadManager.Request.html setDestinationUri(android.net.Uri) to specify where you want to download the file.
downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Toast.makeText(context, "Downloading...", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("---- url here ------");
request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("---- title here ------");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl("---- url here ------");
request.setMimeType(mimeType);
request.setDescription("---- descripation here ------");
if("---- titlehere ------" != null){
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "---- title here ------");
}
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadmanager.enqueue(request);

Categories

Resources