1. This post is about downloading a file from its url to getFilesDir() of the app. Similar code can be used to download to getCacheDir() with little modification.
2. In permission manager add INTERNET permission.
3. Create a java class file LinkHelper.java and put following codes in it. (Change package name to package name of your app).
package com.my.newproject5;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class LinkHelper {
// INTERFACES
public interface DownloadCallback {
void onProgress(int percent); // 0 → 100
void onSuccess(File file);
void onError(String message);
}
// ASYNC FILE DOWNLOAD WITH PROGRESS LISTENER
public static void downloadToAppDataAsync(
final Context context,
final String url,
final String outputName,
final DownloadCallback callback
) {
final Handler ui = new Handler(context.getMainLooper());
new Thread(new Runnable() {
@Override
public void run() {
InputStream input = null;
FileOutputStream output = null;
try {
final File outFile = new File(context.getFilesDir(), outputName);
URL downloadUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) downloadUrl.openConnection();
conn.connect();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new Exception("HTTP " + conn.getResponseCode());
}
int totalSize = conn.getContentLength();
int downloaded = 0;
input = conn.getInputStream();
output = new FileOutputStream(outFile);
byte[] buffer = new byte[4096];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
int percent = (totalSize > 0)
? (downloaded * 100 / totalSize)
: -1;
final int finalPercent = percent;
ui.post(new Runnable() {
@Override
public void run() {
callback.onProgress(finalPercent);
}
});
}
output.flush();
ui.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(outFile);
}
});
} catch (final Exception e) {
ui.post(new Runnable() {
@Override
public void run() {
callback.onError(e.getMessage());
}
});
} finally {
try { if (input != null) input.close(); } catch (Exception ignored) {}
try { if (output != null) output.close(); } catch (Exception ignored) {}
}
}
}).start();
}
public static boolean isFileAlreadyDownloaded(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
return file.exists() && file.length() > 0;
}
}
4. In main.xml, add an EditText edittext1, a Button button1, a SeekBar  ;seekbar1, and a ListView listview1.
5. Create a custom view list_item.xml. In this put a TextView textview1 and an ImageView imageview1 (with delete icon as image).
6. Select list_item.xml as custom view of listview1.
7. Create a number variable n, two String variables link and filename, a List String filelist and a List Map listmap.
8. Create a more block refreshList and put blocks as shown below. Here we get list of all files in getFilesDir() to List String filelist and then one by one add all items from filelist to List Map listmap.
10. Add a Dialog component dialog.
11. In onBindCustomView, in textview1 display filename, and in imageview1 onClick event delete the file.
12. In button1 onClick event, set link to edittext1 getText, set filename to last segment path of link and the use following codes to download.
boolean exists = LinkHelper.isFileAlreadyDownloaded(
getApplicationContext(),
filename
);
if (exists) {
Toast.makeText(getApplicationContext(), "File already exists", Toast.LENGTH_SHORT).show();
} else {
binding.seekbar1.setVisibility(View.VISIBLE);
LinkHelper.downloadToAppDataAsync(
getApplicationContext(),
link,
filename,
new LinkHelper.DownloadCallback() {
@Override
public void onProgress(int percent) {
binding.seekbar1.setProgress(percent);
}
@Override
public void onSuccess(File file) {
binding.seekbar1.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Downloaded: " + file.getPath(), Toast.LENGTH_LONG).show();
_refreshList();
}
@Override
public void onError(String message) {
binding.seekbar1.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
}
);
}
13. Save and run the project.






0 Comments