Android 10 在2019年9月份正式發布,帶來了一個非常重大的GPS權限改變。為用戶提供了 僅在使用此應用時允許
。一旦用戶選擇“僅在使用此應用時允許”,就會導致APP在後台或者鎖屏時候無法正常記錄GPS軌跡,這個對像滴滴出行、共享單車、跑步軟件影響非常的大。
針對這個變化,Google也給出了新的 解決方案。
第一步:升級SDK
修改build.gradle,升級APP的 compileSdkVersion
和 targetSdkVersion
。
android { compileSdkVersion 29 defaultConfig { targetSdkVersion 29 } }
第二步:增加後台定位權限
修改 AndroidManifest.xml
文件,增加 ACCESS_BACKGROUND_LOCATION
權限,並且為對應的服務增加 android:foregroundServiceType="location"
。
<manifest > <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <application> <service android:name=".ExampleService" android:foregroundServiceType="location" /> </application></manifest>
第三步:申請後台定位權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, ACCESS_BACKGROUND_LOCATION ),101)} else { ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),101)}
通過以上方法,就可以獲取用戶是否允許APP後台定位,如果用戶不允許,就會提示下麵的對話框。