2011-11-03 53 views
9

可能重复:
Programmatically find device support GPS or not?的Android检查GPS可用性

如何检查,是GPS设备上可用?

当我尝试使用下面的代码

PackageManager pm = context.getPackageManager(); 
boolean hasGps = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION); 

if (hasGps) { 
    Log.d("TAG", "HAS GPS"); 
} else { 
    Log.d("TAG", "HAS NOT GPS"); 
} 

我总是拥有GPS,但我的爱可视101IT没有GPS模块。有没有办法检查硬件GPS可用性?

回答

23

使用此代码

boolean hasGps = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); 

如果你有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(); 
} 

你可以打电话LocationManager.getAllProviders()和检查列表中是否包含LocationManager.GPS_PROVIDER

否则您只需使用此代码 LocationManager.isProviderEnabled(String provider)方法。

如果连的情况下返回false,如果客人不愿意在你的设备有GPS

+2

我有一个没有GPS的设备,但pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);总是返回True – skayred

+1

请参阅编辑并尝试 – Karthi

+1

LocationManager.isProviderEnabled(String provider)为我的平板电脑返回false,这是真的。但是,如果我的掌上电脑支持GPS,我的GPS已禁用,这也将是错误的。我需要检查硬件可用性,未启用禁用状态 – skayred

2

了Android系统GPS设置屏幕可以被称为像任何其他活动:

startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); 

检查GPS可用性使用下面的代码编码:

(活动必须实现LocationListener的)

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this); 
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER); 
+0

当我的gps关闭和打开isGPS时你的代码段总是正确的?你确定这是否检测到GPS是否有效,或者检查GPS是否可用或许可或其他? – portfoliobuilder