2012-04-12 54 views
5

我可以使用isProviderEnabled()檢查GPS是否打開。如果它不在,我正在啓動意圖,以便用戶可以啓用GPS。 最後,我再次檢查GPS是否由用戶啓用。 如果用戶沒有啓用GPS並出來,仍isProviderEnabled()返回NULL。 可能是什麼問題?請指導我。GPS未啓用,但isProviderEnabled()返回true

String provider = LocationManager.GPS_PROVIDER; 
    // Check if GPS is enabled 
    boolean enabled = myLocationManager.isProviderEnabled(provider); 

    if (!enabled) { 
        // GPS not enabled 
     Log.d("", "Provider " + provider + " is not enabled"); 
     Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
     startActivity(intent); 
        // Consider the case when user does not enable GPS and come out. 
    } else { 
     Log.d("", "Provider is enabled"); 

    }  

      // Re-check if user has enabled or not. (Note: case: user has not enabled GPS) 
    enabled = myLocationManager.isProviderEnabled(provider); 
    if(!enabled) 
    { 

     Log.d("","provider not enabled"); 
    } 
      else 
      { 
        // Control is coming here though user has not enabled GPS in settings 
        Log.d("","GPS is enabled"); 
      } 

感謝, Biplab

回答

8

檢查GPS能夠使用這個代碼,讓我知道發生什麼事,

private void CheckEnableGPS(){ 
    String provider = Settings.Secure.getString(getContentResolver(), 
     Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
     if(!provider.equals("")){ 
      //GPS Enabled 
     Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider, 
      Toast.LENGTH_LONG).show(); 
     }else{ 
     Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); 
      startActivity(intent); 
     } 
    } 
+0

謝謝,這是我想要的完美。 – 2012-04-12 05:34:40

+1

沒有爲我工作,我嘗試了啓用和禁用gps,並獲得相同的敬酒兩次。 – 2012-06-26 19:42:50

+0

@BillGary這可能是因爲你的網絡或被動提供者也是活躍的。該提供商字符串應包含所有啓用的提供商,而不僅僅是GPS。他對null的檢查僅告訴我們提供者已啓用,而不是實際的。 – Guardanis 2013-12-16 21:20:34

5

我有過這樣的問題,實際的物理設備上。

我在我的物理Android設備上使用模擬位置做了一些測試,然後使用GPS切換回真實位置(代碼清理了所有模擬位置)。 這一點,無論GPS是否停止,應用程序將始終返回「真」(GPS激活),並出於某種原因不會再註冊真實位置。

在這種情況下,重新啓動物理設備解決了問題。

+0

我開始擔心我的應用程序。這有很大幫助。謝謝! 此外,有沒有辦法通過編程方式重置模擬位置?我希望確保我的應用程序的完整性,即使對於我的觀衆中有些臭名昭着的大塊。 – SlashG 2015-07-16 19:05:11

+0

我不完全確定你在問什麼,但對我來說(當我嘗試時),這是我可以重置位置的唯一方法。 – Pelpotronic 2015-07-23 19:49:14

+0

只需打開和關閉位置即可完成工作,這就是我在使用我的應用程序時所做的,只需讓用戶重新啓動他的GPS,然後使用'BroadcastReciever'確保用戶真正重新啓動它。 – Dennis 2017-09-15 06:42:04

0

有同樣的問題,即isProviderEnabled()將返回true上的設備<棒棒糖

基於user370305的答案,我更新了我的方法如下:

private boolean isLocationEnabled() { 

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 

     String provider = Settings.Secure.getString(getContentResolver(), 
       Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 

     return !provider.equals(""); 

    } else { 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     return gps || network; 

    } 

} 
相關問題