2012-06-06 11 views

Respuesta

27

por favor proporcione un ejemplo de respuesta.

Paso 1 Mire por ejemplo, sobre cómo descargar los archivos en Android

Paso 2 Mire por ejemplo sobre cómo realizar operaciones en AsyncTask.

Paso 3 Busque un ejemplo sobre cómo mostrar el progreso de descarga durante la descarga.

Paso 4 Busque ejemplo de cómo enviar Broadcast personalizada cuando la tarea se ha completado

Paso 5 Mira por ejemplo sobre cómo conservar el funcionamiento AsysncTask incluso en rotación dispositivo

Paso 6 Busque Ejemplo de Cómo mostrar el progreso de descarga en Notificación.

A continuación se muestra el código de ejemplo.

1. Uso AsyncTask y muestran el progreso de la descarga en un diálogo

// 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(false); 
mProgressDialog.setMax(100); 
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 

// execute this when the downloader must be fired 
DownloadFile downloadFile = new DownloadFile(); 
downloadFile.execute("the url to the file you want to download"); 

The AsyncTask will look like this: 

// usually, subclasses of AsyncTask are declared inside the activity class. 
// that way, you can easily modify the UI thread from here 
private class DownloadFile extends AsyncTask<String, Integer, String> { 
    @Override 
    protected String doInBackground(String... sUrl) { 
     try { 
      URL url = new URL(sUrl[0]); 
      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(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/file_name.extension"); 

      byte data[] = new byte[1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 
    } 

El método anterior (doInBackground) se ejecuta siempre en un subproceso en segundo plano. No debe hacer ninguna tarea de interfaz de usuario allí. Por otro lado, el onProgressUpdate y OnPreExecute se ejecutan en el subproceso de interfaz de usuario, por lo que no se puede cambiar la barra de progreso:

@Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     mProgressDialog.show(); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
     super.onProgressUpdate(progress); 
     mProgressDialog.setProgress(progress[0]); 
    } 
} 

2. Descarga del Servicio

La gran pregunta aquí es: ¿cómo Actualizo mi actividad de un servicio ?. En el siguiente ejemplo vamos a utilizar dos clases de las que puede que no tenga conocimiento: ResultReceiver e IntentService. ResultReceiver es el que nos permitirá actualizar nuestro hilo de un servicio; IntentService es una subclase de servicio que genera un hilo para hacer un trabajo de fondo desde allí (debe saber que un servicio se ejecuta realmente en el mismo hilo de su aplicación; cuando extiende el servicio, debe generar nuevos hilos manualmente para ejecutar operaciones de bloqueo de CPU) .

Descargar servicio puede tener este aspecto:

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 { 
      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(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk"); 

      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); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     Bundle resultData = new Bundle(); 
     resultData.putInt("progress" ,100); 
     receiver.send(UPDATE_PROGRESS, resultData); 
    } 
} 

Agregar el servicio a su manifiesta:

<service android:name=".DownloadService"/> 

y la actividad se verá así:

// inicializar el diálogo de progreso como en el primer ejemplo

// así es como enciendes el descargador

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); 

Aquí es decir eran ResultReceiver viene a jugar:

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"); 
      mProgressDialog.setProgress(progress); 
      if (progress == 100) { 
       mProgressDialog.dismiss(); 
      } 
     } 
    } 
} 
+0

Gracias por la respuesta. Voy a intentar esto. –

+3

Si resuelve tu problema, no olvides aceptar la respuesta, ya que ayudará a otros usuarios, –

Cuestiones relacionadas