Android tutorial

How to Download PDF from URL in Android Code Example

In this tutorial, I am sharing how to download a pdf files from the server throw URL  in android. Looking for Source code or need to understand how to download PDF files from URL or Server in Android, then you are at the right place. Here I explained Step by Step Tutorial of integrating PDF Downloader Functionality in your Android App

Tutorial of integrating PDF Downloader Functionality in your Android App. It’s an easy way to implement that you just follow the simple step and used it successfully.

How to Download PDF from URL in Android Code Example


Step 1: First one to  Start Android Studio

Step 2 :  Seconds step to Create a New Project Project ClickOn  ==> File  ==> NEW ==> New Project

Step 3: AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
   <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"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application android:allowBackup="true" 

        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Step 4: Open your activity_main.XML and add this code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

        android:text="DOWNLOAD PDF"
        android:textStyle="bold" />

Step 5: Open your java file and add these code on these.

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button btnDownload;
    String URL = "";
// Add your downolde file URL

    protected void onCreate(Bundle savedInstanceState) {
        btnDownload = (Button) findViewById(;
        btnDownload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                new DownloadTask(MainActivity.this, URL);


Step 6: Add the required files, this class is for checking the SD card.

import android.os.Environment;

public class CheckForSDCard {
    //Check If SD Card is present or not method
    public boolean isSDCardPresent() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        return false;

Step 7: This class is for the downloading operation.

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class DownloadTask {
    private static final String TAG = "Download Task";
    private Context context;

    private String downloadUrl = "", downloadFileName = "";
    private ProgressDialog progressDialog;

    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;

        this.downloadUrl = downloadUrl;

        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());//Create file name by picking download file name from URL
        Log.e(TAG, downloadFileName);

        //Start Downloading Task
        new DownloadingTask().execute();

    private class DownloadingTask extends AsyncTask<Void, Void, Void> {

        File apkStorage = null;
        File outputFile = null;

        protected void onPreExecute() {
            progressDialog = new ProgressDialog(context);

        protected void onPostExecute(Void result) {
            try {
                if (outputFile != null) {
                    ContextThemeWrapper ctw = new ContextThemeWrapper( context,;
                    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                    alertDialogBuilder.setTitle("Document  ");
                    alertDialogBuilder.setMessage("Document Downloaded Successfully ");
                    alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {


                    alertDialogBuilder.setNegativeButton("Open report",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            File pdfFile = new File(Environment.getExternalStorageDirectory() + "/CodePlayon/" + downloadFileName);  // -> filename = maven.pdf
                            Uri path = Uri.fromFile(pdfFile);
                            Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                            pdfIntent.setDataAndType(path, "application/pdf");
                            }catch(ActivityNotFoundException e){
                                Toast.makeText(context, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
//                    Toast.makeText(context, "Document Downloaded Successfully", Toast.LENGTH_SHORT).show();
                } else {

                    new Handler().postDelayed(new Runnable() {
                        public void run() {

                    }, 3000);

                    Log.e(TAG, "Download Failed");

            } catch (Exception e) {

                //Change button text if exception occurs

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                }, 3000);
                Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());



        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(downloadUrl);//Create Download URl
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection

                //If Connection response is not OK then show Logs
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                            + " " + c.getResponseMessage());


                //Get File if SD card is present
                if (new CheckForSDCard().isSDCardPresent()) {

                    apkStorage = new File(Environment.getExternalStorageDirectory() + "/" + "CodePlayon");
                } else
                    Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

                //If File is not present create directory
                if (!apkStorage.exists()) {
                    Log.e(TAG, "Directory Created.");

                outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

                //Create New File if not present
                if (!outputFile.exists()) {
                    Log.e(TAG, "File Created");

                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

                InputStream is = c.getInputStream();//Get InputStream for connection

                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                while ((len1 = != -1) {
                    fos.write(buffer, 0, len1);//Write new file

                //Close all connection after doing task

            } catch (Exception e) {

                //Read exception if something went wrong
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());

            return null;

simple Example of Download PDF from URL in Android Example. Stay connected for upcoming latest Android Development related training tutorials.

Android download video from URL and save to internal storage

1 Comment

  1. Quality articles is the secret to be a focus for the visitors to pay a quick visit the web site, that’s what this site is providing.|

Comments are closed.