I have an app that downloads about 6k photos from a server and store them in a folder configured y my app settings, I keep the files hidden from the gallery with .nomedia file and they are only visible in my app gallery, but when I leave my device charging about 5000 photos disappears, and there are only about 920 left in the folder, I totally don't know why files are being deleted.
here is my download file code
DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request;
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
Uri downloadUri = Uri.parse(fileURL);
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( getAbsolutePath(path), fileName ));
request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI )
.setTitle(fileName)
.setAllowedOverRoaming(false)
.setVisibleInDownloadsUi(false)
.setDestinationInExternalPublicDir( getPath(path), fileName );
downloadManager.enqueue(request);
Add System.currenttimeMillisecond() to fileUrl to make sure that your file name not to be duplicate .
This weekend i tested with 3 different devices and 2 different download methods, in the one with download manager the files dissapeared, so if someone have the same problem here's how I am donwloading the files:
public static boolean downloadFile(Activity activity, String fileURL) {
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
try {
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( activity.getExternalFilesDir(""), fileName ));
URL u = new URL(fileURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
File file = new File(activity.getExternalFilesDir(""), fileName);
DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return false; // swallow a 404
} catch (IOException e) {
return false; // swallow a 404
}
return true;
}
Related
I'm using the DownloadManager to download the apk from url. Download completes, I get the onReceive in my BroadcastReceiver for DownloadManager.ACTION_DOWNLOAD_COMPLETE.
Some Coding: I download the apk file from an url to the download directory.
DownloadManager.Request r = new DownloadManager.Request(mUri);
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myapp.apk");
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
SharedPreferences mSharedPref = activity.getSharedPreferences("package", Context.MODE_PRIVATE);
mSharedPref.edit().putLong("downloadID", dm.enqueue(r)).commit();
onReceive
File apkFile = new File(Environment.DIRECTORY_DOWNLOADS + "myapp.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(promptInstall);
Problems:
The file is there, I want to execute it but I package-installer is not shown
Even though I see the file in my phones download folder, I if I want to install it there is no package-installer to choose
I'm not sure if I do the file and pathing stuff right..
I get an parsing error from android when I try to open the file
Someone got an idea please?
I recently had to do something like this, hope it helps:
EDIT: Couple of notes,
apkurl is a string to the download location.
Make the byte buffer big enough for your response
try {
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
// Create a file on the external storage under download
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
HttpGet m_httpGet = null;
HttpResponse m_httpResponse = null;
// Create a http client with the parameters
HttpClient m_httpClient = setupHttpClient();
String result = null;
try {
// Create a get object
m_httpGet = new HttpGet(apkurl);
// Execute the html request
m_httpResponse = m_httpClient.execute(m_httpGet);
HttpEntity entity = m_httpResponse.getEntity();
// See if we get a response
if (entity != null) {
InputStream instream = entity.getContent();
byte[] buffer = new byte[1024];
// Write out the file
int len1 = 0;
while ((len1 = instream.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
instream.close();// till here, it works fine - .apk is download to my sdcard in download file
}
} catch (ConnectTimeoutException cte) {
// Toast.makeText(MainApplication.m_context, "Connection Timeout", Toast.LENGTH_SHORT).show();
return false;
} catch (Exception e) {
return false;
} finally {
m_httpClient.getConnectionManager().closeExpiredConnections();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApplication.getApp().getApplicationContext().startActivity(intent);
// System.exit(0);
} catch (IOException e) {
Debug.ERROR(CLASSNAME, METHODNAME, "Failed to update new apk");
return false;
} catch (Exception e1) {
Debug.ERROR(CLASSNAME, METHODNAME, "Failed to update new apk");
return false;
}
return true;
Make sure you have the android.permission.INSTALL_PACKAGES permission declared in your AndroidManifest.xml.
Then get your APK path:
File apkFile = new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk");
Now run the Intent:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
All downloads you do with the device...
To clarify what I mean with "Downloads" here is a screenshot. This is the standart download folder for Android 5 on Nexus 4. When I click on the apk inside this, I dont get the prompt to install a .apk. Instead the HTML-Viewer or other useless stuff shows up to choose...
One possible mistake could be the DownloadManager.. maybe he "tags" the downloaded file wrong so its not interpreted as an apk file, I don't know... but I call
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myapp.apk")), "application/vnd.android.package-archive");
I'm trying to save the path of a downloaded file that was saved to the SD card, but I'm running into troubles when I try to retrieve it. When I try to convert it to a Bitmap, it says the file can't be found, even though it is on the SD card.
File example : /storage/emulated/0/_1404876264453.jpeg
Here's the code that I use to download a photo, and store it to the SD card (returns the URL of where it is saved on the device):
private String downloadProfile(String url)
{
String imageUrl = null;
try
{
String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
String mimeType = getMimeType(url);
String fileExtension = "."+mimeType.replace("image/", "");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
long millis=System.currentTimeMillis();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "_"+millis);
FileOutputStream f = new FileOutputStream(outputFile);
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read()) > 0){
f.write(buffer, 0, len1);
}
imageUrl = outputFile.getAbsolutePath()+fileExtension;
f.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imageUrl;
}
After downloading it, I insert the above URL into a SQLite database; it stores fine. I used Astro file manager to check if the file was there, and it was.
Here's the code in my BaseAdapter that takes the above file url and attemps to convert it into a Bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
String profilePath = result_pos.get("profile_url"); // this just returns the example url
Bitmap bitmap = BitmapFactory.decodeFile(profilePath, options);
imageView.setImageBitmap(bitmap);
LogCat:
07-08 23:35:17.660: E/BitmapFactory(25463): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/_1404876264453.jpeg: open failed: ENOENT (No such file or directory)
check this link.i hope its useful to you.
reference link
1)create your own folder and save image name in proper way.
2)save image path in sqlite database
3)retrieve same path for get images.
I have to develop an application in which I am downloading a video file from an URL
After downloading, I am playing it through an Intent.
But every time I am getting the same message: "You can't play this video."
download code:
protected String doInBackground(String... params) {
File file = new File(getFilesDir(), generateFileName(params[0]));
try {
URL u = new URL(params[0]);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
method for playing the video:
public void playVideo(String fileName) {
Uri data = Uri.parse(new File(fileName).getAbsolutePath());
Log.i("DATA: ",""+data);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(data, "video/mp4");
startActivity(intent);
}
This code worked for me when supplying extra infomation to an intent. It's not video data, but image data, but I believe the concept should be the same (I could be wrong, since I didn't try this on video).
File file = new File(getExternalFilesDir(null), "image.png");
String uriPath = "file://"+file.getPath();
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(uriPath));
Note that the image I am supplying to the intent is downloaded before this of course and then saved in the directory of the app (this I get with getExternalFilesDir(null)). Then the image is passed to an intent as a stream.
If this does not help you then maybe check if there are any apps installed that can handle your type of video (is it mp4 or what is the format?)
In my app I am using a webview to navigate through to a site, automatically fill in a web form using javascript then submit to obtain a link to a CSV export file.
The link looks like this: XYZ.com/TEST/index/getexport?id=130.
I'd like to download the file this URL points to, then when complete read it into a local database but I'm having trouble downloading the linked file.
If I simply try to open the URL in webview I get an error from the webpage telling me no such file exists.
If I use the Download Manager to download it myself, the source code is downloaded as an html file, not the associated .csv file.
I can open the url with an ACTION_VIEW intent and a browser (chrome) downloads the correct file, but this way I have no notification of when the download completes.
Any ideas of how to download my .CSV file?
To download a file from webview use this :
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Hope this helps.
You could resort to manually downloading the file from the url using an AsyncTask.
Here id the background part:
#Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
Perhaps it would make sense to refactor it so that the file is returned. Then you get the file as an argument in onPostExecute as soon as the download is complete.
how can i download audio file from server by url and save it to sdcard.
i am using the code below:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
the above code is not downloading audio file.
if use any permission in menifest file plz tell me.. (i have used internet permission)
please help
thanks..
you must also add
android.permission.WRITE_EXTERNAL_STORAGE
permission if you wish to write data to sd card.
also post your logcat output , if you are getting any IOExceptions.
Your example does not specify a request method and some mimetypes and stuff.
Here you will find a list of mimetypes http://www.webmaster-toolkit.com/mime-types.shtml
Find the mimetypes relevant to you and add it to the mimetypes specified below in the code.
Oh and btw, the below is normal Java code. You'll have to replace the bit that stores the file on the sdcard. dont have an emulator or phone to test that part at the moment
Also see the docs for storage permissions on sd here: http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Then call,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
EDIT:
Bad coder me.
Wrap that input InputStream in a BufferedInputStream. No need to specify buffersizes ect.
Defaults are good.