背景定位

如果你是Target Sdk 28(Android 9),再Android 10上面執行,他預設會給予你一個背景執行的權限,但當你是Android 10你就被須自己定義,自己要求權限,否則你就無法再背景時候拿取定位位置

基本的定位說明

如果背景定位可以參考github sample

另外是如果當你是Android9或是Android10,你會分別有不同的定位行為,可以參考

也就是需要修改的步驟為

Step1.

如果你的Target 28(Android 9),裝再Android 10的裝置上,你會直接被宣告

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

然後是可以再Android 10上進行背景取得定位的,但如果你是Target 29(Android 10),裝再Android 10上面,記得要自己宣告BACKGROUND_LOCATOIN,並且記得要進行 Permission Request

Step2.

另外如果你需要定義你為前景服務,需要有一個Service,而Service必須額外宣告Type

譬如原本是

<service android:name=”.LocationUpdatesService” android:enabled=”true” />

需要增加

android:exported=”true” android:foregroundServiceType=”location”

也就是會變成

<! — Foreground services in Q+ require type. → <service android:name=”.LocationUpdatesService” android:enabled=”true” android:exported=”true” android:foregroundServiceType=”location” />

可以參考官方的manifest

Step3.

另外還有一點是權限的判斷,如果你裝置相容Android below 9 or Andorid 10,你再判斷權限的時候,就必須根據目前裝置去判斷,否則再9當中會因為判斷不到BACKGROUND_PERMISSION而無法通過權限判斷

要求背景位置存取權

https://support.google.com/googleplay/android-developer/answer/9799150?hl=zh-Hant#

https://developer.android.com/about/versions/oreo/background-location-limits

背景的定義

  • It has a visible activity, whether the activity is started or paused.
  • It has a foreground service.
  • Another foreground app is connected to the app, either by binding to one of its services or by making use of one of its content providers. For example, if a foreground app binds to any of the following components within another app, that other app is considered to be in the foreground:
  • Input method editor (IME)
  • Wallpaper service
  • Notification listener
  • Voice or text service

只要是上面其中一個,你就應該不是背景程式

影響的API

Location Manager 會變成 Location updates are provided to background apps only a few times each hour.

Note: If your app needs access to location history that contains time-frequent updates, use the batched version of the Fused Location Provider API elements, such as the FusedLocationProviderApi interface. When your app is running in the background, this API receives the user's location more frequently than the non-batched API. Keep in mind, however, that your app still receives updates in batches only a few times each hour.

MAC address randomization

另外有一點跟定位無關,不過要提出的就是,Andorid再10之後預設開啟了 MAC address randomization的功能

每一次連接同一個WIFI,WIFI host都會得到不同的裝置mac address(你的手機裝置會變動)

其它唯一裝置碼無法取得

再Android 10中,有一些 imei / subscriberId /deviceId都已經會拿不到,所以也必須處理有使用到這些API的功能

https://developer.android.com/training/location/request-updates

需要再background service的manifest中增加

android:foregroundServiceType="location"

--

--

JLin

台中 / JAVA / Android /Kotlin / Kotlin Native 對於Kotlin衍生的JVM等技術 Compose for web / desktop / Ktor Server,生成式AI (Gemini/OpenAI)各式應用, 都有小興趣