Java Code to download files from internet in android studio

In this tutorial, we will write code to download file in android studio using Java.
You can use any latest version of Android Studio.

Let’s get started

Create a new project with name as Codespeedy and package name as org.codespeedy and min android version as 26.

Java Code to download file from the internet in android studio

Since the file will be download using the internet, and it will be saved in local storage so we need the following permissions.

Write these permissions in the manifest.xml file:

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

Now, create a Download Button in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

<!--    // Create a Button-->
    <Button
        android:id="@+id/download_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="156dp"
        android:layout_marginBottom="180dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Upload a File to your google drive:
Then make it sharable to all and copy link:

Convert the Sharing Link
From this Format:
https://drive.google.com/file/d/1gXJ7qf3XJz1Lly4SZJZRYasS3lbQbzuv/view?usp=sharing

To this Format:
https://drive.google.com/uc?id=1gXJ7qf3XJz1Lly4SZJZRYasS3lbQbzuv&export=download

Basically change this -> “/file/d/” to this -> “/uc?id=”
And this at the end -> “/view?usp=sharing” to this -> “&export=download”

Then, write this code in MainActivity.java file:

package org.codespeedy;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;

import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

    Button mButton;

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

        mButton = findViewById(R.id.download_button);

        mButton.setOnClickListener(v -> {
            initDownload();
        });

    }

    /*
    Convert the Sharing Link
    From this:
    // https://drive.google.com/file/d/1gXJ7qf3XJz1Lly4SZJZRYasS3lbQbzuv/view?usp=sharing
    To This:
    // https://drive.google.com/uc?id=1gXJ7qf3XJz1Lly4SZJZRYasS3lbQbzuv&export=download
    */

    private void initDownload() {
        String uri = "https://drive.google.com/uc?id=1gXJ7qf3XJz1Lly4SZJZRYasS3lbQbzuv&export=download";
        download(getApplicationContext(), "CodeSpeedy_writer", ".pdf", "Downloads", uri.trim());
    }

    private void download(Context context, String Filename, String FileExtension, String DesignationDirectory, String url) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, DesignationDirectory, Filename + FileExtension);

        assert downloadManager != null;
        downloadManager.enqueue(request);
        Snackbar snackbar = (Snackbar) Snackbar
                .make(findViewById(android.R.id.content), "Downloading...", Snackbar.LENGTH_LONG);
        snackbar.show();
    }

}

In the above code:

  1. First we get the download button by id.
  2. Then we set a onClick() listener for that button.
  3. Then we create a download() function.
  4. In the download function we first get the DOWNLOAD system service.
  5. Then we create a request for downloading the file using the uri (which here happens to be a google drive
  6. download link)
  7. Then we specify that the Android OS should generate a notification upon successful download of the file.
  8. Then we specify the Directory where the downloaded file will be stored.
  9. Then we enqueue the request so that it can be executed by the Android OS.

Its all done now,
So, for running the app, please connect your mobile to laptop via USB (First enable USB debugging in your mobile and make sure that USB can transfer data)
Then run the app on your mobile and press the download button.

Leave a Reply

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