2011-11-03 47 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