如何检查定位服务是否启用? [英] How to check if Location Services are enabled?

查看:22
本文介绍了如何检查定位服务是否启用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Android 操作系统上开发应用.我不知道如何检查是否启用了定位服务.

I'm developing an app on Android OS. I don't know how to check if Location Services are enabled or not.

我需要一个方法,如果启用它们返回真",否则返回假"(所以在最后一种情况下,我可以显示一个对话框来启用它们).

I need a method that returns "true" if they are enabled and "false" if not (so in the last case I can show a dialog to enable them).

推荐答案

您可以使用下面的代码来检查是否启用了 gps provider 和 network providers.

You can use the below code to check whether gps provider and network providers are enabled or not.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

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 && !network_enabled) {
    // notify user
    new AlertDialog.Builder(context)
        .setMessage(R.string.gps_network_not_enabled)
        .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        })
        .setNegativeButton(R.string.Cancel,null)
        .show();    
}

并且在清单文件中,您需要添加以下权限

And in the manifest file, you will need to add the following permissions

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

这篇关于如何检查定位服务是否启用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆