我想实现以下功能:当应用程序在后台运行时,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);
}
}
答案 0 :(得分:1)
尝试此解决方案
private void turnGPSOff() {
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
希望这对您有用。
答案 1 :(得分:1)
第二个解决方案是
/ ** *方法检查应用程序是否在后台 * /
fun isAppIsInBackground(context : Context) : Boolean{
var isInBackground = true
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
val runningProcesses = am.runningAppProcesses
for (processInfo in runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (activeProcess in processInfo.pkgList) {
if (activeProcess.equals(context.packageName)) {
isInBackground = false
}
}
}
}
} else {
val taskInfo = am.getRunningTasks(1)
val componentInfo = taskInfo.get(0).topActivity
if (componentInfo.packageName.equals(context.packageName)) {
isInBackground = false
}
}
return isInBackground
}
答案 2 :(得分:1)
首先,在您的Application类中,应该注册一个检测器,如下所示:
registerActivityLifecycleCallbacks(new Detector());
在检测器(它是Application.ActivityLifecycleCallbacks
的实例中)中,您应该像这样保持活动的恢复和暂停:
/**Detector class**/
@Override
public void onActivityResumed(Activity activity) {
mActivitiesResumed++;
if (mInBackground) {
mInBackground = false;
// App is in background
}
}
@Override
public void onActivityPaused(Activity activity) {
mActivitiesResumed--;
}
@Override
public void onActivityStopped(Activity activity) {
if (mActivitiesResumed == 0) {
mInBackground = true;
// App is in foreground
}
}
应该就是这样。我这堂课在生产中工作得很完美。