如何在android中以编程方式启用位置访问?

Nar*_*lla 32 gps android location-services

我正在研究与地图相关的android应用程序,我需要在客户端开发中检查位置访问是否启用,如果未启用位置服务则显示对话框提示.

如何在android中以编程方式启用"位置访问"?

Gau*_*tam 77

使用下面的代码进行检查.如果禁用,将生成对话框

public void statusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    }
}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
Run Code Online (Sandbox Code Playgroud)

  • 我想,这不是正确的答案,因为@NarasimhaKolla想激活位置服务.首先,您需要编写真正想激活网络或GPS提供商的内容吗?此解决方案,检查是GPS激活,但如果用户已激活"仅设备"模式,该怎么办.如果用户在Wi-Fi上并且他在建筑物内,你将尝试通过GPS提供商找到位置,我认为用户永远不会收到位置,只有当用户如此靠近窗口时...我的回答:关于"移动数据"检查GPS和网络提供商,在"WiFi"检查并且仅需要网络提供商.抱歉英语:) (5认同)
  • 您不能自动将用户重定向到您的活动,但是在大多数情况下,用户将按向后按钮,如果您使用,则可以捕获该操作-startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),1); 并在onActivityResult中检查结果代码。希望它清除您的疑问 (2认同)

mak*_*ata 9

这是一种以编程方式启用位置(如地图应用程序)的简单方法:

protected void enableLocationSettings() {
       LocationRequest locationRequest = LocationRequest.create()
             .setInterval(LOCATION_UPDATE_INTERVAL)
             .setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
             .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        LocationServices
                .getSettingsClient(this)
                .checkLocationSettings(builder.build())
                .addOnSuccessListener(this, (LocationSettingsResponse response) -> {
                    // startUpdatingLocation(...);
                })
                .addOnFailureListener(this, ex -> {
                    if (ex instanceof ResolvableApiException) {
                        // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().
                            ResolvableApiException resolvable = (ResolvableApiException) ex;
                            resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                        }
                    }
                });
 }
Run Code Online (Sandbox Code Playgroud)

和 onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (REQUEST_CODE_CHECK_SETTINGS == requestCode) {
        if(Activity.RESULT_OK == resultCode){
            //user clicked OK, you can startUpdatingLocation(...);

        }else{
            //user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看文档:https : //developer.android.com/training/location/change-location-settings


ica*_*uds 6

您可以尝试以下方法:

要检查GPS和网络提供商是否已启用:

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    if (lm == null)

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // exceptions will be thrown if provider is not permitted.
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {

    }
    try {
        network_enabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }
    if (gps_enabled == false || network_enabled == false) {
        result = false;
    } else {
        result = true;
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

警报对话框,如果上面的代码返回false:

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    // Setting Dialog Title
    alertDialog.setTitle("Error!");

    // Setting Dialog Message
    alertDialog.setMessage("Please ");

    // On pressing Settings button
    alertDialog.setPositiveButton(
            getResources().getString(R.string.button_ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                }
            });

    alertDialog.show();
}
Run Code Online (Sandbox Code Playgroud)

如何使用上述两种方法:

if (canGetLocation() == true) {

    //DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED                 
} else {

    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS                                
    showSettingsAlert();

    }
Run Code Online (Sandbox Code Playgroud)

  • 如何减少代码:`return gps_enabled || network_enabled;`.另外,您可能需要遵循命名准则并使用camelCase:`return gpsEnabled || networkEnabled;` (3认同)