2011-02-17 29 views
5

我正在写一个方法,如果有GPS传感器存在并启用,将返回true,但如果没有或关闭,则返回false。这很难证明,因为...如何检查GPS传感器的存在?

hasSystemFeature("FEATURE_LOCATION_GPS") // on PackageManager 

返回false,无论设备是否具有GPS。所以即使在有一个设备的设备上,它也会打开,但它仍会返回false。似乎完全错误,但我不明白为什么。

isProviderEnabled("gps") // on LocationManager 

即使在我这里没有GPS硬件的设备上也是如此。这似乎也完全违反直觉。

我接受这些结果可能是因为我错过了一些东西,SDK不直观,或者甚至我测试的设备表现异常。

我错过了什么?

回答

13

这应该工作。在进行此调用时,logcat中是否有任何错误消息?

PackageManager pm = getPackageManager(); 
boolean hasGps = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); 
+0

没有错误,但它在根本没有GPS的设备(Advent Vega 10“非Google批准的平板电脑)上返回true。也许平板电脑被责备,并且OS被错误地设置在设备 – 2011-03-07 16:10:45

+1

那么设备开发人员必须实现一个PackageManager类,因为SDK PackageManager是抽象的,这不是设备开发人员第一次打破某些东西 – 2011-03-07 16:29:05

1

hasSystemFeature()因为FEATURE_LOCATION_GPS是恒定的参考,而不是一个字符串可能总是返回false。我相信它指向的当前字符串文字实际上是“android.hardware.location.gps”。

我相信你所寻找的是这样的:

LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
    //Ask the user to enable GPS 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Location Manager"); 
    builder.setMessage("Would you like to enable GPS?"); 
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      //Launch settings, allowing user to make a change 
      Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      startActivity(i); 
     } 
    }); 
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      //No location service, no Activity 
      finish(); 
     } 
    }); 
    builder.create().show(); 
} 

我添加了额外的有关AlertDialog指出的是,你可以采取用户直接位置设置页面,让他们启用GPS使用Settings.ACTION_LOCATION_SOURCE_SETTINGS意图操作。

希望有帮助!

2

在情况下,当设备不具有下列GPS硬件是真实的:

locationManager.getProvider(LocationManager.GPS_PROVIDER) == null; 

LocationManager locationManager = (LocationManager) AppCore.context().getSystemService(Context.LOCATION_SERVICE); 

在我的情况下,* hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)*返回true,即使设备没有GPS。所以它不可靠。