Faça o download de um arquivo com o Android e mostrando o progresso em um progressdialog
-
26-09-2019 - |
Pergunta
Estou tentando escrever um aplicativo simples que seja atualizado. Para isso, preciso de uma função simples que possa baixar um arquivo e Mostre o progresso atual em um ProgressDialog
. Eu sei como fazer o ProgressDialog
, mas não tenho certeza de como exibir o progresso atual e como baixar o arquivo em primeiro lugar.
Solução
Existem muitas maneiras de baixar arquivos. Seguindo, postarei maneiras mais comuns; Cabe a você decidir qual método é melhor para o seu aplicativo.
1. Use AsyncTask
e mostre o progresso do download em um diálogo
Esse método permitirá que você execute alguns processos em segundo plano e atualize a interface do usuário ao mesmo tempo (neste caso, atualizaremos uma barra de progresso).
Este é um código de exemplo:
// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true); //cancel the task
}
});
o AsyncTask
vai ficar assim:
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
O método acima (doInBackground
) executa sempre em um tópico de segundo plano. Você não deve executar nenhuma tarefa da interface do usuário lá. Por outro lado, o onProgressUpdate
e onPreExecute
Execute no tópico da interface do usuário, para que você possa alterar a barra de progresso:
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
Para que isso seja executado, você precisa da permissão Wake_lock.
<uses-permission android:name="android.permission.WAKE_LOCK" />
2. Baixe do serviço
A grande questão aqui é: Como atualizo minha atividade de um serviço?. No próximo exemplo, usaremos duas classes que você pode não estar ciente: ResultReceiver
e IntentService
. ResultReceiver
é o que nos permitirá atualizar nosso tópico de um serviço; IntentService
é uma subclasse de Service
que gera um tópico para fazer o trabalho de fundo a partir daí (você deve saber que um Service
corre na mesma linha do seu aplicativo; Quando você se estende Service
, você deve gerar manualmente novos threads para executar operações de bloqueio de CPU).
O serviço de download pode ser assim:
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
String path = "/sdcard/BarcodeScanner-debug.apk" ;
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Adicione o serviço ao seu manifesto:
<service android:name=".DownloadService"/>
E a atividade será assim:
// initialize the progress dialog like in the first example
// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
Aqui está ResultReceiver
vem jogar:
private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
dialog.setProgress(progress);
if (progress == 100) {
dialog.dismiss();
}
}
}
}
2.1 Use Biblioteca Groundy
Groundy é uma biblioteca que basicamente ajuda a executar peças de código em um serviço de fundo e é baseado no ResultReceiver
conceito mostrado acima. Esta biblioteca é descontinuada no momento. É assim que o todo o código seria:
A atividade em que você está mostrando a caixa de diálogo ...
public class MainActivity extends Activity {
private ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
Groundy.create(DownloadExample.this, DownloadTask.class)
.receiver(mReceiver)
.params(extras)
.queue();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
});
}
private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
switch (resultCode) {
case Groundy.STATUS_PROGRESS:
mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
break;
case Groundy.STATUS_FINISHED:
Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
mProgressDialog.dismiss();
break;
case Groundy.STATUS_ERROR:
Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
break;
}
}
};
}
UMA GroundyTask
implementação usada por Groundy Para baixar o arquivo e mostrar o progresso:
public class DownloadTask extends GroundyTask {
public static final String PARAM_URL = "com.groundy.sample.param.url";
@Override
protected boolean doInBackground() {
try {
String url = getParameters().getString(PARAM_URL);
File dest = new File(getContext().getFilesDir(), new File(url).getName());
DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
return true;
} catch (Exception pokemon) {
return false;
}
}
}
E apenas adicione isso ao manifesto:
<service android:name="com.codeslap.groundy.GroundyService"/>
Não poderia ser mais fácil, eu acho. Basta pegar o frasco mais recente do github E você está pronto para ir. Tenha em mente que GroundyO principal objetivo é fazer chamadas para APIs de repouso externas em um serviço em segundo plano e publicar resultados na interface do usuário com facilidade. Se você está fazendo algo assim em seu aplicativo, pode ser realmente útil.
2.2 Use https://github.com/koush/ion
3. Use DownloadManager
classe (GingerBread
e apenas mais recente)
Gingerbread trouxe um novo recurso, DownloadManager
, que permite baixar arquivos com facilidade e delegar o trabalho árduo de lidar com tópicos, fluxos, etc. para o sistema.
Primeiro, vamos ver um método de utilidade:
/**
* @param context used to check the device version and DownloadManager information
* @return true if the download manager is available
*/
public static boolean isDownloadManagerAvailable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return true;
}
return false;
}
O nome do método explica tudo. Depois de ter certeza DownloadManager
está disponível, você pode fazer algo assim:
String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// 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);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
O progresso do download será exibido na barra de notificação.
Pensamentos finais
O primeiro e o segundo métodos são apenas a ponta do iceberg. Há muitas coisas que você deve ter em mente se deseja que seu aplicativo seja robusto. Aqui está uma breve lista:
- Você deve verificar se o usuário tem uma conexão com a Internet disponível
- Certifique -se de ter as permissões certas (
INTERNET
eWRITE_EXTERNAL_STORAGE
); tambémACCESS_NETWORK_STATE
Se você deseja verificar a disponibilidade da Internet. - Certifique -se de que o diretório fosse o download de arquivos e tenha permissões de gravação.
- Se o download for muito grande, você poderá implementar uma maneira de retomar o download se as tentativas anteriores falharem.
- Os usuários ficarão agradecidos se você permitir que eles interrompem o download.
A menos que você precise de controle detalhado do processo de download, considere usar DownloadManager
(3) Porque já lida com a maioria dos itens listados acima.
Mas considere também que suas necessidades podem mudar. Por exemplo, DownloadManager
não tem resposta em cache. Ele vai baixar cegamente o mesmo arquivo grande várias vezes. Não há maneira fácil de corrigi -lo após o fato. Onde você começar com um básico HttpURLConnection
(1, 2), então tudo o que você precisa é adicionar um HttpResponseCache
. Portanto, o esforço inicial de aprender as ferramentas básicas e padrão pode ser um bom investimento.
Esta classe foi depreciada no nível 26 da API. O ProgressDialog é uma caixa de diálogo modal, que impede que o usuário interaja com o aplicativo. Em vez de usar esta classe, você deve usar um indicador de progresso como o ProgressBar, que pode ser incorporado na interface do usuário do seu aplicativo. Como alternativa, você pode usar uma notificação para informar o usuário sobre o progresso da tarefa. Para mais detalhes Link
Outras dicas
Não se esqueça de adicionar permissões ao seu arquivo de manifesto se você estiver baixando coisas da Internet!
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:debuggable="true">
</application>
</manifest>
Sim, o código acima funcionará. Mas se você estiver atualizando seu progressbar
dentro onProgressUpdate
do Asynctask
E você pressiona o botão de volta ou termina sua atividade AsyncTask
Perde sua faixa com sua interface do usuário. E quando você voltar à sua atividade, mesmo que o download esteja em execução em segundo plano, não verá nenhuma atualização no ProgressBar. Em breve OnResume()
Tente executar um tópico como runOnUIThread
com uma tarefa de timer que atualiza seu progressbar
com valores atualizando do AsyncTask
Excesso em execução.
private void updateProgressBar(){
Runnable runnable = new updateProgress();
background = new Thread(runnable);
background.start();
}
public class updateProgress implements Runnable {
public void run() {
while(Thread.currentThread()==background)
//while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
Message msg = new Message();
progress = getProgressPercentage();
handler.sendMessage(msg);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
}
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
progress.setProgress(msg.what);
}
};
Não se esqueça de Destruir o fio quando sua atividade não é visível.
private void destroyRunningThreads() {
if (background != null) {
background.interrupt();
background=null;
}
}
Eu modifiquei AsyncTask
classe para lidar com a criação de progressDialog
No mesmo contexto. Acho que o código a seguir será mais reutilizável. (Ele pode ser chamado de qualquer atividade, basta passar o contexto, arquivo de destino, mensagem de diálogo)
public static class DownloadTask extends AsyncTask<String, Integer, String> {
private ProgressDialog mPDialog;
private Context mContext;
private PowerManager.WakeLock mWakeLock;
private File mTargetFile;
//Constructor parameters :
// @context (current Activity)
// @targetFile (File object to write,it will be overwritten if exist)
// @dialogMessage (message of the ProgresDialog)
public DownloadTask(Context context,File targetFile,String dialogMessage) {
this.mContext = context;
this.mTargetFile = targetFile;
mPDialog = new ProgressDialog(context);
mPDialog.setMessage(dialogMessage);
mPDialog.setIndeterminate(true);
mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPDialog.setCancelable(true);
// reference to instance to use inside listener
final DownloadTask me = this;
mPDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
me.cancel(true);
}
});
Log.i("DownloadTask","Constructor done");
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
Log.i("DownloadTask","Response " + connection.getResponseCode());
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(mTargetFile,false);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
Log.i("DownloadTask","Cancelled");
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mPDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mPDialog.setIndeterminate(false);
mPDialog.setMax(100);
mPDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
Log.i("DownloadTask", "Work Done! PostExecute");
mWakeLock.release();
mPDialog.dismiss();
if (result != null)
Toast.makeText(mContext,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File Downloaded", Toast.LENGTH_SHORT).show();
}
}
Não se esqueça de substituir "/sdcard ..." por novo arquivo("/mnt/sdcard/...") Caso contrário, você receberá um FilenotfoundException
eu encontrei isto Postagem de blog muito útil, está usando Loopj para baixar o arquivo, ele tem apenas uma função simples, será útil para alguns novos caras do Android.
Enquanto estava começando a aprender o desenvolvimento do Android, eu aprendi que ProgressDialog
é o caminho a percorrer. Existe o setProgress
método de ProgressDialog
que pode ser chamado para atualizar o nível de progresso à medida que o arquivo é baixado.
O melhor que eu já vi em muitos aplicativos é que eles personalizam os atributos desse diálogo de progresso para dar uma aparência melhor na caixa de diálogo Progresso do que a versão de estoque. Bom para manter o usuário envolvido com alguma animação de gatos/filhotes de gatos/filhotes de elefante ou fofos. Qualquer animação com a caixa de diálogo Progresso atrai usuários e eles não têm vontade de ficar esperando por muito tempo.
Meu conselho pessoal é usar Diálogo de progresso e acumular -se antes da execução, ou iniciar em OnPreExecute()
, publique o progresso frequentemente se você usar o estilo horizontal da barra de progresso da caixa de diálogo Progresso. A parte restante é otimizar o algoritmo de doInBackground
.
Use Android Query Library, muito legal. Você pode alterá -la para usar ProgressDialog
Como você vê em outros exemplos, este mostrará a visão de progresso do seu layout e a ocultará após a conclusão.
File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
if (file != null) {
// do something with file
}
}
});
Permissões
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Usando HttpurlConnection
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadFileUseHttpURLConnection extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path =
"http://coderzheaven.com/sample_folder/sample_file.png";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
});
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) *
100;
cur_val.setText("Downloaded " + downloadedSize +
"KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " +
e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(DownloadFileDemo1.this, err,
Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(DownloadFileDemo1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(
getResources().getDrawable(R.drawable.green_progress));
}
}
Estou adicionando outra resposta para outra solução que estou usando agora, porque a consulta do Android é muito grande e sem atenção para se manter saudável. Então eu me mudei para isso https://github.com/amitshekhariitbhu/fast-android-networking.
AndroidNetworking.download(url,dirPath,fileName).build()
.setDownloadProgressListener(new DownloadProgressListener() {
public void onProgress(long bytesDownloaded, long totalBytes) {
bar.setMax((int) totalBytes);
bar.setProgress((int) bytesDownloaded);
}
}).startDownload(new DownloadListener() {
public void onDownloadComplete() {
...
}
public void onError(ANError error) {
...
}
});