File manager android kotlin

Let’s Build a File Explorer in Kotlin

Have you been away from Kotlin for a while? Wanna practice your Kotlin skills? Wanna build an Android app in Kotlin?

If yes, then I have something for you.

I have written a 5 part tutorial series, in which you will build a basic File Explorer application in Android using Kotlin.

You will start from scratch, setting up the UI and then implementing the corresponding functionality. I will guide you through every feature that is included in the application and keep showing you tips and tricks about Kotlin every now and then. All in all this is a great way to refresh your Kotlin skills.

Kotlin File Explorer

Below are screenshots of completed application.

The source code of completed application can be found at this GitHub repo (Clone the repo as it will help you whenever you are stuck).

Tutorial Series

Part 1 — Introduction and Set up

You will start with setting up an empty project and configure permissions that are required for accessing the file system in Android. You will add a basic File Provider which is required as of Android 7.0.

Part 2 — Reading files from paths

In this part you will set up functions that will read files from a particular path in the file system. Then you will display these files in RecyclerView for the user to see and interact with. This might sound simple but we will implement this functionality with reusability in mind so there is more to it than you think!

Part 3 — Navigating through File System

After you are done reading files from a path, you will add the functionality for the user to navigate through the file system i.e. whenever the user clicks on a folder, you will open up the list of files contained inside that folder and so on.

Part 4 — Adding Breadcrumbs

Now comes the fun part. You might have seen in many file manager applications, in the Toolbar they have a way to navigate back to a point in the file system where you came from, these are called breadcrumbs. You will implement this feature!

Part 5 — Creating/Deleting files and folders

In this part you will add feature to create/delete file and folders anywhere in the file system.

Part 6— Copying/Moving files and folders

I have written a 5 part tutorial series, and you might wonder why is 6th part mentioned. No! this is not a tutorial. This is your homework 😀

I hope you enjoy this short series on Kotlin.

Источник

Download Files in Android — Kotlin & Java

Unless you are writing a Download Manager, downloading files in an Android application is never going to be the main business logic to solve but based on the requirement, you may need to download metafiles, media files, or documents over the Internet within your Android application. However, a reliable solution to download files in an Android application poses its own challenges including but not limited to the following list:

1. Thread Management

IO operations must be executed in a separate thread. Though there are plenty of options to achieve this such as now deprecated AsyncTask, Kotlin coroutines, or RxJava, still complex for a novice developer to properly handle the concurrency problems. Sending signals to the downloading thread to cancel or pause the download may introduce additional synchronization issues.

2. Error Handling

What if the Internet connection dropped while downloading the file? What if the application is closed while downloading/saving the file? How to handle all HTTP errors? the list goes on. Addressing all these scenarios is tedious and most of the time not possible.

3. Updating the UI

While downloading the file in a separate thread, updating a progress bar in the main thread is a challenge unless the concurrency framework you use provides an easy way. The same goes to update the UI after the file is downloaded.

4. Advanced Features

Though not all applications need it, sometimes you may need to pause and resume a download. Implementing such advanced features requires complex coding.

Of course, you can write the code from scratch to download a file, but it is hard to write a reliable solution addressing all the above-listed challenges. Especially if your business logic is something else, the time invested to solve these problems may not be productive.

There are plenty of libraries out there solving all these problems and provide easy to use APIs to download files. This article introduces such a library: PRDownloader a feature-rich but simple library to download files. PRDownloader offers the following features in addition to solving all the above listed problems.

  • PRDownloader can be used to download any type of files like image, video, pdf, apk and etc.
  • This file downloader library supports pause and resume while downloading a file.
  • Supports large file download.
  • This downloader library has a simple interface to make download request.
  • We can check if the status of downloading with the given download Id.
  • PRDownloader gives callbacks for everything like onProgress, onCancel, onStart, onError and etc while downloading a file.
  • Supports proper request canceling.
  • Many requests can be made in parallel.
  • All types of customization are possible.
Читайте также:  Selinux permissive android 11 magisk

The library is inter-operable with both Java and Kotlin. This article is using Kotlin code to demonstrate the library but it can be used with Java too.

Let’s get our hands dirty. The following sample project demonstrates how to use PR Downloader to download a file, show the progress in a progress bar and show a Toast message once the file is successfully downloaded or if there is an error.

Create a new Android project with an Empty Activity in your Android Studio with the following properties:

Name: PRDownloader Demo
Package name: com.example.prdownloaderdemo
Language: Kotlin (You can choose Java if you prefer Java)
Leave other fields with their default value.

First thing first. Add the following permission to the Android Manifest file to access the Internet. You may also need to have External Storage permission if you want to save the file to an external storage location. To keep the article simple, we will save the file in the internal storage of the application

After the changes, the Android Manifest.xml should look like this:

Open the build.gradle (Module) file and add the following dependency.

After adding the dependency, the build.gradle should look like this. Click the «Sync Now» link to synchronize the project after saving the changes made in the build.gradle file.

Step 4:
Modify the activity_main.xml as shown below. A download button and a progress bar are added to the layout.

Step 5:
Open the MainActivity.kt file and initialize the references for the ProgressBar and Button widgets and initialize them in the onCreate method as shown below:
Step 6:
Initialize the PRDownloader in the onCreate function as shown below:

In the above code, read and connection timeout values are set to limit the waiting time if the server is down. PRDownloader offers more configuration options to pause and resume downloads but this article will stick to a simple implementation. After the changes, the MainActivity.kt should look like this:

Create a new function named » readFile » to read a given text file from the internal storage and show it in a Toast. This function is optional as we need this only to validate the downloaded file. Also note that, showing a large text in a Toast is not a good idea but this article is using a tiny README file from the GitHub repository for the demo therefore the content of the text file is shown in a Toast.

Create another function named » download » with the following code. This function is responsible to download the file, save it to the internal storage and call the readFile method after downloading the file successfully.

As implemented in the above function, we only need to pass the URL, output destination, and output file name. PR Downloader will take care of all the IO operations and error handling.

Call the download function from the button click event in the onCreate function as shown below. Here a hard-coded URL and a file name are used for simplicity but you can extend this application to download from any URL you want.

After following all these steps, your final code should look like this:

Save all the changes and run the app. Once the app is ready, click on the «Download» button and see if the file is downloaded. You may not see the progress bar being updated while downloading the given URL in this article because the file is too small and it will be downloaded within a fraction of a second. To see the progress, you have to download a large file but do not call the readFile function after downloading a large file.

To learn more about the PR Downloader, please take a look at the official GitHub page. If you have any questions, feel free to comment below.

Источник

Atomic Spin

Atomic Object’s blog on everything we find fascinating.

Download Files in Kotlin for Android Using Ktor and Intents

Giving a user the ability to download files in your app can be difficult to figure out. In iOS, you can use AlamoFire to download the file locally and then present it with a UIDocumentInteractionController. (The code would look something like this.) It presents the documents, images, gifs, videos, etc. in the app for you, and you can then download to the device from there.

Unfortunately, this isn’t simple in Android because there are many OEMs for Android devices. (In-app image viewing can be handled using Glide. If you absolutely need to view PDFs in-app, you can probably find some solution, but I would recommend just giving the users download ability and letting their device handle it.) Today, I’ll explain how to download files in Kotlin using Ktor and intents.

Initial Setup

The first thing you will need are some dependencies, Ktor, and coroutines. Add these to your app Gradle. Ktor allows for asynchronous communication, which is very useful for file downloading and reporting file progress.

Then we need to add this file into res.xml. (You’ll likely need to create the xml resources folder.) It adds an external path.

In the AndroidManifest, make sure to add these permissions:

Add the provider. This uses the external path we defined above for the FileProvider.

Downloader Coroutine

The coroutine for downloading files will be an extension on Ktor’s HttpClient. First, we need a class to return during the coroutine to report on the status of the download.

This extension creates a coroutine that takes an output stream and URL. While the file is read in, the current progress is emitted. Once finished, the data is written to the output stream, and success is returned. Otherwise, there was some failure.

This code was originally found on Kotlin Academy.

The ViewModel and Layout

Before making the fragment, we need a view model and a layout. The view model is simple, only containing a Boolean to indicate if the download is occurring.

The layout itself is also simple, just a button (which is enabled when the file isn’t downloading) and a horizontal progress bar. Note that material-style circle progress bars can’t have progress set and continually spin; they’re more useful for other types of requests.

Читайте также:  Популярные головоломки для андроида

The Fragment

The base of the fragment is straightforward enough. Of note are the permissions and codes: if the app doesn’t have these permissions, the app can’t download files. The codes don’t need to be “1” and “2,” but if there are others in the app, they should all be unique.

When the fragment loads, if we have permissions, we can set the button click listener; otherwise, we have to request permission. Some apps request these permissions on first load if they require them throughout the app. Others only request them where they are actually needed. If your app has a specific place where file downloads occur, you can just request permission there.

First, we need functions to check the permissions and the request result. Note that only devices with Marshmallow (API 23) or later need permissions; earlier devices had them by default.

If permission needs to be requested, our return should set the click listener when permission is granted. Either you can force the download to occur where you want with the name you provide, or you can let the user decide the name and location. I use the latter case here; the click will start an intent for creating a document with some defaults set.

The result will use the returned URI as the location for downloading the file.

Downloading the file opens the output stream to the URI given and dispatches the download file coroutine. The download itself is handled on the IO thread, but the emitter results are handled on the Main thread. This allows for the correct asynchronous updates (in this case, updating the progress bar).

The viewFile function takes the same URI given and opens it in an intent, if able. If there are multiple applications where the file can be viewed, it presents a chooser.

The code for this can be found on my Github repo: kotlin-file-downloading.

Источник

Kotlin Android DownloadManager Tutorial and Examples

Android DownloadManager Tutorial and Examples

In this session we explore the android.app.DownloadManager class, how to use it and why it’s important.We will look at issues like the types of downloads you can make with DownloadManager class, how to make the actual requests, how to show progress in status bar via noification, open downloaded file and even remove.

What is DownloadManager?

The DownloadManager is a system service which we can use to handle long running downloads.

Why Download?

Don’t underestimate the need for downloads and how complex it can get. The state of bandwith in the current era implies that we are still not able, at least in many parts of the world, to be able to obtain files we need on demand any time. Users don’t leave their internet on all time as it does cost money and drain the device’s battery.

Hence being able to download files and store them locally is important. But this is not an easy task to implement properly. Especially doing it correctly and efficiently. Yet it is one of those tasks that can absolutely be shared among apps. There is no real need most of the time to re-invent the wheel while making http downloads. It makes sense to have one simple to use class that can do this efficiently and inform our app when the task is complete.

Being able to download data is powerful way of enriching our apps as we can get files from the internet which our app can then use. If the user happens to remove the file, we can re-download it again.

Common Questions

Here are some of the questions to allow us understand the DownloadManager class.

Which Types of Downloads are Handled by DownloadManager

Normally there are several protocols for communications across devices. And certainly download a file is just a form or communicating between atleast two devices. One device supplying a file while another receiving it. Beware the DownloadManager is used to handle only HTTP downloads.

DownloadManager is especially useful if your downlaods are long running.

Where Do the Downloads take Place?

Where with regards to threads. Well the downloads will definitely take place in the background thread.

Why Use the DownloadManager?

Well what are it’s advantages? Well we have several. For example

  1. As we said the downloads take place in the background thread. In fact in a background in a system app. This means our app doesn’t have to handle the downloads manually in our main thread hence our UI is always responsive. This fact is quite important. Downloading data is one of the most time and resource consuming tasks personal gadgets do. Yet it is one of those tasks that really make devices as powerful as they are. So we have to do them. But we have to do them in a background thread and DownloadManager definitely obeys that.
  2. Secondly the HTTP interactions are abstracted away from us. We don’t have to worry about variou HTTP codes and messages and possible failures. In fact even retries are made on our behalf. Yet these retries can amazingly be persisted through connectivity state changes and system reboots. Progress can be shown to us as the download takes place hence making it very user friendly.

DownloadManager Quick HowTos and Snippets

1. How to download videos using DownloadManager class

We want to download videos using the DownloadManager class in android. We want to give them appropriate names and store them in external storage.

First we have been passed the video url as a parameter. Let’ say we want to download only mp4 files, so we provide a simple boolean check to check if it contains mp4. Maybe you could use endsWith() if you like instead of contains() .

DownloadManager Examples

Let’s look at some DownloadManager examples.

Example 1. Download File, View All Download, Delete Download

In this complete example we want to see how to download a file from the internet using the downloadManager class. Then we can open the donwload by clicking the notification in the system bar or from internally in our app. Moreover we can delete the file, view all downloads etc.

Video Tutorial

Here we have a video tutorial for this example.

Here’s the demo of the app.

OverView of the App

  1. User clicks the download button.
  2. Download starts.
  3. Meanwhile the progress is shown in the status bar as a notification. The notification also includes the title and description of the download.
  4. The user is notified via the system status bar text when the download is complete.
  5. When user clicks the notification the file is opened. If it is not found then a toast message is shown.
  6. When user clicks View All button then the view for displaying all the downloads is shown. You may have some other downloads enqueued there, some not from your application.
  7. When user clicks the Delete button then our download whether partial or complete gets deleted.
Читайте также:  About flash player для android
(a). MainActivity.java

MainActivity as you can imagine is our launcher activity. it will derive from the AppCompatActivity . This is where we write all our code. But first we start by making several imports. These include:

  1. DownloadManager – The class responsible for allowing us use the system download manahger.
  2. Intent – Class responsible for allowing us open the system download manager view.
  3. Uri – Allows us to parse a string url into a Uri from which our file can be downloaded.
  4. Environment – Allow us specify the public directory where our downloaded file will be stored.
  5. Toast – Allow us to show quick messages.

HowTo’s

Let’s look at several howTos.

(a). How to Initialize the DownloadManager

As a System service, the DownloadManager is not instantiated directly. Instead we will initialize it using the getSystemService() method and cast the resultant object into the DownloadManager class.

(b). How to Create a Download Request

Inside the DownloadManager class is an inner class called the Request class. We can use this class to define our HTTP Request. We conveniently do this via the builder patter.

Clearly you can see we’ve pased the Uri into our Request constructor. Then set the title, descrription, destination and notification visibility.

(c). How to enqueue a Download

Enqueueing a download means adding it to the download queue of the download manager. Then the queue will be processed automatically the system. You enqueue a download using the enqueue() method.

This will return us a download id.

(d). How to remove/delete downloaded file

Well you can remove a downloaded file from the download manager using the remove() method of the DownloadManager class. You pass the download id.

Here’s the full source code.

(b). activity_main.xml

We need a layout for our MainActivity . Here’s the code.

(c). AndroidManifest.xml

In our AndroidManifest we need to add permissions for internet connectivity as well as for writing to external storage. This is because we download our image from internet and write to our external storage.

Here’s my full AndroidManifest.xml file:

Download

Here are reference resources:

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube ProgrammingWizards TV Channel

Example 2: Kotlin Android simple DownloadManager Example

A simple open source Kotlin downloadmanager example suitable for absolute beginners.

Step 1: Create Project

Start by creating an empty AndroidStudio project.

Step 2: Dependencies

No special third party library is needed for this project.

Step 3: Design Layout

Design you MainActivity layout by adding a textview in a ConstraintLayout as shown below:

activity_main.xml

Step 4: Write Code

Start by adding imports:

Create MainActivity by extending AppCompatActivity :

Define a download ID:

Override onCreate() callback:

Create an annonymouse BroadcastReceiver and inside it override the onReceive() as follows:

Create a Download Uri:

Initialize a DownloadRequest:

Enqueue the Download:

Register the BroadcastReceiver:

Here is the full code:

MainActivity.kt

Step 5: Add permissions

In your AndroidManifest add the following permissions:

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 3: Kotlin Android – Dynamic Download

In this example you learn how to download from any link. The link is provided at runtime via an EditText.

Step 1: Create Project

Start by creating an empty AndroidStudio project.

Step 2: Dependencies

No third party dependency is needed for this project.

Step 3: Design Layout

Add an EditText and Button in your mainactivity’s layout:

activity_main.xml

Step 4: Write Code

Start by adding imports to your MainActivity.kt as follows:

Create the Activity:

Define instance fields:

Create an annonymouse BroadcastReceiver class and implement the onReceive() method as follows:

Setup event handlers:

Here is the function that downloads the item:

Unregister the BroadcastReceiver in the onCreate() :

Here is the full code:

MainActivity.kt

Android Manifest

In the AndroidManifest.xml add the following permissions:

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 4: Kotlin DownloadManager with Runtime Permissions and Coroutines

Here is yet another DownloadManager example written in Kotlin. This utilizes Kotlin Coroutines. It also involves checking for necessary permissions at runtime before the download.

Step 1: Create Project

Start by creating an empty AndroidStudio project.

Step 2: Dependencies

No third party dependency is used.

Step 3: Design Layout

Design a simple layout with a button and a textview:

activity_main.xml

Step 4: Write Code

Start by adding imports:

Extend the AppCompatActivity :`

Then define a download URL as an instance field:

Override the onCreate() :

When the download button is clicked, before initiating download we check for permission:

If granted we initiate the download.

Here is the function to initiate download the image:

Here is the function that constructs and returns the Download status as a string that can be displayed to the user:

The following function will allow you to ask for the necessary permissions before we proceed with the download:

Then handle the permission request resulytusing the following callback:

Here is the full code:

MainActivity.kt

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Оцените статью