Waze之类的某些应用程序如何以编程方式打开GPS?

Ehs*_*san 2 android android-gps

我搜索了很多有关以编程方式打开GPS的信息,但没有找到任何解决方案。但是有些像Waze这样的应用程序不是系统应用程序,可以打开GPS!

例如,在显示该窗口的Waze中(如果GPS关闭!):

在此处输入图片说明

然后单击“打开GPS”将显示以下内容:

在此处输入图片说明

GPS将会自动开启!我们怎样才能像位智一样做到这一点?

Vih*_*ith 5

以下代码将显示您想要的对话框。添加以下依赖项。

compile 'com.google.android.gms:play-services-location:11.0.4'
Run Code Online (Sandbox Code Playgroud)

确保已连接到googleApiClientbefor调用此代码。

LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        builder.setAlwaysShow(true);
        Task<LocationSettingsResponse> result =
                LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
        result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
            public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                try {
                    task.getResult(ApiException.class);
                } catch (ApiException exception) {
                    switch (exception.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                ResolvableApiException resolvable = (ResolvableApiException) exception;
                                resolvable.startResolutionForResult(YourActivity.this,100);
                            } catch (IntentSender.SendIntentException e) {
                                Log.d(TAG, e.getMessage());
                            } catch (ClassCastException e) {
                                Log.d(TAG, e.getMessage());
                            }
                            break;
                    }
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的明确答复 (2认同)