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

新手上路,请多包涵

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

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

原文由 NarasimhaKolla 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 421
2 个回答

使用以下代码进行检查。如果禁用,将生成对话框

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

原文由 Gautam 发布,翻译遵循 CC BY-SA 3.0 许可协议

private ActivityResultLauncher<IntentSenderRequest> resolutionForResult;

resolutionForResult = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(), result -> {
        if(result.getResultCode() == RESULT_OK){
            //Granted
        }else {
            //Not Granted
        }
    });

    private void enableLocationSettings() {
    LocationRequest locationRequest = LocationRequest.create()
            .setInterval(10 * 1000)
            .setFastestInterval(2 * 1000)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

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

    LocationServices
            .getSettingsClient(requireActivity())
            .checkLocationSettings(builder.build())
            .addOnSuccessListener(requireActivity(), (LocationSettingsResponse response) -> {
                // startUpdatingLocation(...);
            })
            .addOnFailureListener(requireActivity(), ex -> {
                if (ex instanceof ResolvableApiException) {
                    try{
                        IntentSenderRequest intentSenderRequest = new IntentSenderRequest.Builder(((ResolvableApiException) ex).getResolution()).build();
                        resolutionForResult.launch(intentSenderRequest);
                    }catch (Exception exception){
                        Log.d(TAG, "enableLocationSettings: "+exception);
                    }
                }
            });
}

原文由 EhtA Sham 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题