如何检查GPS是否已禁用Android

时间:2015-12-09 17:13:24

标签: java android function gps

我在MainActivity中有两个文件MainActivity.java和HomeFragment.java从HomeFragment调用一个函数,该函数要求用户打开手机上的位置服务。问题是即使用户已经打开了位置功能,仍然会调用该功能。有没有办法,只有当位置功能关闭时,HomeFragment的功能才会启动。

HomeFragment.java

public static void displayPromptForEnablingGPS(
        final Activity activity)
{
    final AlertDialog.Builder builder =
            new AlertDialog.Builder(activity);
    final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
    final String message = "Enable either GPS or any other location"
            + " service to find current location.  Click OK to go to"
            + " location services settings to let you do so.";


    builder.setMessage(message)
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int id) {
                            activity.startActivity(new Intent(action));
                            d.dismiss();
                        }
                    });

    builder.create().show();
}

MainActivity.java

public void showMainView() {
    HomeFragment.displayPromptForEnablingGPS(this);
}

谢谢:)

1 个答案:

答案 0 :(得分:23)

您可以使用以下内容:

final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    // Call your Alert message
}

这应该可以解决问题。

要检查是否已启用位置服务,您可以使用与此类似的代码:

String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (locationProviders == null || locationProviders.equals("")) {
...
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}

来源: 马库斯'找到帖子here