Android incompeted download file - android

I try to download audio from a URL. I use following sample download manager code from Github https://github.com/folee/Download_Mgr
My problem is If i cancel download, Incomplete mp3 file still there in SDcard. How can i remove Incomplete mp3 files?
#Override
public void onClick(View v) {
Intent downloadIntent = new Intent(DownloadValues.Actions.DOWNLOAD_SERVICE_ACTION);
switch (v.getId()) {
case R.id.btn_continue:
// mDownloadManager.continueTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.CONTINUE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.GONE);
mViewHolder.pauseButton.setVisibility(View.VISIBLE);
break;
case R.id.btn_pause:
// mDownloadManager.pauseTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.PAUSE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.VISIBLE);
mViewHolder.pauseButton.setVisibility(View.GONE);
break;
case R.id.btn_delete:
// mDownloadManager.deleteTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.DELETE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
removeItem(url);
break;
}
}
my file bath :
public class ConfigUtils {
public static void InitPath(Context ctx) {
File temFile = Environment.getExternalStorageDirectory();
if (temFile != null && temFile.canWrite() && Util.getAvailableExternalMemorySize() > 0) {
IMG_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Image/";
FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Downloads/";
}
else {
IMG_PATH = ctx.getFilesDir() + "/Image/";
FILE_PATH = ctx.getFilesDir() + File.separator;
}
new File(IMG_PATH).mkdirs();
new File(FILE_PATH).mkdirs();
Log.i(TAG, "IMG_PATH-->" + IMG_PATH + "\n FILEPATH-->" + FILE_PATH);
}
}
I use this code for delete temp files but not work
case R.id.btn_delete:
File tempFile = new File(ConfigUtils.FILE_PATH + "filename".toString());
if(tempFile.exists()) {
tempFile.delete();
}
But it not work
EDIT:
WORKING CODE: (If download mp3 temp file remane like : "sample.mp3.download"
so ichanged code like this it work fine
File tempFile = new File(ConfigUtils.FILE_PATH + filename +".download".toString());
if(tempFile.exists()) {
tempFile.delete();
}

Before downloading starts. You must know where you are saving the file. So probably a absolute path or Uri pointing to a file in sdcard
that you are giving to Download manager to store your file at.
Incase of cancel. create a file object from that uri or absolute path and call delete on file object if exists.
Something like this
File tempFile = new File(uri.toString());
if(tempFile.exists()) {
tempFile.delete();
}
This should be simple. Google it out

Related

How to open a file without knowing its extension but knowing full name?

Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path+".***"), "video/*");
startActivity(tostart);
Let's say I have a file path
/mnt/sdcard/video/my_birthday_moovie001
'my_birthday_moovie001' can be either .mkv, .mpg or .mkv. I've tried to add ".***" to the file path but I still can't open the file.
Well i read the comments you have stored your path in db without extensions there are many extensions that exists so android cant automatically pick the extension you have to create some way to detect extension.
following is a robust way that is best match in your case but not recommended in proper cases where extensions are known
public String chk_path(String filePath)
{
//create array of extensions
String[] ext=new String[]{".mkv",".mpg"}; //You can add more as you require
//Iterate through array and check your path which extension with your path exists
String path=null;
for(int i=0;i<ext.Length;i++)
{
File file = new File(filePath+ext[i]);
if(file.exists())
{
//if it exists then combine the extension
path=filePath+ext[i];
break;
}
}
return path;
}
now to play a song in your code
if(chk_path(video_path)!=null)
{
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path), "video/*");
startActivity(tostart);
}
else
//tell user that although the path in database but file on this path do not exists
Well as I put on comments
You could compare if the path matches with any filename(it doesn't contains the extension) and then if it does you got it.
You can simply do this :
Get the directory path
File extStore = Environment.getExternalStorageDirectory();
Set the file name my_birthday_moovie001 on my example I put unnamed but change it as your like
String NameOfFile = "unnamed";
Add the videos, I put it Downloads but you can change it
String PathWithFolder = extStore + "/Download/";
Create a method that lists all the files from your path
private List<String> getListFiles(File parentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
String AbsolutePath = file.getAbsolutePath();
//Get the file name ex : unnamed.jpg
String nameofFile = AbsolutePath.substring(AbsolutePath.lastIndexOf("/") + 1, AbsolutePath.length());
//Remove the .jpg --> Output unnamed
String fileNameWithoutExtension = nameofFile.substring(0, nameofFile.lastIndexOf('.'));
//Add each file
inFiles.add(fileNameWithoutExtension);
}
}
return inFiles;
}
You got the names of the files doing this
List<String> files = getListFiles(new File(PathWithFolder));
Simply add a for that looks for a match of your file
for (int i = 0; i<=files.size()-1; i++){
if(PathWithFolder.equals(files.get(i))) {
Toast.makeText(MainActivity.this, "You got it!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "You don't.", Toast.LENGTH_SHORT).show();
}
}
If you want to get the path as well and do what #Zain Ul Abidin proposed and compare it on getListFiles() method add this :
String fileExtension = nameofFile.substring(nameofFile.lastIndexOf("."));
Hope it helps.
From the other question :
Consider DirectoryScanner from Apache Ant:
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).
And then, run on files array and check
if files[i].include(yourfile)
yourfile= files[i]
You may try in this way , first getting the name of file and extension then finally compare and implement. like this :
Example file name is 04chamelon and extension is .png:
File f = new File("/mnt/storage/sdcard/Pictures/04chameleon");
File yourDir = new File("/mnt/storage/sdcard/Pictures");
nametwo = f.getName();
for (File fa : yourDir.listFiles()) {
if (fa.isFile())
fa.getName();
String path = fa.getName(); // getting name and extension
filextension = path.substring(path.lastIndexOf(".") + 1); // seperating extension
name1 = fa.getName();
int pos = name1.lastIndexOf(".");
if (pos > 0) {
name1 = name1.substring(0, pos);
}
}
if (name1.equals(nametwo)) {
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(f + "." + filextension), "image/*");
//tostart.setDataAndType(Uri.parse(f + "." + filextension), "video/*");
startActivity(tostart);
}
With the latest ContentResolver, you can easily make this work using the contentResolver.getType(uri) function which detects the filetype.
private fun getIntentForFile(intent: Intent, filePath: String, context: Context): Intent {
val uri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".fileprovider",
File(filePath)
)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, context.contentResolver.getType(uri))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent
}

Making Android filepaths uniform

I have three segments of code: one that sets the original filepath of the file, one that is used in renaming the file, and one that is used to match the file so that the file (audio recording) can be played.
My problem is that, to the best of my knowledge & what I have been able to find out online, I need "file://" before the rest of the filepath when I am renaming it...otherwise the MediaPlayer throws up exceptions when I try to do the playback. After much searching, I have not come up with a good way to make them uniform so that the "matcher" code can work on all the files. My best guess is that it would be ideal if I could find a way to not have to use "file://" before the rest of the filepath.
1) Code that sets original filepath:
public void setFileNameAndPath(){
int count = 0;
File f;
do{
count++;
mFileName = getString(R.string.default_file_name)
+ " #" + (mDatabase.getCount() + count) + ".mp4";
mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + mFileName;
f = new File(mFilePath);
}while (f.exists() && !f.isDirectory());
}
2) Renaming the filepath:
public void rename(int position, String name) {
//rename a file
String mFilePath = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + name;
File f = new File(mFilePath);
if (f.exists() && !f.isDirectory()) {
//file name is not unique, cannot rename file.
Toast.makeText(mContext,
String.format(mContext.getString(R.string.toast_file_exists), name),
Toast.LENGTH_SHORT).show();
} else {
//file name is unique, rename file
File oldFilePath = new File(getItem(position).getFilePath());
oldFilePath.renameTo(f);
mDatabase.renameItem(getItem(position), name);
notifyItemChanged(position);
}
}
3) Matching the file:
Intent iin = getIntent();
Bundle b = iin.getExtras();
newString = (String) b.get("filename");
mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + newString;
I think file:// is the URI of the file and it's useful for example in a mediaplayer where the resource can exists on local storage (file://) or over internet (http://)
To "convert" string to URI use
Uri uri = Uri.parse("http://www.google.com");
And to "convert" URI to file use
File file = new File(uri.getPath());

Android app - how to write to Android device's Documents folder?

I want to create a XML file inside my Android app.
This file I want to write into the documents folder of my Android device.
Later I want to connect my Android device to my PC using USB and read that XML file out of the documents folder.
My Device is an Android Galaxy Tab Pro 10.1, Android 4.4.2.
I tried already:
String fileName = "example.xml";
String myDirectory = "myDirectory";
String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);
But no file is created. I also want later to read that file out of the documents folder into may app again.
Any help is appreciated, thanks!
I know this is late, but you can get the documents directory like this:
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(dir, "example.txt");
//Write to file
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.append("Writing to file!");
} catch (IOException e) {
//Handle exception
}
Set permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use this code to write to external directory
String fileName = "example.xml";
String dirName = "MyDirectory";
String contentToWrite = "Your Content Goes Here";
File myDir = new File("sdcard", dirName);
/*if directory doesn't exist, create it*/
if(!myDir.exists())
myDir.mkdirs();
File myFile = new File(myDir, fileName);
/*Write to file*/
try {
FileWriter fileWriter = new FileWriter(myFile);
fileWriter.append(contentToWrite);
fileWriter.flush();
fileWriter.close();
}
catch(IOException e){
e.printStackTrace();
}
Before creating file you have to create directory in which you are saving the file.
Try like this one:-
String fileName = "example.xml";
String myDirectory = "myDirectory";
String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
File outputDirectory = new File(externalStorage + File.separator + myDirectory );
if(!outputDirectory.exist()){
outputDirectory.mkDir();
}
File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);
outputFile.createFile();
Try restarting you device and then check if the file exists. If so, you are creating it (which it looks like you should be based on your code) but it is not showing up until the media is scanned on your device. Try implementing MediaScannerConnectionClient so it will show become visible after creation.
public class MainActivity extends Activity implements MediaScannerConnectionClient {
private MediaScannerConnection msConn;
private File example;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
msConn = new MediaScannerConnection(this.getApplicationContext(), this);
String dir = Environment.getExternalStorageDirectory() + "/Documents/";
example = new File(dir, "example.xml");
msConn.connect();
}
#Override
public void onMediaScannerConnected() {
msConn.scanFile(example.getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
}
From Android 10 onwards, Android started using Scoped Storage model to protect user privacy.
If you want to share this file with the User, then you should write this file in Shared Storage. To write a file in Shared Storage, this has to be done in 3 steps:-
Step 1: Launch System Picker to choose the destination by the user. This will return Uri of the destination directory.
private ActivityResultLauncher<Intent> launcher; // Initialise this object in Activity.onCreate()
private Uri baseDocumentTreeUri;
public void launchBaseDirectoryPicker() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
launcher.launch(intent);
}
Step 2: Launch System Picker to choose the destination by the user. This will return the Uri of the destination directory. Also, you can optionally persist the permissions and Uri for future use.
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
baseDocumentTreeUri = Objects.requireNonNull(result.getData()).getData();
final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// take persistable Uri Permission for future use
context.getContentResolver().takePersistableUriPermission(result.getData().getData(), takeFlags);
SharedPreferences preferences = context.getSharedPreferences("com.example.fileutility", Context.MODE_PRIVATE);
preferences.edit().putString("filestorageuri", result.getData().getData().toString()).apply();
} else {
Log.e("FileUtility", "Some Error Occurred : " + result);
}
}
Step 3: Write CSV content into a file.
public void writeFile(String fileName, String content) {
try {
DocumentFile directory = DocumentFile.fromTreeUri(context, baseDocumentTreeUri);
DocumentFile file = directory.createFile("text/*", fileName);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file.getUri(), "w");
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
}
}
For more explanation, you can read "How to Save a file in Shared Storage in Android 10 or Higher" or Android official documentation.

File being downloaded is saved inside data folder

I am using download manager to download MP3 Files from my server.
Here is the code for it.
public String createFilePath()
{
String path;
String dir = "APP_NAME";
path = Environment.getExternalStorageDirectory().getPath();
File file = new File(Environment.getExternalStorageDirectory(),dir);
if(!file.exists())
{
file.mkdir();
}
path += "/" +dir + "/";
System.out.println("-- saving path : " + path);
return path;
}
public void startDownload() {
Uri uri=Uri.parse(URLFixer.Fix(DATA.url));
System.out.println("-- download path : " + createFilePath() + FileNameGetter.getFileName(DATA..url));
DownloadManager.Request request = new Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle(DATA..title);
request.setDescription(DATA.artist + " - " + DATA.album);
request.setDestinationInExternalFilesDir(activity, createFilePath(), FileNameGetter.getFileName(DATA..url));
// request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
lastDownload= mgr.enqueue(request);
isDownloading = true;
Toasts.pop(activity, "Download Started!!");
// v.setEnabled(false);
// findViewById(R.id.query).setEnabled(true);
}
The problem is that it should be saved on SD Card inside folder "APP_NAME", but once the audio is downloaded, I cant see it inside that folder, and when I play the audio, and check its info, it shows path like thie
/sdcard/Android/data/com.X.app/files/mnt/sdcard/APP_NAME/file.mp3
As its being saved inside data folder, user is not able to see the file. How to fix it to move it to main SD Card i.e. /mnt/sdcard/APP_NAME so that user can see it.
DownloadManager.Request.setDestinationUri(Uri uri) should fit your requirement, remember to call allowScanningByMediaScanner() if you want the MP3 to be scanned by MediaScanner.

Where is my Excel file on Android saved?

I have this code which makes new Excel file.
The file is blank, it only creates a sheet.
Code goes like this
public void onClick(View v) {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Havaji");
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Hi there");
try{
FileOutputStream output = new FileOutputStream("Test2.xls");
workbook.write(output);
output.close();
}
...
Where is that file saved ?
How to manage to save a file on the location on the mobile device that i want?
How to create a directory where all the files are gonna be stored?
Here are a few methods you'll find useful for your purposes:
Creates all the directories along the path provided:
public static boolean createPath(String path) {
File pathFile = new File(path);
if (!pathFile.exists()) {
boolean result = pathFile.mkdirs();
if (!result) {
Log.e(TAG, "Unable to create directory path: " +
path);
return false;
}
}
if (!pathFile.isDirectory()) {
return false;
}
return true;
}
Returns the root of the external storage directory:
public static String extDirectory() {
File file = Environment.getExternalStorageDirectory();
return file.getAbsolutePath();
}
Returns the path to the root of an application's external storage directory:
public static String externalMyAppDataRoot(Context context) {
return externalAppDataRoot() + File.separatorChar
+ context.getPackageName() + File.separatorChar + "data";
}
Returns the path to the root of the Android application data directory:
public static String externalAppDataRoot() {
return extDirectory() + File.separatorChar + "Android/data";
}
I'm guessing that is being stored in /data/app//files/Test2.xls, though i'm not completely sure
I would try to pass in an absolute file path. If you want the file to be in the sdcard, i would use the Context.getExternalFilesDir to get the root path of the sdcard.

Categories

Resources