Re: [androidbrasil-dev] Aplicativo travando ao realizar download

Ola amigo bom dia,
obrigado pela sugestão.

Consegui resolver aqui. Era mais um caso de aprendizado do que de produtividade em si.

Consegui resolver utilizando a solução desse link


2017-09-16 13:24 GMT-03:00 Rudson Lima <rudsonlive@gmail.com>:
Amigo recomendo vc usar o Download Manager. Com poucas linhas de código vc consegue fazer o download, ter uma notificação e ainda ter o progress do download. 

Em 16 de set de 2017 1:14 PM, "Willian do Amor" <willsazon@gmail.com> escreveu:
Tenho o seguinte código para fazer download de um arquivo

private class AsyncDownloadTask extends AsyncTask<String, String, Boolean> {


       
private static final String TAG = "DownloadUpdateAsyncTask";


       
private int NOTIFICATION_ID = 1;


       
private HttpURLConnection httpURLConnection;


       
private InputStream input;


       
private OutputStream output;




       
@Override
       
protected Boolean doInBackground(String... params) {


           
boolean sucesso;


           
try {


                sucesso
= baixarAtualizacao(params[0], params[1], params[2]);


           
} catch (Exception e) {


               
return null;
           
}




           
return sucesso;
       
}


       
@Override
       
protected void onPostExecute(Boolean result) {
           
super.onPostExecute(result);


           
try {


               
if (result != null) {


                   
if (result) {


                       
/*terminando o download remove a notificacao*/
                        notificationManager
.cancel(NOTIFICATION_ID);




                        sha1sumLocal
= AndroidUtils.getHash(fileDestino);
                       
Log.i(TAG, "sha1sum local: " + sha1sumLocal + " | sha1sum remota: " + sha1sum);


                       
/*Valida o checksum do arquivo para saber se o download
                        *terminou*/

                       
if (sha1sum.equalsIgnoreCase(sha1sumLocal)) {


                           
Log.i(TAG, "MD5 do arquivo OK! ");


                            sendNotificationUpdate
(DownloadUpdateTaskService.this, android.R.drawable.stat_sys_download_done, DownloadUpdateTaskService.this.getString(R.string.app_name),
                                   
DownloadUpdateTaskService.this.getString(R.string.download_notification_install_tittle), DownloadUpdateTaskService.this.getString(R.string.download_notification_install_message),
                                    NOTIFICATION_ID
, true, fileDestino.getAbsolutePath());




                       
} else {


                           
if (fileDestino.exists()) {
                                fileDestino
.delete();
                           
}
                       
}


                   
} else {


                        sendNotificationUpdate
(DownloadUpdateTaskService.this, android.R.drawable.stat_sys_download_done, DownloadUpdateTaskService.this.getString(R.string.app_name),
                               
DownloadUpdateTaskService.this.getString(R.string.download_notification_install_tittle), DownloadUpdateTaskService.this.getString(R.string.download_notification_falha),
                                NOTIFICATION_ID
, false, "");




                   
}
               
}


           
} catch (Exception e) {


               
Log.e(TAG, "onPostExecute - Erro ao fazer download " + e);
                sendNotificationUpdate
(DownloadUpdateTaskService.this, android.R.drawable.stat_sys_download_done, DownloadUpdateTaskService.this.getString(R.string.app_name),
                       
DownloadUpdateTaskService.this.getString(R.string.download_notification_install_tittle), DownloadUpdateTaskService.this.getString(R.string.download_notification_falha),
                        NOTIFICATION_ID
, false, e.toString());


           
}




       
}


       
/*Faz o download do arquivo */
       
private boolean baixarAtualizacao(String url, String hash, String local) {


            urlDownload
= url;
            sha1sum
= hash;
            destino
= local;


           
try {


               
Log.i(TAG, "urlDownload - " + urlDownload);


                URL urlOrigem
= new URL(urlDownload);
                   
/**/
               
int slashIndex = urlOrigem.getFile().lastIndexOf('/');
                   
/**/
               
String fileName = urlOrigem.getFile().substring(slashIndex + 1);
                   
/**/
                fileDestino
= new File(destino, fileName);


               
new File(destino).mkdirs();


               
/**Conectar a URL de destino*/
               
URLConnection connect = urlOrigem.openConnection();


               
/*Pega o tamanho do arquivo*/
               
int lenghtOfFile = connect.getContentLength();


                httpURLConnection
= (HttpURLConnection) connect;
                httpURLConnection
.setConnectTimeout(getConnectionTimeout());
                httpURLConnection
.setReadTimeout(getReaderTimeout());
                httpURLConnection
.connect();


                 
/*Realiza o Download do arquivo*/
                input
= new BufferedInputStream(httpURLConnection.getInputStream());
                output
= new FileOutputStream(fileDestino);


               
byte data[] = new byte[1024];
               
int countRead;
               
int progress = 0;
               
int percent = 0;




               
while (!isCancelled() && (countRead = input.read(data)) != -1) {
               
/*Verifica se a task nao foi cancelada*/
                   
if (isCancelled()) {
                        input
.close();


                   
}


                    progress
+= countRead;
                    percent
= (int) ((progress * 100) / lenghtOfFile);


                   
/*Grava os bytes recebidos do arquivo no dispositivo*/


                   
Log.i(TAG, "Download... " + percent);
                    output
.write(data, 0, countRead);


                   
if (!isCancelled()) {


                        showNotification
(lenghtOfFile, progress, percent, DownloadUpdateTaskService.this.getString(R.string.app_name), DownloadUpdateTaskService.this.getString(R.string.download_notification_download_progress));
                   
}


               
}


                output
.flush();
                output
.close();
                input
.close();


               
Log.i(TAG, "Download do arquivo completo! ");


               
return true;
           
} catch (Exception e) {


               
if (fileDestino.exists()) {
                    fileDestino
.delete();
               
}


                input
= null;
                output
= null;


               
Log.e(TAG, "Falha no download do arquivo de atualização!", e);


               
return false;


           
} finally {


               
try {


                   
if (httpURLConnection != null) {


                        httpURLConnection
.disconnect();


                   
}




               
} catch (Exception e) {


                   
Log.e(TAG, "Erro ao fechar arquivo output " + e.getMessage());


               
}
           
}/*Finnaly*/


       
}


//
       
private void showNotification(int lenghtOfFile, int progresso, int porcentagem, CharSequence ticket, CharSequence contentText) {


           
/*Cria uma notificacao para informar ao usuario
            do andamento do download*/

           
Intent notificationIntent = new Intent();
            notificationIntent
.setAction(Intent.ACTION_VIEW);


           
/*Cria a pending intent*/
           
PendingIntent contetIntent = PendingIntent.getActivity(DownloadUpdateTaskService.this, 0, notificationIntent, 0);


           
/*Cria o remote view*/
           
RemoteViews remoteViews = new RemoteViews(DownloadUpdateTaskService.this.getPackageName(), R.layout.notification_download_media);
            remoteViews
.setTextViewText(R.id.notification_title, DownloadUpdateTaskService.this.getString(R.string.download_notification_download_progress));
            remoteViews
.setProgressBar(R.id.notification_progress, lenghtOfFile, 1, false);


             
/*Atualiza a porcentagem do download na notificacao*/
            remoteViews
.setProgressBar(R.id.notification_progress, lenghtOfFile, progresso, false);
            remoteViews
.setTextViewText(R.id.notification_porcentagem, porcentagem + "%");


           
//Configura a notificacao
           
Notification notification = new NotificationCompat.Builder(DownloadUpdateTaskService.this)
                   
//.setLargeIcon(BitmapFactory.decodeResource(DownloadUpdateTaskService.this.getResources(), android.R.drawable.stat_sys_download))
                   
.setSmallIcon(android.R.drawable.stat_sys_download)
                   
.setContentTitle(DownloadUpdateTaskService.this.getString(R.string.app_name))
                   
.setTicker(ticket)
                   
.setContentText(contentText)
                   
.setWhen(System.currentTimeMillis())
                   
.setContentIntent(contetIntent)
                   
.setContent(remoteViews)
                   
.build();


            notification
.flags = Notification.FLAG_AUTO_CANCEL;
            notification
.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;


           
/*Inicia o servico em primeiro plano*/
           startForeground
(NOTIFICATION_ID, notification);


       
}


       
/*Atualiza a notificacao*/
       
public void sendNotificationUpdate(Context context, int icon, CharSequence ticketText, CharSequence title, CharSequence text, int notifyID, boolean vibrate, String dstFile) {


           
String ns = Context.NOTIFICATION_SERVICE;
           
NotificationManager notificationManager = (NotificationManager) DownloadUpdateTaskService.this.getSystemService(ns);


           
long when = System.currentTimeMillis();


           
Intent notificationIntent = new Intent(context, InstallUpdateIntent.class);
            notificationIntent
.putExtra("dstFile", dstFile);


           
PendingIntent contIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);


           
Notification notification = new NotificationCompat.Builder(context)
                   
.setSmallIcon(icon)
                   
.setContentTitle(title)
                   
.setContentText(text)
                   
.setTicker(ticketText)
                   
.setContentIntent(contIntent)
                   
.setWhen(when)
                   
.build();


           
if (vibrate) {


                notification
.defaults = Notification.DEFAULT_VIBRATE;
           
}


            notification
.flags = Notification.FLAG_AUTO_CANCEL;


            notificationManager
.notify(notifyID, notification);
       
}




   
}/*Fim da classe DownloadUpdateTaskService*/



O código funciona e o download e realizado normalmente.

O problema acontece quando eu clica na notificação para ver o andamento do download.
Quando tento expandir a notificação trava o aplicativo e chega a travar até o celular.

Alguém sabe o que estou fazendo de errado?

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS