像Waze这样的应用程序如何以编程方式打开GPS?

时间:2018-01-16 12:28:24

标签: android android-gps

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

例如在Waze中显示此弹出窗口(如果您的GPS已关闭!):

enter image description here

然后点击打开GPS显示这一个:

enter image description here

GPS将自动开启! 我们怎么能像Waze那样做呢?

1 个答案:

答案 0 :(得分:2)

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

compile 'com.google.android.gms:play-services-location:11.0.4'

确保您已连接到googleApiClient,因为请拨打此代码。

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