Android – Como descargar archivos usando DownloadManager

DownloadManager es servicio de Android que nos facilita las descargar de archivos via HTTP, en especial cuando estos son archivos que pueden demorar en descargar.

DownloadManager gestionará la descarga en segundo plano, cuidando los estados de conectividad del sistema.

downloadmanagerexample

Veremos con un ejemplo sencillo la utilización de esta clase para entender su funcionalidad y lo simple que resulta su utilización.

Obtener una instancia de DownloadManager

Para obtener una instancia de este servicio debemos simplemente solicitarla a través de getSystemService(..) de este modo

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

Definir el Request a la url

Primero necesitamos definir la url sobre la cual deseamos realizar la descarga y el destino

...
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading file " + fileName);
request.setTitle("Downloading");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
...

Requerir la URL

Luego pasamos ese request al DownloadManager

...
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
...

Verificar cuando ha terminado la descarga con BroadcastReceiver

A fin de verificar el momento en el que DownloadManager ha terminado la descarga de nuestro archivo debemos registrar un BroadcastReceiver de este modo

...
registerReceiver(new DonwloadCompleteReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

// 
public class DonwloadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
            Toast.makeText(context,"Download completed", Toast.LENGTH_LONG).show();
            // DO SOMETHING WITH THIS FILE
        }
    }
}
...

Permisos

Debemos tener en cuenta que necesitaremos permisos para INTERNET y para WRITE_EXTERNAL_STORAGE

De este modo quedaría nuestra Activity de ejemplo completa

public class MainActivity extends AppCompatActivity {

    public static final String URL_TO_DOWNLOAD = "https://upload.wikimedia.org/wikipedia/commons/0/0e/Googleplex-Patio-Aug-2014.JPG";
    private static final short REQUEST_CODE = 6545;
    public static final String NAME_FILE = "googleplex.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void download(View view) {
        if (isDownloadManagerAvailable()) {
            checkSelfPermission();
        } else {
            Toast.makeText(this, "Download manager is not available", Toast.LENGTH_LONG).show();
        }

    }

    private static boolean isDownloadManagerAvailable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return true;
        }
        return false;
    }

    private void checkSelfPermission() {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE);

        } else {

            executeDownload();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted! Do the work
                    executeDownload();
                } else {
                    // permission denied!
                    Toast.makeText(this, "Please give permissions ", Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }

    private void executeDownload() {

        // registrer receiver in order to verify when download is complete
        registerReceiver(new DonwloadCompleteReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL_TO_DOWNLOAD));
        request.setDescription("Downloading file " + NAME_FILE);
        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);
        }
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, NAME_FILE);

        // get download service and enqueue file
        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);

    }

}

Nuestro BroadcastReceiver que recibirá el resultado

...
public class DonwloadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
            Toast.makeText(context,"Download completed", Toast.LENGTH_LONG).show();
            // DO SOMETHING WITH THIS FILE
        }
    }
}

Descarga este codigo completo

Referencias:

DownloadManager.Request DownloadManager

Hi! If you find my posts helpful, please support me by inviting me for a coffee :)

Ver también