download manager class crashes when try to download multiple files? - android

i am trying to download images from the web when my app is connected to the internet through this code
public void downloadimages(String url,String filename)
{
String ur1=url,v1=filename;
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse(ur1);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
request.setDescription("Android Data download using DownloadManager.");
request.setDestinationInExternalFilesDir(getApplicationContext(),Environment.DIRECTORY_DOWNLOADS,v1 + ".jpg");
downloadManager.enqueue(request);
}
when i run the app first time downloads happen but the app crashes after that the app did'nt open i am checking for the dowloaded files also:
String path = "/mnt/sdcard/Android/data/com.example.webdata/files/Download/" + extra2 + ".jpg";
tt1.append(path);
File f = new File(path);
if(f.exists())
{
//Toast.makeText(getApplicationContext(), "File already exists....",
// Toast.LENGTH_SHORT).show();
}
else
{
downloadimages(extra,extra2);
}
if the file has been downloaded previously it should not be dowloaded next time ,but i my app crashes and i don't know why any help guys.........
this is my logcat output:-
02-21 18:00:41.547: E/AndroidRuntime(23964): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webdata/com.example.webdata.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 1088, size is 1088

Can you show us the code MainActivity class, because it seems that the error comes from this class.
then the error is a IndexOutOfBoundsException, so have you tried with less image eg 10 or 20? and run later when the first 10 are recovered?

Related

Rescan older files with mediascannerconnection in local storage. files get not updated on windows

My android-application writes a bunch of csv-files and jpg-files to the internal storage of the device. I am using MediaScannerConnection.scanFile() to make the files accessable from my windows-system without rebooting the android-device.
private void scanFiles() {
File targetDirectory = new File(Environment.getExternalStorageDirectory(), "DIR_OF_MY_APP");
if (targetDirectory.exists()) {
List<File> filesToScan = getFiles(targetDirectory);
List<String> filePathsToScan = new ArrayList<>();
for(File file : filesToScan) {
filePathsToScan.add(file.getPath());
}
MediaScannerConnection.scanFile(this, filePathsToScan.toArray(new String[0]), null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.d("OK", "Path: " + path);
Log.d("OK", "Uri : " + uri);
}
});
}
}
In my Logcat i can see every file is getting scanned. The new ones and the old ones.
My problem is when my app is adding new lines to an existing csv-file and the file is getting scanned, The new lines do not appear in the csv-file when its opend from my pc. How can i fix this problem?
I already tried to rename all the files from filename to tmp_filename, rescann all the files and rename them back from tmp_filename to filename and rescann them again. After this, i have can see the oldfilename-file and the tmp_oldfilename-file on my windows-computer. The tmp_oldfilename-file can not be opend (Unknown error on [memory-adress]). The oldfilename-file shows the not updated csv-file.
I also tried to use a intent to scan the files, since some questions on so say its going to update them:
for(File file : filesToScan) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
Log.d("OK", "File: " + file.getName() + " scanned...");
}
here i can see the files getting scanned too, but they do not show up updated on my windows-computer.
Okay the only solution i came up with, is to set the usb-mode to load-only (this must be done by hand from the user) before performing the MediaScannerConnection.scanFile();. After this is done, the user can set the usb-mode back to mtp and than the csv-files will show up with the new added lines.
This is a really bad workarround, but still better than rebooting the device. If someone has an better solution, pls share.

Android partial download http

In my application I download media from server via HTTP connection. While downloading if connection is break anyhow (say, no n/w, permission revoke), File get downloaded partially.
Earlier we are deleting the file and downloading it from the scratch.
Now, the requirement is changed. I have to continue from where I left (like in WhatsApp).
So what I am doing is checking the file existence and if file exist skip the stream. Please find the below code snip.
InputStream is = con.getInputStream();
File file = new File(targetPath);
boolean fileExist = file.exists();
if (fileExist) {
long skippedBytes = is.skip(file.length());
}
// opens an output stream to save into file
OutputStream os = new FileOutputStream(targetPath, fileExist);
Its working merely in respect of skipping but actually not working.
Say, file (video) length is 20 sec and in first attempt I downloaded up to 6 sec and rest subsequently. But when I play it just play till 6 sec then after throw the usual Video playback error.
File file = new File(targetPath);
if (file.exists()) {
con.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
} else {
con.setRequestProperty("Range", "bytes=" + 0 + "-");
}

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.

Download .apk with DownloadManager

Hi I'm facing a little problem here. For updates of my App (that isn't available in Play Store) I download it via DownloadManager to the Donwload directoryof the device. The .apk file is on a ftp server.
After downloading I pop up a dialog if the user wants to install the update (not malicious or something, no root needed). Everything works fine except the user cancels this dialog and wants to "manually" install the apk by clicking on the downloaded file in the Download diretory. If so, I don't get the Package-Installer to choose to open the file. On some devices "HTML Viewer" is opened without a question. If I download the apk via QR-Code (direct link) from browser everything is fine, so I guess it's a failure coming with the DownloadManager.
How can I download a file from ftp with DownloadManager, so that it is recognized as .apk and I can install it from the download region?
Here's the code for downloading and installIntent:
String url = "http://www.test.xx/myApp.apk";
Uri mUri = Uri.parse(url);
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);
dm.enqueue(r);
And on download receive:
#Override
public void onReceive(Context context, Intent intent) {
try {
Bundle extras = intent.getExtras();
long myDownloadID = DashboardActivity.this.mSharedPref.getLong(PreferenceIdentifier.DOWNLOAD_APK.toString(), 0);
mSharedPref.edit().remove(PreferenceIdentifier.DOWNLOAD_APK.toString()).commit();
long downloadCompletedId = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
DownloadManager.Query q = new DownloadManager.Query();
if (myDownloadID == downloadCompletedId) {
q.setFilterById(downloadCompletedId);
DownloadManager mManager = (DownloadManager) MyActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor c = mManager.query(q);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setDataAndType(
Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
"application/vnd.android.package-archive");
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(promptInstall);
}
}
c.close();
}
As you can see I did
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
"application/vnd.android.package-archive");
I thought that would set the file type to apk so it is handles as one.
Hope I made my point clear, can anyone help?
Yeah, well... kinda stupid..
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
"application/vnd.android.package-archive");
just affects the way android want to open the file..
DownloadManager.Request r = new DownloadManager.Request(mUri);
r.setMimeType("application/vnd.android.package-archive");
will do it...

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;
}

Categories

Resources