I have an app that downloads mp3 files from a url. The downloading works, and I get a file in the downloads folder. However, when I click on it, it says "Can't open file." When I use getExternalStorageDirectory(), it also isn't retrieving the file or getting any of the information. Is there something wrong with how I'm implementing the download function? Or is there more I have to do with the download manager? I also tried using addCompletedDownload(), but it would just add a "0" file.
private long DownloadData (Uri uri) {
long downloadReference;
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
// Create request for android download manager
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle("Downloading Song");
//Setting description of request
request.setDescription("Downloading Song from URL");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, "DownloadSong.mp3");
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
return downloadReference;
}
The code that you had shown to us is absolutely not enough to understand the problem. Here is an example code for downloading using DownloadManager.
According to the symptoms described, I think, you haven't finished the download operation or the writing operation correctly. You should check if the download is finished and the file is written and closed. The fact that a file appeared, means that the downloading and writing had started, but not that they finished correctly.
Using DownloadManager terms, it should be completed. Look How to notify after all download completed from Android download manager about that
Related
I want to create a folder for my app to put audio files into. I want it to be in the same location where the DCIM folder lives. So when I run the emulator and go to Files -> Internal Storage, I want to be able to see the folder here (similar to how Snapchat creates its folder here). Is this even possible? I tried doing the below but got an error.
Code:
var path = Environment.getExternalStorageDirectory() // this is /storage/emulated/0
val testappDir = File(path?.absolutePath, "/testapp/")
testappDir.mkdirs() //mkdirs creates any missing parent directories, mkkdir does not
if (testappDir.createNewFile()) {
println("File created: " + testappDir.name)
} else {
println("File already exists.")
}
Error:
java.io.IOException: Operation not permitted
You are calling a path for an external storage with Environment.getExternalStorageDirectory().
The Exception java.io.IOException: Operation not permitted means that you don't have the permissions to read or write the external storage.
You have to add the permission to the Android Manifest and the at Runtime you have to request the permission from the user. More information about this can be found here: https://developer.android.com/training/permissions/requesting
When you want to read and write the App Internal Storage you can found more information here: https://developer.android.com/training/data-storage/app-specific
[Screenshot displaying the downloaded file in a window[][1]1i am not able to access my downloaded file which i opened in a new small window popup using selenium java and also i am not able to find it in downloads folder.
When i click on a download button-->the file gets downloaded with an icon of word in a new small popup browser window-->but it does not move into the downloads folder. Testcase passes but i am not able to validate.In that browser window i am not able to find any elements....only .... tags are displayed.. While doing it in manual way i am able to view it in downloads folder.
Kindly advise me what should be done.
you are coding in java language,
so, use method exists() which will return boolean value.
You must know your Downloaded file name along with exact download path,
String FileName = "YOUR_FILE_NAME";
File tmpDir = new File("C:\Users\a.k\Downloads\"+FileName);
if(tmpDir.exists())
System.out.println("File Downloaded");
System.out.println("File Not Downloaded");
Im using a download manager which downloads a file into a new folder on the phone storage. Here is the code im using:
DownloadManager.Request downloadSample = new DownloadManager.Request(Uri.parse(urlSample));
downloadSample.allowScanningByMediaScanner();
downloadSample.setDestinationInExternalPublicDir("/Samples/"+previewName, "sample.ttf");
downloadSample.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(downloadSample);
This works perfectly fine on many of the devices Ive tested on, but a few devices force close the app with the following error in the log:
E/AndroidRuntime(29918): java.lang.IllegalStateException: Unable to create directory: /storage/sdcard0/Samples/Helvetica
E/AndroidRuntime(29918): at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:507)
Its annoying that it works fine on some but not at all on other devices. Does anyone know why this is happening?
The documentation for setDestinationInExternalPublicDir(String dirType, String subPath) says that dirType can take only specified values.
Here dirType can only be the android defined directories for example:
Environment.DIRECTORY_DOWNLOADS
etc.
you can find all the possible values of dirType at: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
So the proper way to use this method is:
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath)
Also note that this will make the folder in Downloads folder on phone storage. Download manager will not allow you to make a folder in the default directory of phone storage.
This will not give you IllegalStateException for creating directory.
[UPDATE]
I uninstalled and then installed again the application on the test device, and it started working fine.
I'm implementing APK Expansion file support (but no XAPK ZIP library support).
The documentation implies that if a required APK Expansion file is missing (e.g. it got deleted from the obb folder), my application will re-download it. This doesn't happen for me; my app keeps saying NO_DOWNLOAD_REQUIRED. It seems that the Google Play Downloader Library gets null for the download info from its SQLite database. Note that I haven't updated the draft APK and Expansion file on Google Play - they are still the first version. Moreover, the versionCode of the APK uploaded to Google Play is also identical with the one on the test device.
In details:
There was an APK Expansion file in the correct folder (obb). I used it for testing purposes before I actually started implementing the downloader functionality.
When the Downloader implementation (based on Google Play Downloader Library) was finished, I changed the size of the above obb file to make it invalid for my app. Therefore, this makes my app call the startDownloadIfNeeded() method.
First, I ran my implementation without any files on Google Play. The response was, as I expected: "Download failed because the resources could not be found"
Then I uploaded my 40MB APK and a 4 MB expansion file to Google Play (for testing purposes). Note that this 4 MB expansion file is not the invalid one which was left in the obb folder. When I ran my implementation, the response came after 1.5 seconds: "Download complete".
This was strange, because my internet connection is not so fast to download 4 MB. Indeed, the obb folder (the folder for APK Expansion files) still contained the invalid expansion file that I initially put there manually. That is, nothing was downloaded!
I deleted the invalid file, i.e. the obb folder is now empty, but still no download starts, and Downloader Library says NO_DOWNLOAD_REQUIRED. (I checked its internal implementation: when it queries an SQLite database for download info, it gets null after the query.)
I just read on SO somewhere that the APK Expansion files uploaded to Google Play require a few hours to take effect. In my case, I tested my implementation immediately after upload. But it must have noticed that there are files on Google Play, because instead of "resources could not be found", it gave a different message ("Download completed"). Too bad that it didn't actually download anything; and since then, it doesn't even try to (it keeps returning NO_DOWNLOAD_REQUIRED).
What am I missing?
Shouldn't the Downloader Library notice if an APK Expansion file gets deleted? Its implementation seems to deal with this, but only if the SQLite database query returns non-null for downloadable files.
The relevant part of internal implementation of Google Play Downloader Library (the last comment is mine):
int status = NO_DOWNLOAD_REQUIRED;
// the database automatically reads the metadata for version code
// and download status when the instance is created
DownloadsDB db = DownloadsDB.getDB(context);
// we need to update the LVL check and get a successful status to
// proceed
if (isLVLCheckRequired(db, pi)) {
status = LVL_CHECK_REQUIRED;
}
// we don't have to update LVL. do we still have a download to start?
if (db.mStatus == 0) {
DownloadInfo[] infos = db.getDownloads();
if (null != infos) {
for (DownloadInfo info : infos) {
if (!Helpers.doesFileExist(context, info.mFileName, info.mTotalBytes, true)) {
status = DOWNLOAD_REQUIRED;
db.updateStatus(-1);
break;
}
}
}
/// <----- This is when infos==null, in this case result will be NO_DOWNLOAD_REQUIRED
} else {
status = DOWNLOAD_REQUIRED;
}
If you encounter the same issue, uninstall the application, and then install it again. (Don't let Eclipse reinstall it in the usual way. Uninstall it completely from the device, manually.)
I have a problem with Android internal storage. I have created folder in package root folder calling getDir() and with MODE_WORLD_WRITEABLE because I want camera app to write captured image in this folder. Anyway, I can see that captured image is inside that folder with DDMS.
Problem is that I cannot read that file.
I tried to read file with this code:
File file = context.getDir("images", Context.MODE_WORLD_READABLE);
File image = new File(file, "image.jpeg");
if (image.canRead())
Log.w("read", "can read");
else
Log.w("read", "can't read");
And in LogCat there is only second message (can't read).
I have also tried to create FileInputStream with file name but I receive FileNotFoundException.
Can somebody tell me what I'm doing wrong here?
Thanks in advance
EDIT:
Reading file is correct but only problem is that when cam app is saving image to specified location, permission set by cam app to image file are -rwxrwx---. After changing permissions with
adb (chmod 777 image.jpeg)
I was able to read image. Interesting thing is that cam app is writing images files to sdcard with ----rwxr-x.
Is there any way to change file permission in runtime?
Why not put it in the default photo directory?
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
( From: http://developer.android.com/reference/android/os/Environment.html )
See also a more complete example invoking the camera app: http://developer.android.com/training/camera/photobasics.html
Referencing to Android developers you should use openFileOutput() and openFileInput() to work on the internal storage... you are not allowed / not able to make dirs there. Android does it itself.. Those data will be cleared when your application will be deleted.