Downloading an image from an http url using DownloadManager and displaying in ImageView by dynamically registered BroadcastReceiver

September 3, 2012
By

In this article we will see how to download an image from an http url using DownloadManager and display it in an ImageView using a dynamically registered broadcast receiver.

This application will work in Android API level 9 ( GingerBread )  and its higher versions. This is because, DownloadManager is introduced in API level 9.

In this application, user can input the url of the image in the EditText widget and press Download button to start downloading the image. Once the download process is complete, DownloadManager sends a broadcast message containing action ACTION_DOWNLOAD_COMPLETE. This broadcast message is received by the BroadcastReceiver class namely DownloadCompleteReceiver.

From the DownloadCompleteReceiver class, we will query the downloaded file to get the file’s details. These details will be passed to UI thread by sending a message via handler.  The handler receive the message in the UI thread and set the file details such as local image uri, title, uri, media type and total size in the textview and displays the image in the ImageView widget.

This application is developed in Eclipse (4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )


1. Create a new Android application project namely “DownloadManagerImage”

New Android Application Project

Figure 1 : New Android Application Project


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity to define MainActivity class

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Remove Android’s Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>

    <string name="app_name">DownloadManagerImage</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">DownloadManager Demo</string>
    <string name="str_btn_download">Download</string>
    <string name="str_btn_view">View Downloads</string>
    <string name="str_et_url">http://wptrafficanalyzer.in/blog/demo/img6.jpg</string>

</resources>


7. Update the layout file res/layout/activity_main.xml


<LinearLayout 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:orientation="vertical"
    android:gravity="center_horizontal" >

    <EditText
        android:id="@+id/et_url"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_et_url"
        android:inputType="textUri" />

    <Button
        android:id="@+id/btn_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_download"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/tv_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/img_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp" />

</LinearLayout>


8. Update the MainActivity class in the file src/in/wptrafficanalyzer/downloadmanagerimage/MainActivity.java


package in.wptrafficanalyzer.downloadmanagerimage;

import android.app.Activity;
import android.app.DownloadManager;
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.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    DownloadManager mDManager;
    DownloadCompleteReceiver mReceiver;
    Handler mHandler;

    ImageView mImgShow;
    TextView mTvDetails;
    EditText mEtUrl;
    Button mBtnDownload;

    String mLocalImageUri;
    String mTitle;
    String mUri;
    String mMediaType;
    String mTotalSize;

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

        mBtnDownload = (Button) findViewById(R.id.btn_download);
        mImgShow = (ImageView) findViewById(R.id.img_show);
        mTvDetails = (TextView) findViewById(R.id.tv_details);
        mEtUrl = (EditText) findViewById(R.id.et_url);

        mDManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);

        /** savedInstanceState will not be null, when the activity
        * is re created by configuration changes
        */
        if(savedInstanceState!=null){
            mLocalImageUri =  savedInstanceState.getString("local_image_uri");
            mTitle = savedInstanceState.getString("title");
            mUri = savedInstanceState.getString("uri");
            mMediaType = savedInstanceState.getString("media_type");
            mTotalSize = savedInstanceState.getString("total_size");

            Uri local_uri = Uri.parse(mLocalImageUri);
            mImgShow.setImageURI(local_uri);

            mTvDetails.setText(
                                "Title : " + mTitle + "\n" +
                                "Uri : " + mUri + "\n" +
                                "Local Image Uri : " + mLocalImageUri + "\n" +
                                "Media Type :" + mMediaType + "\n" +
                                "File Size : " + mTotalSize + " Bytes "
                              );
        }

        /** Creating an instance of Handler class,
        * which draws the image and download image details
        * in the MainActivity
        */
        mHandler = new Handler(){
            @Override
            /** This callback method is invoked when sendMessage() is
            * invoked on this handler
            */
            public void handleMessage(Message msg) {

                mLocalImageUri = msg.getData().getString("local_image_uri");
                mTitle = msg.getData().getString("title");
                mUri = msg.getData().getString("uri");
                mMediaType = msg.getData().getString("media_type");
                mTotalSize = msg.getData().getString("total_size");

                Uri local_uri = Uri.parse(mLocalImageUri);
                mImgShow.setImageURI(local_uri);

                mTvDetails.setText(
                                    "Title : " + mTitle + "\n" +
                                    "Uri : " + mUri + "\n" +
                                    "Local Image Uri : " + mLocalImageUri + "\n" +
                                    "Media Type :" + mMediaType + "\n" +
                                    "File Size : " + mTotalSize + " Bytes "

                );
                super.handleMessage(msg);
            }
        };

        /** Defining a button click listener for the Download button */
        OnClickListener downloadsListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(mEtUrl.getText().toString());
                DownloadManager.Request req = new DownloadManager.Request(uri);
                mDManager.enqueue(req);
            }
        };

        mReceiver = new DownloadCompleteReceiver();
        IntentFilter filter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
        registerReceiver(mReceiver, filter);

        /** Setting click event listener for the button */
        mBtnDownload.setOnClickListener(downloadsListener);

    }

    /** This callback method is called when the configuration
    * change occurs
    */
    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("local_image_uri", mLocalImageUri);
        outState.putString("title", mTitle);
        outState.putString("uri", mUri);
        outState.putString("media_type", mMediaType);
        outState.putString("total_size", mTotalSize);

        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /** Defining a broadcast receiver */
    private class DownloadCompleteReceiver extends BroadcastReceiver{

        /** Will be executed when the download is completed */
        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                Bundle data = intent.getExtras();
                long download_id = data.getLong(DownloadManager.EXTRA_DOWNLOAD_ID );

                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(download_id);

                Cursor c = mDManager.query(query);

                if(c.moveToFirst()){

                    Bundle d = new Bundle();
                    d.putString("title", c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE )));
                    d.putString("uri", c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI )));
                    d.putString("media_type", c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE )));
                    d.putString("total_size", c.getString(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES )));
                    d.putString("local_image_uri", c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI )));

                    Message msg = new Message();
                    msg.setData(d);

                    mHandler.sendMessage(msg);
                }
            }
        }
    }
}


9. Update the file AndroidManifest.xml to provide Internet accessibility permission


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.downloadmanagerimage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

10. Screenshots of the application

Inputing the url of the image to be downloaded

Figure 5 : Inputing the url of the image to be downloaded

Progressing the download process. This will be available in the notifications list

Figure 6 : Progressing the download process. This will be available in the notifications list

Download process is completed and the image and its details are displayed in the MainActivity

Figure 7 : Download process is completed and the image and its details are displayed in the MainActivity


11. Download


12. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , , , ,

4 Responses to Downloading an image from an http url using DownloadManager and displaying in ImageView by dynamically registered BroadcastReceiver

  1. mothar on May 30, 2013 at 3:02 pm

    how to save file to sd

  2. Suman Chatterjee on April 7, 2016 at 10:13 am

    Thanks a lot.

  3. Aakriti Goel on June 17, 2016 at 3:00 pm

    where is DownloadManager class????

  4. Vishal M. Vekariya on July 18, 2016 at 11:45 am

    how to download file in android form dynamic url

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner