Android downloading in background

Android downloading in background

Note: Unsupported feature

This package is not an officially supported feature, and is provided «as is».

Use Background Download to download large files in the background on mobile platforms. It lets you fetch files that aren’t required immediately while caring less about application lifecycle. Downloads will continue even if your application goes into background or the Operating System closes it (usually due to low memory for foreground tasks). The Background Download package is not a replacement for HTTP clients. It has a specific focus on fetching lower-priority files for future use. Because the app assumes that these downloads have lower priority, download speeds can also be slower.

The Background Download is not integrated with the Addressable System or Asset Bundles and will require you write additional code to use in this context.

Limited platform support

Background Download only works on Android, iOS and Universal Windows Platform. It does not work in the Unity Editor, it only compiles.

For 2019.4 or newer

This feature is built as a package. To install the package, follow the instructions in the Package Manager documentation from a local folder or from a GIT URL.

For 2019.3 or older:
Clone/download this project from the 2019-3-and-older branch. Drop BackgroundDownload and Plugins folders into Assets in your Unity project. If you are building for Android, you have to set Write Permission to External in Player Settings. If you are building for Universal Windows Platform, you need to enable one of the Internet permissions.

The following table describes the package folder structure:

Location Description
Runtime Contains C# code and native plugins for mobile platforms.
Samples Contains example C# scripts explaining how to use this package.

The example below shows how to call StartCoroutine(StartDownload()) to download a file during the same app session in a coroutine.

The example below shows how to pick up a download from a previous app run and continue it until it finishes.

Enum that lets control the network types over which the downloads are allowed to happen. Not supported on iOS.

  • UnrestrictedOnly — downloads using unlimited connection, such as Wi-Fi.
  • AllowMetered — allows downloads using metered connections, such as mobile data (default).
  • AlwaysAllow — allows downloads using all network types, including potentially expensive ones, such as roaming.

Structure containing all the data required to start background download. This structure must contain the URL to file to download and a path to file to store. Destination file will be overwritten if exists. Destination path must relative and result will be placed inside Application.persistentDataPath , because directories an application is allowed to write to are not guaranteed to be the same across different app runs. Optionally can contain custom HTTP headers to send and network policy. These two settings are not guaranteed to persist across different app runs.

  • System.Uri url — the URL to the file to download.
  • string filePath — a relative file path that must be relative (will be inside Application.persistentDataPath ).
  • BackgroundDownloadPolicy policy — policy to limit downloads to certain network types. Does not persist across app runs.
  • float progress — how far the request has progressed (0 to 1), negative value if unkown. Accessing this field can be very expensive (in particular on Android).
  • Dictionary > requestHeaders — custom HTTP headers to send. Does not persist across app runs.
  • void AddRequestHeader(string name, string value) — convenience method to add custom HTTP header to requestHeaders .

The state of the background download

  • Downloading — the download is in progress.
  • Done — the download has finished successfully.
  • Failed — the download operation has failed.

A class for launching and picking up downloads in background. Every background download can be returned from the coroutine to wait for it’s completion. To free system resources, after completion each background download must be disposed by calling Dispose() or by placing the object in a using block. If background download is disposed before completion, it is also cancelled, the existence and contents of result file is undefined in such case. The destination file must not be used before download completes. Otherwise it may prevent the download from writing to destination. If app is quit by the operating system, on next run background downloads can be picked up by accessing BackgroundDownload.backgroundDownloads .

  • static BackgroundDownload[] backgroundDownloads — an array containing all current downloads.
  • BackgroundDownloadConfig config — the configuration of download. Read only.
  • BackgroundDownloadStatus status — the status of download. Read only.
  • string error — contains error message for a failed download. Read only.
  • static BackgroundDownload Start(BackgroundDownloadConfig config) — start download using given configuration.
  • static BackgroundDownload Start(Uri url, String filePath) — convenience method to start download when no additional settings are required.
  • void Dispose() — release the resources and remove the download. Cancels download if incomplete.

About

Plugins for mobile platforms to enable file downloads in background

Источник

How to Download File in Background Using Android WorkManager? (Tutorial)

This Android WorkManager download file tutorial will be useful for those who want to develop an Android app with the feature of downloading any file, such as music, document, or video
In this Android WorkManager upload file tutorial, we will learn how to:-

  • Add WorkManager in an Android Project
  • Creating a background task
  • Configuring how to run the task

Before moving to the technical part, we will understand what is a background task, what is Android WorkManager, the benefits of it, and when one should make use of it.

What is a Background Task?

To define a background task in simple terms, we can say that the Background task is an existing app-related task which not executed completely within the app. Generally, we need to execute the task within an app on a background thread because it is an invaluable process.

Now, because we don’t want to block the existing app or we want the task to continue running even after if we close the current app, we have to put that task into a background thread to execute.

What is Android WorkManager?

Have you ever noticed when downloading any file, data or document in an Android app that sometimes when you close the app, that file download gets paused/stop?

Moreover, in some cases, you also have observed that when you come out of the app, the download still works until the file is downloaded completely. Isn’t it?

Yes, this all occurs with the help of Android WorkManager. Now, you must be wondering what is WorkMager?

WorkManager in Android is one of the parts of Architecture Components and Android Jetpack that runs the postponed background task when the task’s restrictions are fulfilled.

WorkManager controls the background task that needs to run when various restrictions are gathered, irrespective of whether the application process is viable or not.

There are many options available on the Android platform for prolonged background work and WorkManager is one of the most compatible and simple libraries to perform the temporary adjourned task. WorkManager has been preferred as one of the best task schedulers in Android to work on postponed tasks with an assurance of execution.

The background task can be executed in 2 different methods using Android WorkManager,

  1. Opportunistic execution:– In this method, the WorkManager will perform the execution of the background task as soon as possible.
  2. Guaranteed execution:– In this method, the WorkManager will make sure to start the execution of background tasks under different conditions, even if we come out of the app.

Benefits of Android WorkManager

WorkManager in Android is a simple yet resilient library which has numerous benefits, given as:

  1. Follows system health best practices
  2. Fully backward compatible
  3. Handles API level compatibility back to API level
  4. Supports constraints such as network conditions, storage space, and charging status
  5. LiveData support to easily display work request state in UI
  6. Tasks can be chained, while it also supports both asynchronous one-off and periodic tasks

When to Use Android WorkManager?

Although there are different ways for background task execution like ForegroundService, JobScheduler, AlarmManager, Firebase JobDispatcher, here we will prefer to use Android WorkManager as it can easily set up a task for run & forward it to the system based on specified conditions.

There are a few use cases where it is suitable to use WorkManager, such as

  • Upload files to the server
  • Syncing data to or from the server
  • Sending logs to the server
  • Executing the valuable process

To know more in detail, you can refer to the Android development guide released by Google. In our Android app development tutorial, we will learn how to download a file using WorkManager.

Validate your app idea and get a free quote.

Источник

Android Downloading File by Showing Progress Bar

When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.
This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.

As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded
completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!

Creating new Project

1. Create a new project and fill all the details. File ⇒ New ⇒ Android Project
2. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your main.xml

3. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.

4. Progress Dialog can be shown using ProgressDialog class. It is a subclass of normal AlertDialog class. So add an alert method in your main activity class.

5. Now we need to add our Async Background thread to download file from url. In your main activity add a asynctask class and name it as DownloadFileFromURL(). After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.

6. Open your AndroidManifest.xml file and add internet connect permission and writing to sdcard permission.

7. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.

Final Code

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]

Источник

Foreground services

Foreground services perform operations that are noticeable to the user.

Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources. The notification cannot be dismissed unless the service is either stopped or removed from the foreground.

Devices that run Android 12 (API level 31) or higher provide a streamlined experience for short-running foreground services. On these devices, the system waits 10 seconds before showing the notification associated with a foreground service. There are a few exceptions; several types of services always display a notification immediately.

Examples of apps that would use foreground services include the following:

  • A music player app that plays music in a foreground service. The notification might show the current song that is being played.
  • A fitness app that records a user’s run in a foreground service, after receiving permission from the user. The notification might show the distance that the user has traveled during the current fitness session.

You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they’re not directly interacting with the app. If the action is of low enough importance that you want to use a minimum-priority notification, create a background task instead.

This document describes the required permission for using foreground services, how to start a foreground service and remove it from the background, how to associate certain use cases with foreground service types, and the access restrictions that take effect when you start a foreground service from an app that’s running in the background.

Services that show a notification immediately

If a foreground service has at least one of the following characteristics, the system shows the associated notification immediately after the service starts, even on devices that run Android 12 or higher:

  • The service is associated with a notification that includes action buttons.
  • The service has a foregroundServiceType of mediaPlayback , mediaProjection , or phoneCall .
  • The service provides a use case related to phone calls, navigation, or media playback, as defined in the notification’s category attribute.
  • The service has opted out of the behavior change by passing FOREGROUND_SERVICE_IMMEDIATE into setForegroundServiceBehavior() when setting up the notification.

Request the foreground service permission

Apps that target Android 9 (API level 28) or higher and use foreground services must request the FOREGROUND_SERVICE permission, as shown in the following code snippet. This is a normal permission, so the system automatically grants it to the requesting app.

Start a foreground service

Before you request the system to run a service as a foreground service, start the service itself:

Kotlin

Inside the service, usually in onStartCommand() , you can request that your service run in the foreground. To do so, call startForeground() . This method takes two parameters: a positive integer that uniquely identifies the notification in the status bar and the Notification object itself.

Note: The status bar notification must use a priority of PRIORITY_LOW or higher. If your app attempts to use a notification that has a lower priority, the system adds a message to the notification drawer, alerting the user to the app’s use of a foreground service.

Here is an example:

Kotlin

Restrictions on background starts

Apps that target Android 12 (API level 31) or higher can’t start foreground services while running in the background, except for a few special cases. If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException .

Check whether your app performs background starts

To better understand when your app attempts to launch a foreground service while running in the background, you can enable notifications that appear each time this behavior occurs. To do so, execute the following ADB command on the development machine connected to your test device or emulator:

Update your app’s logic

If you discover that your app starts foreground services while running from the background, update your app’s logic to use WorkManager. To view an example of how to update your app, look through the WorkManagerSample on GitHub.

Exemptions from background start restrictions

In the following situations, your app can start foreground services even while your app is running in the background:

  • Your app transitions from a user-visible state, such as an activity.
  • Your app can start an activity from the background, except for the case where the app has an activity in the back stack of an existing task.

Your app receives a high-priority message using Firebase Cloud Messaging.

Note: When your app is in the frequent bucket or a more restrictive bucket, your high-priority FCM messages might be downgraded to normal priority. If the message’s priority is downgraded, your app can’t start a foreground service. To check the priority of an FCM message that your app receives, call getPriority() .

The user performs an action on a UI element related to your app. For example, they might interact with a bubble, notification, widget, or activity.

Your app invokes an exact alarm to complete an action that the user requests.

Your app is the device’s current input method.

Your app receives an event that’s related to geofencing or activity recognition transition.

Your app receives the ACTION_TIMEZONE_CHANGED , ACTION_TIME_CHANGED , or ACTION_LOCALE_CHANGED intent action in a broadcast receiver.

Your app receives a Bluetooth broadcast that requires the BLUETOOTH_CONNECT or BLUETOOTH_SCAN permissions.

Apps with certain system roles or permission, such as device owners and profile owners.

Your app uses the Companion Device Manager and declares the REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND permission or the REQUEST_COMPANION_RUN_IN_BACKGROUND permission. Whenever possible, use REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND .

The user turns off battery optimizations for your app. You can help users find this option by sending them to your app’s App info page in system settings. To do so, invoke an intent that contains the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent action.

Remove a service from the foreground

To remove the service from the foreground, call stopForeground() . This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run.

If you stop the service while it’s running in the foreground, its notification is removed.

Declare foreground service types

If your app targets Android 10 (API level 29) or higher and accesses location information in a foreground service, declare the location foreground service type as an attribute of your component.

If your app targets Android 11 (API level 30) or higher and accesses the camera or microphone in a foreground service, declare the camera or microphone foreground service types, respectively, as attributes of your component.

By default, when you call startForeground() at runtime, the system allows access to each of the service types that you declare in the app manifest. You can choose to limit access to a subset of the declared service types, as shown in the code snippets within the following sections.

Example using location and camera

If a foreground service in your app needs to access the device’s location and camera, declare the service as shown in the following snippet:

At runtime, if the foreground service only needs access to a subset of the types declared in the manifest, you can limit the service’s access using the logic in the following code snippet:

Kotlin

Example using location, camera, and microphone

If a foreground service needs to access location, the camera, and the microphone, declare the service as shown in the following snippet:

At runtime, if the foreground service only needs access to a subset of the types declared in the manifest, you can limit the service’s access using the logic in the following code snippet:

Kotlin

Add foreground service types of Work Manager workers

If your app uses Work Manager and has a long-running worker that requires access to location, camera, or microphone, follow the steps to add a foreground service type to a long-running worker, and specify the additional or alternative foreground service types that your worker uses. You can choose from the following foreground service types:

Restricted access to location, camera, and microphone

To help protect user privacy, Android 11 (API level 30) introduces limitations to when a foreground service can access the device’s location, camera, or microphone. When your app starts a foreground service while the app is running in the background, the foreground service has the following limitations:

  • Unless the user has granted the ACCESS_BACKGROUND_LOCATION permission to your app, the foreground service cannot access location.
  • The foreground service cannot access the microphone or camera.

Exemptions from the restrictions

In some situations, even if a foreground service is started while the app is running in the background, it can still access location, camera, and microphone information while the app is running in the foreground («while-in-use»). In these same situations, if the service declares a foreground service type of location and is started by an app that has the ACCESS_BACKGROUND_LOCATION permission, this service can access location information all the time, even when the app is running in the background.

The following list contains these situations:

  • The service is started by a system component.
  • The service is started by interacting with app widgets.
  • The service is started by interacting with a notification.
  • The service is started as a PendingIntent that is sent from a different, visible app.
  • The service is started by an app that is a device policy controller that is running in device owner mode.
  • The service is started by an app which provides the VoiceInteractionService .
  • The service is started by an app that has the START_ACTIVITIES_FROM_BACKGROUND privileged permission.

Determine which services are affected in your app

When testing your app, start its foreground services. If a started service has restricted access to location, microphone, and camera, the following message appears in Logcat:

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Читайте также:  Как сделать сброс китайский андроид
Оцените статью