How to download file from Url
fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")
if (!direct.exists()) {
direct.mkdirs()
}
val extension = url?.substring(url.lastIndexOf("."))
val downloadReference: Long
var dm: DownloadManager
dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
request.setDestinationInExternalPublicDir(
"/your_folder",
"pdf" + System.currentTimeMillis() + extension
)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setTitle(title)
Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()
downloadReference = dm?.enqueue(request) ?: 0
return downloadReference
}
Bofore calling this method do check for Runtime permission:
Manifest.permission.WRITE_EXTERNAL_STORAGE
Answer from chand mohd on Stack OverflowHow to download file from Url
fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")
if (!direct.exists()) {
direct.mkdirs()
}
val extension = url?.substring(url.lastIndexOf("."))
val downloadReference: Long
var dm: DownloadManager
dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
request.setDestinationInExternalPublicDir(
"/your_folder",
"pdf" + System.currentTimeMillis() + extension
)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setTitle(title)
Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()
downloadReference = dm?.enqueue(request) ?: 0
return downloadReference
}
Bofore calling this method do check for Runtime permission:
Manifest.permission.WRITE_EXTERNAL_STORAGE
Please try this code
public void downloadPdf(String url, String sem, String title, String branch) {
Uri Download_Uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading");
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading File");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title + "_" + branch + "_" + sem + "Year" + System.currentTimeMillis() + ".pdf");
request.allowScanningByMediaScanner();
request. setNotificationVisibility(DownloadManager.Request. VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)
//Enqueue a new download and same the referenceId
downloadReference = downloadManager.enqueue(request);
}
attach broadcast receiver
BroadcastReceiver attachmentDownloadCompleteReceive = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
openDownloadedAttachment(context, downloadId);
}
}
};
private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
}
}
cursor.close();
}
Videos
Using Async task
call when you want to download file : new DownloadFileFromURL().execute(file_url);
public class MainActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
if not working in 4.0 then add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Simple kotlin version
fun download(link: String, path: String) {
URL(link).openStream().use { input ->
FileOutputStream(File(path)).use { output ->
input.copyTo(output)
}
}
}
is there anyway to get the download progress or downloaded size from this method ?
This is the same realization as defined in InputStream.copyTo, but with progress
/*inline*/ fun download(link: String, path: String, progress: ((Long, Long) -> Unit)? = null): Long {
val url = URL(link)
val connection = url.openConnection()
connection.connect()
val length = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) connection.contentLengthLong else
connection.contentLength.toLong()
url.openStream().use { input ->
FileOutputStream(File(path)).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytesRead = input.read(buffer)
var bytesCopied = 0L
while (bytesRead >= 0) {
output.write(buffer, 0, bytesRead)
bytesCopied += bytesRead
progress?.invoke(bytesCopied, length)
bytesRead = input.read(buffer)
}
return bytesCopied
}
}
}
An example of usage:
val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
// length may be negative because it is based on http header
val (progress, length) = msg.obj as Pair<Long, Long>
}
}
// call this outside of main thread
val totalSize = download("http://example.site/path/to/file", "path/to/file") { progress, length ->
// handling the result on main thread
handler.sendMessage(handler.obtainMessage(0, progress to length))
}
use below library:
implementation 'com.mindorks.android:prdownloader:0.5.0'
code for downloading video from a given url is below:
fun downfile(urll:String,fileName:String){
if(!isFilePresent(fileName)) {
var mFile2: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")
System.out.println("File Foond " + mFile2!!.absolutePath)
var mFile3: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")
var downloadId = PRDownloader.download(urll, mFile2!!.absolutePath, fileName)
.build()
.setOnStartOrResumeListener(object : OnStartOrResumeListener {
override fun onStartOrResume() {
System.out.println("??????????????????? start")
}
})
.setOnPauseListener(object : OnPauseListener {
override fun onPause() {
}
})
.setOnCancelListener(object : OnCancelListener {
override fun onCancel() {
}
})
.setOnProgressListener(object : OnProgressListener {
override fun onProgress(progress: Progress) {
circlePeView.visibility = View.VISIBLE
var per = (progress.currentBytes.toFloat() / progress.totalBytes.toFloat()) * 100.00
//var perint = per*100
System.out.println("::??????????????????? Per : " + per + " ?? : " + progress.currentBytes + " ?? : " + progress.totalBytes)
circlePeView.setProgress(per.toInt())
}
})
.start(object : OnDownloadListener {
override fun onDownloadComplete() {
circlePeView.visibility = View.GONE
circlePeView.setProgress(0)
prefs = getSharedPreferences(PREFS_FILENAME, 0)
val editor = prefs!!.edit()
editor.putString(wall, "WallpapersBillionaire/" + fileName)
editor.apply()
try {
val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
try {
myWallpaperManager.setResource(R.raw.wallp)
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
startActivity(intent)
} catch (e: Exception) {
val intent = Intent()
intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
try {
startActivity(intent)
}catch (e2: java.lang.Exception){
Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
}
}
System.out.println("??????????????????? complete")
}
override fun onError(error: Error) {
System.out.println("??????????????????? error " + error)
}
})
System.out.println("??????????????????? called")
}else{
System.out.println("File Foond ")
circlePeView.visibility = View.GONE
circlePeView.setProgress(0)
prefs = getSharedPreferences(PREFS_FILENAME, 0)
val editor = prefs!!.edit()
editor.putString(wall, "WallpapersBillionaire/" + fileName)
editor.apply()
try {
val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
try {
myWallpaperManager.setResource(R.raw.wallp)
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
startActivity(intent)
} catch (e: Exception) {
val intent = Intent()
intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
try {
startActivity(intent)
}catch (e2: java.lang.Exception){
Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
}
}
System.out.println("??????????????????? complete")
}
}
1) Download Manager
The Android Download Manager was introduced in Android 2.3 as a service to optimize the handling of long-running downloads.
The Download Manger handles the HTTP connection and monitors connectivity changes. Its a good practice to use Download.
Manager in most situations, particularly where a download is likely to continue in the background between user sessions.
Instances of this class should be obtained through getSystemService(String) by passing DOWNLOAD_SERVICE.
Apps that request downloads through this API should register a broadcast receiver for ACTION_NOTIFICATION_CLICKED to appropriately handle when the user clicks on a running download in a notification or from the downloads UI.
2)Running a Service in the Foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
For example, Download a video from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current Download and allow the user to launch an activity to interact with Download process.
To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification for the status bar.
I have a video file(.MP4 format) and I want to allow the user to be able to download the video to their SD card.I currently use this code but its not working..
String PATHSdcard = "/sdcard/Video/";
public void DownloadFromUrl(String VideoURL, String fileName)
try { URL url = new URL("https://javmed-prod.s3.amazonaws.com/666034cbe81045f2a2da50e5205e376b.mp4");
File file = new File(fileName);
long sTime = System.currentTimeMillis();
URLConnection URLcon = url.openConnection();
InputStream is = URLcon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(PATHSdcard+file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ERROR.......",e+"");
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public class VideoSaveSDCARD extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressBack PB = new ProgressBack();
PB.execute("");
}
private class ProgressBack extends AsyncTask<String,String,String> {
ProgressDialog PD;
@Override
protected void onPreExecute() {
PD= ProgressDialog.show(LoginPage.this,null, "Please Wait ...", true);
PD.setCancelable(true);
}
@Override
protected void doInBackground(String... arg0) {
downloadFile("http://beta-vidizmo.com/hilton.mp4","Sample.mp4");
}
protected void onPostExecute(Boolean result) {
PD.dismiss();
}
}
private void downloadFile(String fileURL, String fileName) {
try {
String rootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File rootFile = new File(rootDir);
rootFile.mkdir();
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(rootFile,
fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (IOException e) {
Log.d("Error....", e.toString());
}
}
So after 3 days of wanting to jump off a cliff. I found the answer. Of course it was a few minutes after asking the question here (first question ever so be kind.). The only Issue is you need a SSL cert for HTTPS on the server retrieving the file. My server is http but i can get a cert in there and fix that. to Test i threw up a github repository and linked to the raw text file. Here is my solution if this saves you 3 days pour one out for me.
Thread {
try {
val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
val br = BufferedReader(InputStreamReader(uc.getInputStream()))
var line: String?
val lin2 = StringBuilder()
while (br.readLine().also { line = it } != null) {
lin2.append(line)
}
Log.d("The Text", "$lin2")
} catch (e: IOException) {
Log.d("texts", "onClick: " + e.getLocalizedMessage())
e.printStackTrace()
}
}.start()
Credit: answered Aug 12, 2018 at 9:29 Aishik kirtaniya Android - How can I read a text file from a url?
How about this?
import java.net.URL
val s = "https://www.someplace.com/dir/file.txt"
val text = URL(s).openStream().readAllBytes().decodeToString()
Wrap it in some exception handling if you want. So long as you don't keep references to the intermediate stream, it'll immediately be eligible for garbage collection. The stream will be closed when it's garbage collected, thus I don't bother with adding a call to explicitly close it.