我想在应用程序进入后台时实现功能,GPS 应自动关闭,而当前台应用程序应自动开启时,GPS 应自动开启。我已经参考了https://stackoverflow.com/a/44668999/9635628的启用 GPS 它工作正常但是当应用程序进入后台时如何禁用?
请帮我解决它!
我试过下面的代码
class ArchLifecycleApp : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
Log.d("App", "App in background")
offGPS()
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.d("App", "App in foreground")
enableLoc()
}
}
private fun enableLoc() {
if (googleApiClient == null) {
googleApiClient = GoogleApiClient.Builder(this@MainActivity)
.addApi(LocationServices.API)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
override fun onConnected(bundle: Bundle?) {
}
override fun onConnectionSuspended(i: Int) {
googleApiClient!!.connect()
}
})
.addOnConnectionFailedListener { connectionResult -> Log.d("Location error", "Location error " + connectionResult.errorCode) }.build()
googleApiClient!!.connect()
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_NO_POWER
locationRequest.interval = (30 * 1000).toLong()
locationRequest.fastestInterval = (5 * 1000).toLong()
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
builder.setAlwaysShow(true)
val result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
result.setResultCallback(object : ResultCallback<LocationSettingsResult> {
override fun onResult(result: LocationSettingsResult) {
val status = result.status
when (status.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(this@MainActivity, REQUEST_LOCATION)
// finish()
} catch (e: IntentSender.SendIntentException) {
// Ignore the error.
}
}
}
})
}
}
fun offGPS() {
var provider = Settings.Secure.getString(contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
if (provider.contains("gps")) { //if gps is enabled
var poke: Intent = Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}