Downloading Media in Android (Download Manager)

Downloading Media files in android is a very important task that every app is now performing such as: download pdf or excel file or an image or videos. But it should not hamper the main application’s other tasks means we can see the other features of that app while downloading a video through that app. In android so we need to run that download process in background and hence we need to implement Download Manager which allows downloading media in background. It is also required to notify the app about the status of downloaded file i.e failure or success so that user can easily understand the situation.

This can be done by Broadcast Receiver. So the scenario is that Download Manager download the media file in background process and notify user by using Broadcast Receiver about the status of downloaded file. So here Android App Developers India are going to discuss these two steps with all the required codes.

Downloading-Media

Purpose: Downloading media (like video, audio, images) with the help of Download Manager and Broadcast Receiver in Android.

Scope:

IDE: Android Studio.

Procedure::

Step 1:

At first in your android.Manifest file enable internet, access network state, write external storage and read external storage permissions. Following are codes:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manali.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Step 2:

Next initialize download manager at oncreate method

//start download button Button btnDownload = (Button) findViewById(R.id.startDownload); var downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

On button click event we will write code for download media from a specific URL. Also in this code we can set title and description of notification Bar:

btnDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Download_Uri = Uri.parse("YOUR REQUIRED URL.png"); DownloadManager.Request request = new DownloadManager.Request(Download_Uri); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setAllowedOverRoaming(false); request.setTitle("Data Download" + ".png"); request.setDescription("Downloading " + "Sample" + ".png"); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/Required Title/" + "/" + "Sample" + ".png"); refid = downloadManager.enqueue(request); } });

Step 3:

For multiple file downloading we just set this code with for loop.The download requests will be added into the queue. Next we need to add Broadcast receiver to notify the Download Completed Broadcasts. This will be triggered everytime a download is completed.All the registered application is notified by the Android runtime once event happens. Here we have added NotificationManagerto notify user about completion of downloading media.

BroadcastReceiver onComplete = new BroadcastReceiver() { public void onReceive(Contextctxt, Intent intent) {s // get the referenceid from the download manager long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); // remove it from our list list.remove(referenceId); // if list is empty means all downloads completed if (list.isEmpty()) { // show a notification Log.e("INSIDE", "" + referenceId); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Required Title") .setContentText("All Download completed"); NotificationManagernotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(455, mBuilder.build()); } } }; downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } });

Step 4:

Next we need to register broadcastreceiver in mainactivity onCreate method and also unRegister it in onDestroy method. Following are the codes:

registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(onComplete); }

Step 5:

Next we have created a button to check the download status of the particular media.Query the status of downloaded data. Following are codes:

Button checkStatus = (Button) findViewById(R.id.checkStatus); checkStatus.setOnClickListener(this); checkStatus.setEnabled(false); caseR.id.checkStatus: Query myDownloadQuery = new Query(); //set the query filter to our previously Enqueued download myDownloadQuery.setFilterById(downloadReference); //Query the download manager about downloads that have been requested. Cursorcursor = downloadManager.query(myDownloadQuery); if(cursor.moveToFirst()){ checkStatus(cursor); } break;

Step 6:

Next we need to define checkStatus(cursor) method and will display the status in Toast message.

private void checkStatus(Cursor cursor){ //column for status int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); //column for reason code if the download failed or paused int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON); int reason = cursor.getInt(columnReason); //get the download filename int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME); String filename = cursor.getString(filenameIndex); String statusText = ""; String reasonText = ""; switch(status){ case DownloadManager.STATUS_FAILED: statusText = "STATUS_FAILED"; switch(reason){ case DownloadManager.ERROR_CANNOT_RESUME: reasonText = "ERROR_CANNOT_RESUME"; break; case DownloadManager.ERROR_DEVICE_NOT_FOUND: reasonText = "ERROR_DEVICE_NOT_FOUND"; break; case DownloadManager.ERROR_FILE_ALREADY_EXISTS: reasonText = "ERROR_FILE_ALREADY_EXISTS"; break; case DownloadManager.ERROR_FILE_ERROR: reasonText = "ERROR_FILE_ERROR"; break; case DownloadManager.ERROR_HTTP_DATA_ERROR: reasonText = "ERROR_HTTP_DATA_ERROR"; break; case DownloadManager.ERROR_INSUFFICIENT_SPACE: reasonText = "ERROR_INSUFFICIENT_SPACE"; break; case DownloadManager.ERROR_TOO_MANY_REDIRECTS: reasonText = "ERROR_TOO_MANY_REDIRECTS"; break; case DownloadManager.ERROR_UNHANDLED_HTTP_CODE: reasonText = "ERROR_UNHANDLED_HTTP_CODE"; break; case DownloadManager.ERROR_UNKNOWN: reasonText = "ERROR_UNKNOWN"; break; } break; case DownloadManager.STATUS_PAUSED: statusText = "STATUS_PAUSED"; switch(reason){ case DownloadManager.PAUSED_QUEUED_FOR_WIFI: reasonText = "PAUSED_QUEUED_FOR_WIFI"; break; case DownloadManager.PAUSED_UNKNOWN: reasonText = "PAUSED_UNKNOWN"; break; case DownloadManager.PAUSED_WAITING_FOR_NETWORK: reasonText = "PAUSED_WAITING_FOR_NETWORK"; break; case DownloadManager.PAUSED_WAITING_TO_RETRY: reasonText = "PAUSED_WAITING_TO_RETRY"; break; } break; case DownloadManager.STATUS_PENDING: statusText = "STATUS_PENDING"; break; case DownloadManager.STATUS_RUNNING: statusText = "STATUS_RUNNING"; break; case DownloadManager.STATUS_SUCCESSFUL: statusText = "STATUS_SUCCESSFUL"; reasonText = "Filename:\n" + filename; break; } Toast toast = Toast.makeText(DownloadDataActivity.this, statusText + reasonText, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 25, 400); toast.show(); }