Downloads the same file twice? - android

Hi i've been looking through various parts of my code to try and find out whats happening but can't seem to figure it out. The following code is supposed to be downloading two files one called "clientraw" and one called "clientrawextra" but for some reason when i look in the directory there are 2 versions of each file "clientraw...1..." "clientrawextra...1..."
Therefore it seems like it's downloading the files multiple times and i have no idea why??
Thanks in advance!
distance dis = new distance();
dis.findURL(value);
String url = dis.findURL(value);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// 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.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientraw.txt");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
/////////////////////////////////////////////////////
distance disextra = new distance();
disextra.findextra(value);
String urlextra = disextra.findextra(value);
DownloadManager.Request requestextra = new DownloadManager.Request(Uri.parse(urlextra));
// 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) {
requestextra.allowScanningByMediaScanner();
}
requestextra.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientrawextra.txt");
manager.enqueue(requestextra);
mDownload = new DownLoadComplte();
registerReceiver(mDownload, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
And the broadcast receiver...
private class DownLoadComplte extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent myIntent = new Intent(splash.this, MainActivity.class);
myIntent.putExtra("key", value); //Optional parameters
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//unregisterReceiver(mDownload);
splash.this.startActivity(myIntent);
}
}
}

So if anyone has the same issue, apparently this is an ongoing and as of yet unresolved issue with the Download manager. I have used a little bit of a work around which you might want to use if your flow is similar to mine. Basically every time that the user opens the app two files are automatically downloaded to the SD card which overwrites the two files previously downloaded. So all i did was add a couple of extra functions to delete the duplicates...
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() +
"/Download/", client);
Log.d("file path", String.valueOf(file));
if(file.exists())
{
boolean flag = file.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra = Environment.getExternalStorageDirectory();
File fileextra = new File(sdCardextra.getAbsolutePath() +
"/Download/", clientextra);
boolean exist = fileextra.exists();
Log.d("the file exists = ", String.valueOf(exist));
if(fileextra.exists())
{
boolean flag = fileextra.delete();
Log.d("file", "file deleted " + flag);
}
File sdCard2 = Environment.getExternalStorageDirectory();
File file2 = new File(sdCard2.getAbsolutePath() +
"/Download/", "clientraw-1.txt");
Log.d("file path", String.valueOf(file2));
if(file2.exists())
{
boolean flag = file2.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra3 = Environment.getExternalStorageDirectory();
File fileextra3 = new File(sdCardextra3.getAbsolutePath() +
"/Download/", "clientrawextra-1.txt");
boolean exists = fileextra3.exists();
Log.d("the file exists = ", String.valueOf(exists));
if(fileextra3.exists())
{
boolean flag = fileextra3.delete();
Log.d("file", "file deleted " + flag);
}

Related

Can't play mp3 file from internal storage into media player

I am downloading mp3 file from this url using DownloadManager. Here is my code.
// Downloading file from internet and save to internal storage.
private void downloadFromOnline() {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = null;
request = new DownloadManager.Request(Uri.parse("https://alquran.technobdapis.com/quranallaudio/arabic_with_bangla/arbn_001.mp3"));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Downloading...");
request.setDescription("Downloading...arbn_001.mp3");
request.setVisibleInDownloadsUi(true);
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
// Internal storage file path to save the downloaded file
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
if (!myDataPath.exists())
myDataPath.mkdir();
request.setDestinationInExternalFilesDir(getApplicationContext(), myDataPath.getPath() + "/arabic_with_bangla", "arbn_001.mp3");
long refid = downloadManager.enqueue(request);
id = refid;
}
I have tried to play the downloaded file in media player using this code. But unfortunately targetFile.exists() returns false although file exists in that path. Here is the code -
public BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
File targetFile = new File(myDataPath.getPath() + "/arabic_with_bangla/" +"arbn_001.mp3");
Log.d("FileExists", targetFile.exists() + " ");
// Downloaded file path
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
// Although target file exists in device It's targetFile.exists() returning false
// TODO: This is the main problem.
if(targetFile.exists()){
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(MainActivity.this, Uri.parse(targetFile.getParent()));
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}else{
// File Not Exists
Log.d("FileExists", targetFile.exists() + " ");
}
}
};
File exists in my device.

Temporary creating bitmaps in Android then deleting them

So I am working on a project where if a manager registers a user he gets an email with a QR code (bitmap). The QR code is saved in cache. I want the QR code removed after the QR code is sent to the user, but a "cache" folder gets created (also shows up in gallery), and the image itself gets deleted but it remains there ( you cant see it, but its there as a grey square).
Any idea how to remove the created folder and the created bitmap compeletely?
My code:
BitmapSaver(Context mContext){
this.mContext=mContext;
this.cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024);
}
public static File saveImageToExternalStorage(Context context, Bitmap finalBitmap) {
destFolder =context.getCacheDir().getAbsolutePath();
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
// myDir = new File(root + "/saved_images");
// myDir.mkdirs();
long n = System.currentTimeMillis() / 1000L;
fname = "Image-" + n + ".jpg";
//file2 = new File(destFolder);
file = new File(destFolder+"/"+fname);
if (file.exists())
file.delete();
try {
Log.i("path",destFolder+"/"+fname);
FileOutputStream out = new FileOutputStream(destFolder+"/"+fname);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
url = Uri.parse(path);
Log.i("External",url.toString());
}
});
return file;
}
In Activity after email is sent:
BitmapSaver bms = new BitmapSaver(RegisterActivity.this);
bms.saveImageToExternalStorage(RegisterActivity.this, bitmap);
bms.file.delete();
First of all you need to know what MediaScannerConnection.scanFile does. It will update the file information to the current device, so other applications like gallery, file explorer, etc, can show the correct file information and content.
From your code, when you are saving the temporary file, you are also scanning it, because your app has changed the corresponding file, which is creating the file to be exact. So the file will be available to the other applications right away. But, since the file location is in your application cache directory, it will not accessible by other applications. Usually you must restart your device to update the file information if you don't call MediaScanner.scanFile. If you are creating a temporary file, I think you don't need to call MediaScanner.scanFile, since you will delete it right away.
Then after delete, you also need to re-scan the file again, so other applications will know that the file has been deleted.
Also, despite of using MediaScannerConnection.scanFile directly, if you are supporting android version < KitKat, you should broadcast with intent action Intent.ACTION_MEDIA_MOUNTED instead. And I also recommend that you are broadcasting the data directly, because from my experience MediaScannerConnection.scanFile failed from one of my test devices.
Intent mediaScanIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(new File(imagePath)));
} else {
Uri fileUri = Uri.parse("file://" + imagePath);
mediaScanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED, fileUri);
}
context.sendBroadcast(mediaScanIntent);

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

How to track the path of the file On some other Application

I have an requirement on my app that is , i have to track the file path and second i have to track the time of the file if that file is opened in some other application . I had researched everything but still not figuring out how to start . I know it's challenging and brain stroke implementation , but i need proper idea to move ahead .
I have achieved to create a file (file is of any kind .pdf/.docs etc)inside a folder . Now what i need if any one open the file in any other app then i have to first get the path of the file and secondly i have to track the time at what time the file is opened and closed . Here is the way i created the folder and dumped the file inside it . Now i have to read the file path and file opened in other app .
#Override
protected File doInBackground(FileMetadata... params) {
FileMetadata metadata = params[0];
//pathOfFileToSaved --> eg flight/ticket/vilash.pdf , flight/other/suman.docs
String folder_name = pathOfFileToSaved;
// File f = new File(Environment.getExternalStorageDirectory(), folder_main);
try {
File path = new File(Environment.getExternalStorageDirectory() + "/" + folder_name);
Log.e("pathoffile",""+path);
File file = new File(path, metadata.getName());
// Make sure the Downloads directory exists.
if (!path.exists()) {
if (!path.mkdirs()) {
mException = new RuntimeException("Unable to create directory: " + path);
}
} else if (!path.isDirectory()) {
mException = new IllegalStateException("Download path is not a directory: " + path);
return null;
}
// Download the file.
try (OutputStream outputStream = new FileOutputStream(file)) {
mDbxClient.files().download(metadata.getPathLower(), metadata.getRev())
.download(outputStream);
}
// Tell android about the file
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
return file;
} catch (DbxException | IOException e) {
mException = e;
}
return null;
}

How to save files with DownloadManager in private path?

I have downloaded some files with DownloadManager, I want to save them where that no one can access them, I mean they are private, just my application can access them and I want after uninstall my app they get deleted. but according to my search DownloadManager can save files just in SDCard that everyone can see my files.
can anyone tell me what to do?
You should probably use:
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, File.separator + folderName + File.separator + fileName);
Where request is your DownloadManager.Request
This folder (sdcard/Android/data/your.app.package) is accessible to the user, but not visible in galleries (not scanned by media scanner), it's only accessible using file manager. Also, this folder will be deleted when your app gets deleted.
You can use internal storage path to save data internally and it will get deleted when your app will get uninstalled
String dir = getFilesDir().getAbsolutePath();
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Categories

Resources