[譯]How to handle background services in ANDROID O?

[譯]How to handle background services in ANDROID O?

如何處理Android O的後臺Service

前段時間公司項目中作Android O的適配。在瞭解Android O新功能時,看到這個文章,雖然介紹的是Android O的預覽版,但讀了一遍感受不錯,記錄下來。順便翻譯一下(不翻譯你們確定也看得懂,只是以爲單純轉一下太low了)…android

原文地址:
How to handle background services in ANDROID O? 2017.04.02ios

Nothing makes an android developer more crazy than a new version of Android.
對於一個Android開發者來講,沒有什麼比一個新的Android版本發佈,讓人更加瘋狂了。git

Google has just revealed the DP1 of the next iteration of android: Android O. There are many new exciting features and under the hood performance improvements in the newest version of android.github

谷歌已經發布了Android O的預覽版。新版本的Android O對性能進行了提高 而且 增長了不少使人興奮的新功能。api

While others talk about what will be the name of Android O, let’s analyze this flavour of android from developer’s perspective. For android developers there are four groundbreaking changes:服務器

當你們在討論Andorid O是什麼的時候,讓咱們從開發的角度來討論一下Android O。對於開發者來講,這裏有四個突破性的變化:app

  • Background execution limits
    後臺任務限制
  • Location updates limit
    位置更新限制
  • Removing of implicit broadcasts
    移除隱式廣播
  • Notification channels
    Notification更改

Here, in this article let’s talk about background execution limitation. Background execution limitations mainly apply to two major components:less

這裏,這篇文章,讓咱們討論一下後臺服務的限制。後臺服務的限制,主要影響兩個主要的組件:socket

  • Service
  • Wakelocks

Let’s talk about the limitations applied on services in this article.
這篇文章裏,讓咱們討論後臺服務限制對 services 的影響。ide

What is the service in android?

Let’s first refresh what is the service in Android? As per the android documentation:

首先讓咱們回憶一下在Android中什麼是service 。Android API文章

A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface.

Service 不提供用戶界面,提供長時間後臺操做的一個應用程序組件。

So, fundamentally Service is the same thing as the activity but it doesn't have the UI component in it. So, it doesn't have to perform smooth animation at 60 fps. That’s why it can run perform any task for the longer period of time than the activity.

所以,從根本上講,除了沒有UI組件,Service和Actiivity在功能上是相同的。所以,Service沒必要執行60 fps的平滑刷幀動畫。這是爲何相對於Activity,Service能夠執行長時間後臺任務的緣由。

There are three types of the service:

這裏有三種類型的Service:

  • Started Service  — A service is started when an application component (such as an activity) calls startService().
    Activity經過調用startService()方法啓動Service
  • Bound Service  — A service is bound when an application component binds to it by calling bindService().
    Activity經過調用bindService()方法啓動Service
  • Scheduled Service  — A service is scheduled when an API such as the JobScheduler.
    JobScheduler

Background vs Foreground applications:

後臺應用 VS 前臺應用

To learn background execution changes, we need to know the difference between background and foreground application first.

爲了瞭解後臺運行的更改,首先咱們須要瞭解前臺應用和後臺應用的不一樣。

Rule of thumb, your application will be considered as a foreground service if any of the below three cases are true:

根據經驗,若是知足一下三個條件的任何一個,你的應用程序將被視爲前臺應用。

  • Your application has currently visible activity.
    應用當前有可見的Activity。
  • Your application has foreground service running.
    應用有正在運行的前臺Service。
  • Your application is connected to another foreground app by binding the service or by consuming their content providers.
    應用綁定了其餘前臺應用或者被其餘content providers使用。

If any of the above scenarios is not true in the current instance, your application is considered to be in the background.

若是以上三種場景,任何一個都不知足,你的應用將被視爲後臺應用。

Why do we need to restrict the use of background services?

爲何咱們要約束後臺Service的使用

Whenever your applications run in the background using services, your application consumes two precious resources:

不管任什麼時候候,應用程序使用後臺Service,都將消耗兩個珍貴的資源:

  • 1) Memory 內存
  • 2) Battery 電量

These two are limited resources on the mobile devices and most of the low to mid-range devices doesn’t have plenty of memory or battery inside it.

在大多數的中端和低端設備上,內存和電量 是不夠豐富的。

Suppose, if your application is doing some very intensive tasks in the background and using the larger amount of RAM to perform that task, then this will create the very junky user experience, especially if the user is using another resource-intensive app, such as playing a game or watching a video in foreground.

假使,若是應用程序使用不少的RAM,來運行密集的後臺任務,將會產生很是糟糕的用戶體驗。特別是用戶在使用其餘消耗資源的應用,例如:打遊戲 或 看視頻。

As per the documentation for the started service the best practice is,When the operation is complete, the service should stop itself.

根據文檔開始一個Service是最好的選擇,當操做完成時,Server應當自動中止。

But, many applications have long running background services, which basically runs for the infinite time to either maintain the socket connection with the server or monitor some tasks or user activity. These services create battery drain and also they constantly consume memory.

可是,不少的應用程序一直在運行後臺Service,這些應用程序基本上無限運行,保持與服務器套接字鏈接或監視某些任務和用戶活動。這些Service致使了電量消耗和不斷的消耗內存。

From past couple of releases of android (Starting from Marshmallow), Google is trying very hard to increase the battery life and reduce the memory consumption used by the applications by introducing the doze mode and app standby by delaying the background execution by some amount of time if the phone is idle.

從過去發佈的幾個Android版本開始(從 Marshmallow版本開發),爲了提高電池的使用壽命和減小內存的消耗,Google作了不少工做。包括引入doze模式 和 手機空閒時,延遲後臺運行服務的執行。

But most of the time despite of knowing the downsides of the long-running services developers still use them. (Mostly because it is easy to implement and maintain rather than using other workarounds.)

但大多數時候,儘管developers瞭解長時間運行後臺服務的缺點,但任然這樣使用。(主要是它容易實現和維護而不使用其餘變通方法)

What are the limitations on services starting from Android O?

從Android O開始,新增了哪些Server的限制

Starting from Android O, if your application is in the background (check above three conditions), your application is allowed to create and run background services for some minutes.

從Android O開始,若是你的應用運行在後臺(檢查以上三個條件),你的應用只容許在後臺運行幾分鐘。

After some minutes passed, your application will enter in the idle stage. When your application enteres in the idle stage, the system will stop all the background services just like your service calls Service.stopSelf().

幾分鐘以後,應用程序將進入閒置狀態。當應用程序進入閒置狀態,Andorid系統將中止後臺Service,就像Server調用了Service.stopSelf() 方法。

And here comes the fun part…

As I discussed above, the problem of battery drain and memory consumption are mainly caused by started services. To eliminate this, Android O completely prevents the use of startService() method to start the service. If you call startService() on Android O, you will end up getting IllegalArgumentException 😲.

正如前邊討論的,電量消耗和內存消耗問題主要是因爲開啓Service。爲了消除這一隱患,Android O完全阻止了startService()方法的調用。在Android O中,若是開發者調用startService()方法,將會獲得一個IllegalArgumentException異常。

There are some exceptions in these scenarios when your application is whitelisted temporarily for some time window. During this period, your application can create background services freely. The application will put into temporary whitelist under below situations:

有一些例外,在這些場景中,當應用程序白名單暫時一段時間窗口。在此期間,您的應用程序能夠自由建立背景服務。應用程序將放入臨時白名單在如下狀況:

  • When high priority FCM message received
  • Receiving a broadcas
  • Executing a PendingIntent from a notification.

How can you run background tasks?

如何執行後臺任務

If you are building a very large android application, there might be some genuine scenarios where you need to perform some tasks​ in background. Since starting a service using startService() command is not an option, we need to find out another ways​ to perform the tasks in background.

若是您正在構建一個很是大的android應用程序,可能會有一些真實的場景中,您須要執行某些任務的背景。自從startService()命令不是一個好的選擇,咱們須要找到另外一個方法來執行後臺任務。

Scheduling your tasks using Job Scheduler API:

經過Job Scheduler來運行後臺任務:


  • JobScheduler api introduced in API21 to perform background tasks.
    JobScheduler在API 21被引入,用於執行後臺任務

  • This API allows you to run scheduled service and the android system will batch all the services from different applications and run them together in some particular timeframe. The reason behind this is to reduce the amount of time your phone’s CPU and radio wakes up by batching the tasks together. This will consume less battery and maintains system health.
    這個API容許您運行後臺Service,android系統將不一樣的應用程序,在一個特定的時間段統一處理運行。這背後的機制是經過廣播喚醒CPU統一處理全部任務,減小手機CPU的消耗。這將減小電池消耗和維護系統的健康。

  • What if your application has minSdkVersion < 21? In this situation the official way to schedule the job is to use Firebase Job Dispatcher. Firebase Job Dispatcher is supported to all the way down upto API9. 若是應用程序的 `minSdkVersion<21 && minSdkVersion>19,官方的解決方案是Firebase Job Dispatcher </li> </ul> ¨K14K

    ¨K15K

    If you want some long running tasks to be performed in the background, consider using foreground services for that.None of the above background execution limitations applies to the foreground services.

    若是你想要一些長時間運行的Service在後臺執行,考慮使用前臺服務。以上services限制不適用於前臺服務。

    This will also keep your user aware that your application is performing some background tasks by displaying the ongoing notification. This will increase transparency with your user.

    經過展現notification,能夠保持後臺服務的運行。notification對用戶是可見的。

    Before Android O, if you want to create foreground service, you usually start a background service by calling startService(). Then after you can promote your service to the foreground service by assigning an ongoing notification using startForeground() method. But starting from Android O, you cannot use startService() anymore.So to create foreground service you have to use NotificationManager.startServiceInForeground(). This method is equivalent to creating background service and promoting it to the foreground service combine.

    Android O以前,若是開發者想建立前臺Service。開發者任然能夠經過調用startService()啓動一個Service,而後經過startForeground()方法建立一個正在運行的notification,將Service提高爲一個前臺Service。可是從Android O開始,startService()再也不容許被使用。所以建立前臺Service,開發者必須使用NotificationManager.startServiceInForeground(). 方法,這個方法等同於建立一個後臺Service,並將其提高爲一個前臺服務。`

    Conclusion:

    結論

    These limitations applied to the background service will definitely provide extended battery life and also lower RAM usage. Ultimately it will make your applications smooth and your user happy.

    這些適用於後臺服務的限制,確定會延長電池壽命和下降內存的消耗。最終會使應用程序平滑和提高用戶體驗。

    Should you make changes in your application code now?

    Android O is still in DP1. There are 3 more developer previews to be release before the final version of Android O gets released. There might be some API changes in upcoming releases. So, right now it’s time to think the effects of these changes in your application and think about the alternative solution for them. Once developer preview 3–4 gets released, apply those changes to your applications and make your application Android O compatible.

相關文章
相關標籤/搜索