0

我想在应用程序进入后台时实现功能,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);
        }
    }
4

3 回答 3

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
    }
}

应该就是这样。我让这门课完美地在生产中工作。

于 2018-09-20T07:50:24.460 回答
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
}
于 2018-09-20T07:08:31.247 回答
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);
    }
}

希望这对你有用。

于 2018-09-20T06:26:34.857 回答