Java 如何检查 GPS 是否已禁用 Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34184903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:23:18  来源:igfitidea点击:

How to check if GPS is Disabled Android

javaandroidfunctiongps

提问by Bruno Albuquerque

I have two files MainActivity.java and HomeFragment.java in the MainActivity calls a function from HomeFragment that asks the user to turn on the location services on their phone. The problem is even when the user has the location feature already turned on the function is called anyway. Is there a way I can make it so only when the location feature is off that the function from the HomeFragment is launched.

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

HomeFragment.java

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

主活动.java

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

Thank you :)

谢谢 :)

采纳答案by liquidsystem

You could use something like this:

你可以使用这样的东西:

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

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

That should do the trick.

这应该够了吧。

To check if Location Services are enabled, you can use code similar to this:

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

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

Source: Marcus' Post found here

资料来源:Marcus 的帖子在这里找到