Skip to main content

Android DownloadManager Tutorial | Build mp3 Downloading Android App

Downloading a file from the Internet is an inbuilt feature of most of the apps and having such functionality in your app that could fetch and download anything from the internet can help you build great apps that could possibly download anything like pdf, mp3 or mp4 files which can be later played on phone in offline state as well.

In this tutorial which is the part of Roadway to Android Development Course, we will teach you how you can build a simple button app using DownloadManager service in android that would download an MP3 file from the internet and will notify you the download progress and when it is completed.

Before beginning with this tutorial, if you’re a beginner then you may also be interested in learning how to build your own calculator app and how to build a simple live wallpaper in android.

 Download Manager  is an android library written in java and helpful in accessing the system functionality, which is downloading a file from the link provided. This means that it can handle long running HTTP download request.

Android DownloadManager Tutorial
Android DownloadManager Tutorial


In this tutorial we will request our app to download an mp3 file from the internet (can be any other file format like pdf or mp4 as well) using URI (also known as Uniform resource identifier) which is an immutable object. Also please note that Download Manager class only works if the app has
The Download Manager makes the download happen in the background, update on which can be seen in the notification bar using VISIBILITY_VISIBLE_NOTIFY_COMPLETED code.

So now lets begin with building and coding our app:

1.To start with this tutorial open Android Studio (we are using 3.x version).

2. Create a new project named ‘MP3 Download’ and create an Empty Activity’ using minimum API 19 level.

3. Create a User Interface as shown below with a TextView with simple explanation and a button, you may customize the app with effects like textSize, padding, textColor and background etc.

The code for the activity_main.xml is as follows:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.faultinmycode.mp3download.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download MP3"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.283"
        android:background="@color/colorPrimary"
        android:padding="15sp"
        android:textStyle="bold"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click the Button below to begin Download"
        android:textAlignment="center"
        android:textSize="36sp"
        android:textStyle="bold"
        android:padding="15sp"
        android:textColor="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.18" />
</android.support.constraint.ConstraintLayout>
 
4. Now go to AndroidManifest.xml file and add the permissions that our app will use, which are the Internet, write to the external storage (used for downloading and saving the file) and access the network state, which means is the device using WiFi or Network Data for Download.

5. The code for Android Manifest and to get the permissions required is as follows:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.faultinmycode.mp3download">

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

    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
 
6. Coming on to the coding part, open MainActivity.java file and link the Button in xml file using findViewByID and name this object as dwnbtn. Also create a Uri object which means an Immutable URI reference that’ll be our URL or Download link from where the mpr file will be downloaded. The link we have used for this app is http://download4.prokerala.com/downloads/ringtones/files/dl/mp3/visa-trendz-36946.mp3. 

Button dwnbtn;
Uri imagess = Uri.parse("http://download4.prokerala.com/downloads/ringtones/files/dl/mp3/visa-trendz-36946.mp3");
 
7. Now for dwnbtn use ‘setOnClickListener’ and create an onClick() method to create download request, the code for which is as follows:

DownloadManager.Request request = new DownloadManager.Request(imagess);
 
8. Now set the title and description about your download as follows:

request.setTitle("Music File");
request.setDescription("Its a music File");
 
9. Because the downloaded file is a mp3 file, allow scanning by media scanner.

request.allowScanningByMediaScanner();
 
10. Now to notify that the progress of app download use the following code.

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
 
11. Now we are left with enqueuing the request made to Android system. we can do this by using the following code:

DownloadManager manager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
 
12. Here is the MainActivity.Java file code for this app:

MainActivity.java
package com.faultinmycode.mp3download;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button dwnbtn;
    Uri imagess = Uri.parse("http://download4.prokerala.com/downloads/ringtones/files/dl/mp3/visa-trendz-36946.mp3");

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

        dwnbtn = findViewById(R.id.button);
        dwnbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadManager.Request request = new DownloadManager.Request(imagess);
                request.setTitle("Music File");
                request.setDescription("Downloading File...");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                DownloadManager manager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            }
        });
    }
}
 
TaDa! Build and Run you app in your mobile device, stay tuned with us at faultinmycode to get latest updates on Android App Development and become a smart Developer.

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Get inspirtion from here: Top 7 PDF Download for Mobile Android Apps

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I'v…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…

Python Turtle Example: Flappy Bird Development in under 10 mins!

Python Turtle Example | Develop Flappy Bird Clone in 10 mins In the following tutorial, we have used following Python libraries:
1. random: To generate obstacles at random position. 2. turtle: To help provide directions to the player. 3. vector from freegames: To 2-dimensional vectors.
Before developing the game, here is a screenshot of what you'll be developing in 10 mins.
Steps to create Python Flappy Bird Game:
1. Open Pycharm and install 'freegames' package by going to Files > Settings > Project Interpreter. 2. Click on '+' sign on right and search for 'freegames' package. 3. Import packages in your project by writing following lines of code:
from random import * from turtle import * from freegames import vector 4. There are two variables required in the game, one for Bird object and another for an array of obstacles:
bird = vector(0, 0) balls = []
5. Create function for the player response on screen tap:
def tap(x, y): "Move bird up in res…