GPS服务检查,检查设备上是启用还是禁用GPS

时间:2016-03-21 04:58:04

标签: android gps android-service android-gps

我使用Stack Overflow中的以下代码来检查设备上是启用还是禁用GPS

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }


}

它在我的设备(华为G610)上工作正常,我没有任何问题。然后我把这个应用程序交给了一个使用三星Galaxy Note的朋友,他说它没有通知是否没有启用GPS服务。

如果未启用GPS以要求用户启用它,此功能用于触发警告对话框。

我不知道为什么它不能在他的设备上工作,我们非常感谢您的帮助。我问的是它背后的原因不是在某些设备上工作而是在某些设备上工作。

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码检查位置是否已启用。我会在所有设备上工作

LocationManager location_manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        LocationListener listner = new MyLocationListener();


        boolean networkLocationEnabled = location_manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean gpsLocationEnabled = location_manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (networkLocationEnabled || gpsLocationEnabled) {

            if (location_manager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER) && networkLocationEnabled) {
                location_manager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
                location_manager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            } else if (location_manager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && gpsLocationEnabled) {
                location_manager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 2000, 2000, listner);
                location_manager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);

答案 1 :(得分:1)

试试这个。
     私人LocationManager lm;

 lm = (LocationManager)          getActivity().getSystemService(getActivity().LOCATION_SERVICE);
 if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
     Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
     startActivity(intent);
 }

你的清单文件应该设置权限 您需要的主要权限是 android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION