How to Download files using OkDownload Android Library

🎯 How to Download Files in Android Using OkDownload

In this tutorial, we’ll learn how to create a simple Android application that downloads video or file content using the OkDownload library. We'll use Java and integrate a clean UI with a ProgressBar to track the download process.


📁 Step 1: Add Required Permissions

Add the following permissions to your AndroidManifest.xml:

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

🧩 Step 2: XML Layout (res/layout/main.xml)


<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

    </com.google.android.material.appbar.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="8dp">

        <EditText
            android:id="@+id/edittext1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter file URL" />

        <ProgressBar
            android:id="@+id/progressbar1"
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/downloadButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Download"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

🧠 Step 3: Java Code (MainActivity.java)


public class MainActivity extends AppCompatActivity {

    private EditText edittext1;
    private ProgressBar progressbar1;
    private Button downloadButton;
    private String path;

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

        edittext1 = findViewById(R.id.edittext1);
        progressbar1 = findViewById(R.id.progressbar1);
        downloadButton = findViewById(R.id.downloadButton);

        path = FileUtil.getExternalStorageDir().concat("/OkDownload/");
        if (!FileUtil.isExistFile(path)) {
            FileUtil.makeDir(path);
        }

        downloadButton.setOnClickListener(v -> {
            _download(edittext1.getText().toString(), path);
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(intent);
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        }
    }

    private void _download(final String _link, final String _path) {
        OkDownload.setSingletonInstance(new OkDownload.Builder(getApplicationContext()).build());
        DownloadTask task = new DownloadTask.Builder(_link, new File(_path))
            .setMinIntervalMillisCallbackProcess(500)
            .setPassIfAlreadyCompleted(false)
            .build();

        task.enqueue(new DownloadListener() {
            @Override
            public void taskStart(@NonNull DownloadTask task) {
                progressbar1.setVisibility(View.VISIBLE);
            }

            @Override
            public void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes) {
                progressbar1.setProgress((int) increaseBytes);
            }

            @Override
            public void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength) {
                progressbar1.setVisibility(View.GONE);
                downloadButton.setText("Completed");
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
                Toast.makeText(MainActivity.this, "Download Finished", Toast.LENGTH_SHORT).show();
            }

            // Empty implementations for unused methods
            public void connectTrialStart(...) {}
            public void connectTrialEnd(...) {}
            public void connectStart(...) {}
            public void connectEnd(...) {}
            public void downloadFromBeginning(...) {}
            public void downloadFromBreakpoint(...) {}
        });
    }
}


✅ Output

➡️ The app displays an input box where you can paste a file URL (e.g., MP4 video), and a Download button. It handles progress with a horizontal progress bar and confirms when the download is complete.

📦 Library Used

  • OkDownload - Advanced download library for Android

💡 Tip

Always request MANAGE_EXTERNAL_STORAGE for Android 11+ and test with valid download URLs.

---

📌 If you found this tutorial useful, follow SketchLife for more Android guides!

Comments

Popular posts from this blog

How to Display Math Equations in Android Using MathView