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

如何在android中以编程方式启用位置访问?,android,gps,location-services,Android,Gps,Location Services,我正在开发与地图相关的android应用程序,如果未启用位置服务,我需要在客户端开发中检查位置访问是否启用显示对话框提示 如何在android中以编程方式启用“位置访问”?只需签出以下线程: 它提供了一个很好的示例,说明如何检查位置服务是否已启用。使用下面的代码进行检查。如果禁用,将生成一个对话框 public void statusCheck() { final LocationManager manager = (LocationManager) getSystemService(C

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


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

只需签出以下线程:
它提供了一个很好的示例,说明如何检查位置服务是否已启用。

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

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

您可以尝试以下方法:

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

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gpsEnabled = false;
    boolean networkEnabled = false;

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

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

    try {
        networkEnabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    return gpsEnabled && networkEnabled;
}
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();
}
if (canGetLocation()) {     
    //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();
}
如果上述代码返回false,则显示警报对话框:

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gpsEnabled = false;
    boolean networkEnabled = false;

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

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

    try {
        networkEnabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    return gpsEnabled && networkEnabled;
}
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();
}
if (canGetLocation()) {     
    //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();
}
如何使用上述两种方法:

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gpsEnabled = false;
    boolean networkEnabled = false;

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

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

    try {
        networkEnabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    return gpsEnabled && networkEnabled;
}
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();
}
if (canGetLocation()) {     
    //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();
}

在最近的棉花糖更新中,即使打开了位置设置,您的应用程序也需要明确请求许可。建议的方法是显示应用程序的权限部分,用户可以根据需要在其中切换权限。执行此操作的代码段如下所示:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
    
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
} else {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean isGpsProviderEnabled, isNetworkProviderEnabled;
    isGpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isGpsProviderEnabled && !isNetworkProviderEnabled) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "coarse location permission granted");
            } else {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        }
    }
}
并覆盖
onRequestPermissionsResult
方法,如下所示:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
    
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
} else {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean isGpsProviderEnabled, isNetworkProviderEnabled;
    isGpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isGpsProviderEnabled && !isNetworkProviderEnabled) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "coarse location permission granted");
            } else {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        }
    }
}

另一种方法是,您还可以使用查询启用了哪些位置提供程序。如果未启用任何设置,您可以在应用程序中提示一个对话框来更改设置。

以下是一种以编程方式启用类似“地图”应用程序的位置的简单方法:

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

您可以在这里看到文档:

在AndroidManifest.xml中添加以下内容:


您好,上面的代码工作正常,但启用位置服务后出现了一个小问题:如何重定向我的当前页面?使用下面的意图-Intent i=new Intent(Yourclassname.this,ClassToReach.class);星触觉(i);非常感谢您分享信息。这很好。我想,这不是正确的答案,因为@NarasimhaKolla想要激活定位服务。首先,你需要写下你真正想要激活的网络或GPS提供商?这个解决方案,检查是GPS激活的,但如果用户激活了“仅设备”模式怎么办。若用户在Wi-Fi上,并且他在大楼内,你们会试图通过GPS提供商找到位置,我认为用户永远不会收到位置,只有当用户离窗户很近的时候。。。我的回答是:在“移动数据”上检查GPS和网络提供商,在“WiFi”上检查并仅要求网络提供商。抱歉,英文版:)您无法自动重定向用户以转到您的活动,但在大多数情况下,用户将按“后退”按钮,如果您使用-startActivityForResult(新意图(设置。操作位置源设置),1),您可以捕获操作在onActivityResult中检查结果代码。希望它消除您的疑虑此项目不再可用如何减少代码:
return gps|u enabled | network|u enabled。此外,您可能希望遵循命名准则并改用camelCase:
返回gpsEnabled | | networkEnabled
@MichelJung我想它将
返回启用gps和启用网络。是否授予位置权限以及是否启用位置服务是两个不同的问题!这类似于谷歌地图应用程序,显示带有“确定”和“取消”按钮的小对话框,可以在不离开应用程序的情况下启用GPS。谢谢,它正在工作。如何从对话框中禁用“不感谢”按钮?我只想限制是选择选项还是自动启用位置服务?有可能吗?@TejpalBh这种方法是不可能的!而且,你正在寻找的是一个糟糕的设计。。。