Why does Environment.getExternalStorageDirectory() create direcotory in Cache folder - android

When I use Environment.getExternalStorageDirectory()+File.separator+"applicationAsbid"; I expect to create a directory in device's external storage but it is created in Cache folder.
Why?
What happened and what should I do?
UPDATE:
This is my method:
root = Environment.getExternalStorageDirectory().getPath();
myDir = new File(root);
myDir.mkdir();
private void downloadDoc(ProgressBar progressBar, CircularImageView imageView, String name, String link, SendMessageViewModel messageData) {
progressBar.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(link);
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("در حال دانلود");
request.setDescription("لطفا منتظر بمانید...");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationInExternalFilesDir(mContext, root, name);
final long id = downloadManager.enqueue(request);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
long downloadedBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long totalBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
final int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
final int percent = (int) ((downloadedBytes * 100) / totalBytes);
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setProgress(percent);
if (percent == 100) {
Toast.makeText(mContext, "دانلود با موفقیت انجام شد", Toast.LENGTH_SHORT).show();
timer.purge();
timer.cancel();
for (int item : downloadList) {
if (Integer.parseInt(messageData.getId()) == item) {
imageView.setImageResource(R.drawable.ic_doc3);
imageView.setContentDescription("after");
progressBar.setVisibility(View.GONE);
}
}
}
}
});
}
}
}, 0, 100);
}
At the end I should say this is not my own code and my colleague has written that. We check that and found nothing so I aske here.
We use Downloadmanager in another class and for download something else. That works fine but here it does not work.
Second Update:
I changed my code to this:
root = Environment.getExternalStorageDirectory().getPath() + "/Dehkade/Chat1";
myDir = new File(root);
if (!myDir.exists()) {
if (!myDir.mkdir()) {
Toast.makeText(mContext," ...sorry could not create directory...",Toast.LENGTH_SHORT).show();
return;
}
}
But it does not work too, in fact the Toast is executed. Also I use this code:
request.setDestinationInExternalFilesDir(mContext, null, name);
Instead of this code:
request.setDestinationInExternalFilesDir(mContext, root, name);
But nothing changes.

Related

Download Speed is slow in Android

I have a list of PDFs that I need to download all PDFs in one click. I have implemented a foreground service to do the task. In this service I am enqueuing the list of PDFs in the Android DownloadManager's request to handle the downloads.
For the enqueue of request, I am inserting 6 PDF's in request for the first time and further when any one download completed I am inserting next PDF in the request list.
In this implementation the whole process is taking around 1-2 mins for the 91 PDFs(roughly size of 40MB in total). Is there any way, so we can speed up the download process.
This is the function to start Download queue
private void startDownloadQueue()
{
for(int i=0;i<6;i++){
if(i<hashMap.size()) {
listIndex++;
initiateDownload(documentList.get(i), positionList.get(i), hashMap.size());
}
}
}
private void initiateDownload(DocumentJsonModel.Document doc, int pos, int listSize)
{
if (doc != null && isDownloading) {
String position = String.valueOf(pos);
String docId = doc.id;
String docFile = doc.file;
String docName = doc.name;
String docDescription = doc.description;
boolean isJustView = false;
isFromSearch = false;
long id = downloadFile(doc, docId, docFile, docName, docDescription, position, isJustView, listSize);
if (id != 0) {
setProgressUpdate(id, Integer.parseInt(position), Integer.parseInt(docId), isJustView, doc, listSize);
} else if (isJustView) {
Intent intent1 = new Intent(INTENT_FILTER_ACTION_OPEN_DOC);
intent1.putExtra("docID",docId);
intent1.putExtra("position",pos);
intent1.putExtra("fromDownloadAll", true);
intent1.putExtra("docId", docId);
sendBroadcast(intent1);
stopForeground(true);
stopSelf();
} else if (isFromSearch) {
Intent intent1 = new Intent(INTENT_FILTER_ACTION_OPEN_DOC_FROM_SEARCH);
intent1.putExtra("fromDownloadAll", true);
intent1.putExtra("position", pos);
intent1.putExtra("docId", docId);
sendBroadcast(intent1);
stopForeground(true);
stopSelf();
}
}
}
Method to enqueue PDFs in download manager request queue -
public long downloadFile(DocumentJsonModel.Document doc,String docId, String docFile, String docName, String description, String position, boolean isJustView, int listSize) {
long downloadReference = 0;
String root = "/twoway/saved_documents/";
String BASE_DIR = getExternalFilesDir(null).getPath();
File dir = new File(BASE_DIR + root);
File file = new File(dir, docId + "_" + docFile);
if(!isCancelledButtonPressed) {
if (!file.exists()) {
String fileUrl = DOCUMENT_URL + docFile;
fileUrl = fileUrl.replaceAll(" ", "%20");
Uri fileUri = Uri.parse(fileUrl);
//Create request for android download manager
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(fileUri);
//set title for download
request.setTitle(docName);
request.setVisibleInDownloadsUi(false);
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
//Setting description of request
request.setDescription(description);
request.setDestinationInExternalFilesDir(this, null, "/twoway/saved_documents/"
+ docId + "_" + docFile);
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
}
}}

Pausing and resuming a download

I know there are some libraries for this, but i want to implement my own pause/resume functionality for android.
i'm now using DownloadManager for downloading and this is the service i implemented for download:
public class DownloadService extends Service {
public static boolean isServiceRunning = false;
private static String downloadingPackageName;
private DownloadManager downloadManager;
long downloadRef;
RemoteViews contentView;
private boolean isDownloading = false;
Notification notification;
NotificationManager manager;
DownloadRequestListener downloadRequestListener;
NotificationManager notifManager;
private String dirPath;
private String packageName;
public static String PACKAGE_NAME;
#Override
public void onCreate() {
super.onCreate();
PACKAGE_NAME = getApplicationContext().getPackageName();
Log.e("OnCreate","OnCreateCommandClled...");
downloadRequestListener = new DownloadRequestListener();
IntentFilter filter = new IntentFilter("ir.amulay.downloadRequest");
registerReceiver(downloadRequestListener, filter);
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
isServiceRunning = true;
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.e("Service","Service Destroyed...");
unregisterReceiver(downloadRequestListener);
isServiceRunning = false;
super.onDestroy();
}
public Long downloadFile(String path, String packageName, String dirPath){
if(isDownloading) return null;
isDownloading =true;
this.dirPath = dirPath;
notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
contentView = new RemoteViews(getPackageName(), R.layout.download_notification_bar);
contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
contentView.setTextViewText(R.id.title, "Custom notification");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChanel = new NotificationChannel(
"downloadChanel",
"Example Service Chanel",
NotificationManager.IMPORTANCE_LOW
);
manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChanel);
}
notification = new NotificationCompat.Builder(this,"downloadChanel")
.setContentTitle("test")
.setContentText("test Againg")
.setContent(contentView)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setAutoCancel(false)
.build();
startForeground(1,notification);
//I Dont Want many files to be downloaded at same time, so here is a check...
downloadingPackageName = packageName;
Uri uri = Uri.parse(path);
//Uri dir = Uri.parse(dirPath + "/" + packageName + ".apk");
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
this.packageName = packageName;
request.setTitle("Download File");
request.setDestinationInExternalPublicDir(dirPath, packageName+".apk");
request.setDescription("download apk files using download manager");
request.setMimeType(getMimeType(uri.toString()));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(false);
// request.setDestinationUri(dir);
request.setAllowedOverMetered(true);
request.setAllowedOverRoaming(true);
downloadRef = downloadManager.enqueue(request);
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
boolean downloading = true;
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadRef); //filter by id which you have receieved when reqesting download from download manager
Cursor cursor = manager.query(q);
if(cursor.getCount() <= 0 ){
return;
}
cursor.moveToFirst();
//if its Running Send BroadCast... :)
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_RUNNING) {
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));
final int dl_progress = (int) ((bytes_downloaded * 100L) / bytes_total);
Log.e("DownloadProgress", "progress= " + dl_progress);
contentView.setTextViewText(R.id.title,"Downloading " +dl_progress);
// contentView.setProgressBar(R.id.downloadProgress,200,dl_progress,true);
notification.contentView.setProgressBar(R.id.downloadProgress, 100, dl_progress, false);
notifManager.notify(1, notification );
Intent intent = new Intent();
intent.setAction("ir.amulay.downloadEvent");
intent.putExtra("eventType","downloadProgress");
intent.putExtra("progresspercent",""+dl_progress);
intent.putExtra("packagename",packageName);
intent.putExtra("refID",""+downloadRef);
sendBroadcast(intent);
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
downloading = false;
}
cursor.close();
if(!downloading) {
Intent intent= new Intent();
intent.setAction("ir.amulay.downloadEvent");
intent.putExtra("eventType","downloadCompleted");
intent.putExtra("packagename",packageName);
intent.putExtra("refID",""+downloadRef);
sendBroadcast(intent);
//send a broadcast to tell its completed
return;
}
handler.postDelayed(this,300);
}
});
return downloadRef;
}
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadRef == id) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
openDownloadedAttachment(context, downloadId);
}
}
};
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
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();
}
private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
if(attachmentUri!=null) {
// Get Content Uri.
if (ContentResolver.SCHEME_FILE.equals(attachmentUri.getScheme())) {
// FileUri - Convert it to contentUri.
File file = new File(attachmentUri.getPath());
attachmentUri = FileProvider.getUriForFile(this, "com.freshdesk.helpdesk.provider", file);
}
Intent openAttachmentIntent = new Intent(Intent.ACTION_VIEW);
openAttachmentIntent.setDataAndType(attachmentUri, attachmentMimeType);
openAttachmentIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(openAttachmentIntent);
} catch (ActivityNotFoundException e) {
// Toast.makeText(context, context.getString("cant O"), Toast.LENGTH_LONG).show();
}
finally {
stopSelf();
}
}
}
private class DownloadRequestListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();
String reqType = intent.getStringExtra("reqType");
String packageName =intent.getStringExtra("package");
if(reqType.equals("download")){
String url = intent.getStringExtra("url");
String dirPath = intent.getStringExtra("dirPath");
downloadFile(url,packageName,dirPath);
}
else if(reqType.equals("stop")){
if(downloadingPackageName.equals(packageName) && downloadManager!= null){
downloadManager.remove(downloadRef);
isDownloading =false;
unregisterReceiver(onDownloadComplete);
stopSelf();
}
}
}
}
}
how can i implement Pause/Resume for my downloads? WITHOUT a library?
is it possible trough Download manager itself or i should use some other methods?
You can send message to the DownloadService you created, and invoke the DownloadManager to do the pause and resume action.
When DownloadManager enqueue a download task, you will get a id (long)
DownloadManager keep the download info in the ContentProvider, just update the ContentProvider info with the given id (long), if the network or other conditions satisfied the action will execute.
You can extends DownloadManager and create a pair of methods like below.
Pause Download
/**
* pause download
*
* #param ids the IDs of the downloads to be paused
* #return the number of downloads actually paused
*/
public int pauseDownload(long... ids) {
if (ids == null || ids.length == 0) {
// called with nothing to remove!
throw new IllegalArgumentException("input param 'ids' can't be null");
}
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_PAUSED);
values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PAUSED_BY_APP);
if (ids.length == 1) {
return mResolver.update(ContentUris.withAppendedId(mBaseUri, ids[0]), values,
null, null);
}
return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
getWhereArgsForIds(ids));
}
Resume download
/**
* resume download
*
* #param ids the IDs of the downloads to be resumed
* #return the number of downloads actually resumed
*/
public int resumeDownload(long... ids) {
if (ids == null || ids.length == 0) {
// called with nothing to remove!
throw new IllegalArgumentException("input param 'ids' can't be null");
}
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_RUNNING);
if (ids.length == 1) {
return mResolver.update(ContentUris.withAppendedId(mBaseUri, ids[0]), values,
null, null);
}
return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
getWhereArgsForIds(ids));
}

DownloadManager.remove(download_id) crash app

I am trying to cancel downloading task with id.
I get id from
DownloadManager manager = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
downloadId = manager.enqueue(req);
I want to stop download when on user button click, but I tested to stop download after 10% of being downloaded in this test code.
the code "manager.remove(downloadId);" is working perfect to clear downloading noti and stopping the task with requested ID. But it also stop the app too, app error also occur after that code. please how can I solve the problem.
new Thread(new Runnable() {
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final 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);
String finalDl_size;
int dl_size = (int) (bytes_total/(1024*1024));
finalDl_size = Integer.toString(dl_size)+" MB";
if(dl_size>1000){dl_size=(int) (bytes_total/(1024*1024*1024));
finalDl_size = Integer.toString(dl_size)+" GB";}
final String finalDl_size1 = finalDl_size;
runOnUiThread(new Runnable() {
#Override
public void run() {
btndownload.setText("Downloading "+Integer.toString(dl_progress)+"% , "+ finalDl_size1);
if(dl_progress==100){
btndownload.setBackgroundColor(Color.GREEN);
btndownload.setText("Download Completed");
}
else if(dl_progress>10){
try{
manager.remove(downloadId); ///// Stop after 10%
}
catch (Exception e){}
}
}
});
cursor.close();
}
}
}).start();
Logcat Output
Please Kindly help me. Thank you in advance.
Try this
if (cursor.getCount() > 0)
manager.remove(downloadId); ///// Stop after 10%

Alternative way to show download progress of DownloadManager

I'm trying to show the download progress of DownloadManager in percentage as shown in the notification bar.
I've read up some answer here.
However, the method provided is using the Thread.
As my understanding,Thread is not a good way.
Is there any alternative way to do the same thing?
Or using Thread is just fine in this case?
Edit 1:
Added in the code in my project.
new Thread(new Runnable() {
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = downloadManager.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);
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
holder.mTextView.setText(String.valueOf(dl_progress) + "%");
}
});
cursor.close();
}
}
}).start();

How to Show download progress in progress bar in Android?

I am using .net web services and I am able to download the file in sd card, But I want to show progress bar when particular file start download and complete and then I want to show options like view and cancel.
Click event Class:
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
LazyAdapter ca = (LazyAdapter)parent.getAdapter();
FolderList item_name = (FolderList)ca.getItem(position);
FolderList DocumentID = (FolderList)ca.getItem(position);
FolderList type = (FolderList)ca.getItem(position);
Intent mIntent = new Intent();
mIntent.putExtra("item_name", item_name.folder_name);
mIntent.putExtra("item_id", DocumentID.ID);
mIntent.putExtra("item_type", type.type);
mIntent.getStringExtra("item_name");
String Type = mIntent.getStringExtra("item_type");
Log.i("Type", Type);
if {
// Some code here...
} else {
Intent i = new Intent(getApplicationContext(), Display_image.class);
i.putExtra("item_name", item_name.folder_name);
i.putExtra("ID", DocumentID.ID);
i.putExtra("item_type", type.type);
i.putExtra("User_ID",User_ID);
i.getStringExtra("item_name");
Id = i.getStringExtra("ID");
i.getStringExtra("item_type");
startActivity(i);
}
}
My Code: I want to use download manager
SoapPrimitive DocumentResponse = (SoapPrimitive)Envelope.getResponse();
Log.i("DocumentResponse", DocumentResponse.toString());
String DocAsString = DocumentResponse.toString();
byte[] decodedString = Base64.decode(DocAsString, Base64.DEFAULT);
File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
if(!direct.exists())
{
direct.mkdir();
}
File photo = new File(Environment.getExternalStorageDirectory() + "/MyFolder", Name);
if (photo.exists())
{
photo.delete();
}
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Name));
request.setDescription("Have Fun ;)");
request.setTitle("Downloading...");
// 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.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(decodedString);
fos.close();
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
ContentValues values= new ContentValues();
System.out.println(values);
}
catch (java.io.IOException e)
{
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
Please suggest how to use download manager into it??? thanks
You could use a ProgressBar to accomplish this.
First, add a progressbar to your interface like this:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/Widget.ProgressBar.Small"/>
Then in your code update your method like this:
protected ProgressBar mProgressBar;
protected long downloadId;
protected DownloadManager manager;
public void startdownload() {
//<SET UP DOWNLOAD MANAGER HERE>
downloadId = manager.enqueue(request);
mProgressBar = findViewById(R.id.progress_bar);
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
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));
cursor.close();
int dl_progress = (bytesDownloaded * 1f / bytesTotal) * 100;
runOnUiThread(new Runnable(){
#Override
public void run(){
mProgressbar.setProgress((int) dl_progress);
}
});
}
}, 0, 10);
}
Use Follow Method
private NotificationManager mNotifyManager;
case R.id.btnSubmit:
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("BuyMixTapes")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.appiconmain);
new DownloadFile().execute(vv);
public class DownloadFile extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//context.showDialog(progress_bar_type);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
protected String doInBackground(String... f_url) {
int count;
try {
for (int i = 0; i < f_url.length; i++) {
Log.e("0url",""+f_url[0]);
Log.e("1url",""+f_url[1]);
// Log.e("1url",""+f_url[1]);
URL url = new URL(f_url[i]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
// OutputStream output = new FileOutputStream("/sdcard/"+f_url[i]);
OutputStream output = new FileOutputStream(
"/sdcard/" +i + "buymix.mp3");
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
*/
/**
* After completing background task
* Dismiss the progress dialog
**/
#Override
protected void onProgressUpdate(String... values) {
// Update progress
mBuilder.setProgress(100, Integer.parseInt(values[0]), false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
// Removes the progress bar
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/downloaded.mp3";
mBuilder.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
}
Update 2021:
Add a ProgressBar in your layout (TextView is just for showing more information):
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/progressBar"
android:text="Hello World!" />
Then before onCreate:
DownloadManager downloadManager;
long downloadReference;
TextView text1;
ProgressBar progressBar;
Timer progressTimer;
Afterwards, in onCreate:
text1 = (TextView) findViewById(R.id.textView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Then after setting up download manager:
// <Some codes which setup download manager>
downloadReference = downloadManager.enqueue(request); // enqueue a new download
// update progressbar
progressTimer = new Timer();
progressTimer.schedule(new TimerTask() {
#Override
public void run() {
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadReference);
Cursor cursor = downloadManager.query(downloadQuery);
if (cursor.moveToFirst()) { // this "if" is crucial to prevent a kind of error
final int downloadedBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final int totalBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); // integer is enough for files under 2GB
cursor.close();
final float downloadProgress = downloadedBytes * 100f / totalBytes;
if(downloadProgress > 99.9) // stop repeating timer (it's also useful for error prevention)
progressTimer.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
text1.setText(downloadedBytes + "\n" + totalBytes + "\n" + downloadProgress + "%");
progressBar.setProgress((int) downloadProgress);
}
});
}
}
}, 0, 1000);
Some tips:
If your file is larger than 2GB, you should use another type instead of int such as double etc.
You can stop timer somewhere else for example, in BroadcastReceiver if you have.
Task executions is every 1000 milliseconds (every 1 second) which is obviously changable.

Categories

Resources