049 Java Android to demonstrate Download Manager in Android
Posted by Superadmin on February 26 2017 09:12:53

Java Android to demonstrate Download Manager in Android

Here is source code of the Program demonstrates Download Manager in Android in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

 

Before you can access Internet resources, you need to add an INTERNET uses-permission node to your application manifest, as shown in the following XML snippet:

<uses-permission android:name=”android.permission.INTERNET/>

The Download Manager was introduced in Android 2.3 (API level 9) as a Service to optimize the handling of long-running downloads. The Download Manager handles the HTTP connection and monitors connectivity changes and system reboots to ensure each download completes successfully.

To access the Download Manager, request the DOWNLOAD_SERVICE using the getSystemService method, as follows:

String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceString);

To request a download, create a new DownloadManager.Request, specifying the URI of the file to download and passing it in to the Download Manager’s enqueue method.

 
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceString);
Uri uri = Uri.parse(“http://developer.android.com/shareables/icon_templates-v4.0.zip”);
DownloadManager.Request request = new Request(uri);
long reference = downloadManager.enqueue(request);

You can use the returned reference value to perform future actions or queries on the download, including checking its status or canceling it. You can add an HTTP header to your request, or override the mime type returned by the server, by calling addRequestHeader and setMimeType, respectively, on your Request object. You can also specify the connectivity conditions under which to execute the download. The setAllowedNetworkTypes method enables you to restrict downloads to either Wi-Fi or mobile networks, whereas the setAllowedOverRoaming method predictably enables you to prevent downloads while the phone is roaming.

The following snippet shows how to ensure a large fi le is downloaded only when connected to Wi-Fi:

request.setAllowedNetworkTypes(Request.NETWORK_WIFI);

To receive a notification when the download is completed, register a Receiver to receive an ACTION_DOWNLOAD_COMPLETE broadcast. It will include an EXTRA_DOWNLOAD_ID extra that contains the reference ID of the download that has completed. The following code snippet demonstrates this

 
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (myDownloadReference == reference) {
                    // Do something with downloaded file.
            }
    }
};
registerReceiver(receiver, filter);

This particular class focuses on how to download a file(/picture from the specified URL) and display it on the Image View in the Activity , further the user can check about the information of the downloaded file.

Main Activity

package com.example.downloadmanager;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {
    private long enqueue;
    private DownloadManager dm;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button download = (Button) findViewById(R.id.button1);
        Button viewdownload = (Button) findViewById(R.id.button2);
 
        download.setOnClickListener(this);
        viewdownload.setOnClickListener(this);
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                    long downloadId = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    Query query = new Query();
                    query.setFilterById(enqueue);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {
                        int columnIndex = c
                                .getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == c
                                .getInt(columnIndex)) {
 
                            ImageView view = (ImageView) findViewById(R.id.imageView1);
                            String uriString = c
                                    .getString(c
                                            .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            view.setImageURI(Uri.parse(uriString));
                        }
                    }
                }
            }
        };
 
        registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
 
    @Override
    public void onClick(View view) {
 
        switch (view.getId()) {
 
        case R.id.button1:
 
            dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Request request = new Request(
                    Uri.parse("http://www.sanfoundry.com/wp-content/uploads/2013/04/san-ecosystem_new.png"));
            enqueue = dm.enqueue(request);
            break;
        case R.id.button2:
            Intent i = new Intent();
            i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            startActivity(i);
            break;
        }
 
    }
 
}

ActivityMain.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="34dp"
        android:text="View Downloads" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Click to Download" />
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="70dp"
        android:src="@drawable/ic_launcher" />
 
</RelativeLayout>