Download any file from url








The post guide how to download any file from file url in sketchware project.
1.Add a linear layout linear1 and a button button1  which will act as download block
[Download file FROM URL(string: url) TO PATH(string: path) with progress dialog]

2.In moreblock area create a moreblock Download.











In add source directly block add following code:

3.android.net.ConnectivityManager connMgr = (android.net.ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {


final String urlDownload = _url;

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlDownload));

final String fileName = URLUtil.guessFileName(urlDownload, null, null);

request.setDescription("URL - " + urlDownload);

request.setTitle(fileName);

request.allowScanningByMediaScanner();

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

request.setDestinationInExternalPublicDir(_path, fileName);

final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

final long downloadId = manager.enqueue(request);

final ProgressDialog prog = new ProgressDialog(this);
prog.setMax(100);
prog.setIndeterminate(true);
prog.setCancelable(false);
prog.setCanceledOnTouchOutside(false);
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setTitle("Please Wait...");
prog.setMessage("Downloading the " + fileName + ".\n\nProgress - 0%");
prog.show();

new Thread(new Runnable() {
@Override
public void run() {

boolean downloading = true;

while (downloading) {

DownloadManager.Query q = new DownloadManager.Query();

q.setFilterById(downloadId);

android.database.Cursor cursor = manager.query(q);

cursor.moveToFirst();

int bytes_downloaded = cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));

int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {

downloading = false;

}

final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);

runOnUiThread(new Runnable() {
@Override
public void run() {

prog.setTitle("Please Wait...");
prog.setMessage("Downloading the " + fileName + ".\n\nProgress - " + dl_progress + "%");
prog.show();

if (dl_progress == 100) {
prog.dismiss();
}

} });
} } }).start();


} else {
showMessage("No Internet Connection.");
}

4.In button1 onClick event add moreblock Download 





In url position add the image url as shown below:

https://res.cloudinary.com/dsra7di8p/image/upload/v1573375424/Screenshot_20191110-140803_MX_Player_Pro_compress90.jpg






5. Save and run the project.Now you can download image from image url oby clicking button1.
4

Comments

Popular posts from this blog