2015-08-29 170 views
0

我正在測試使用Location服務的應用程序。並且,當我的定位服務關閉時,它將返回null,導致NPE (Null Pointer Exception)。所以經過一番搜索,我發現`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);`總是返回true

isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER); 

應該返回正確的boolean value但在測試我的應用程序時,它似乎總是返回true造成NPE (Null Pointer Exception)撞毀我的應用程序。

我也看過this的問題。這顯然有完全相反的問題,並試圖解決這個問題。這也沒有奏效。我正在測試三星G5。這是爲什麼發生。代碼中出現錯誤,或者有其他解決方案來解決我的問題。

下面是代碼:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    isGPSEnabled = false; 
    intentThatCalled = getIntent(); 
    String m2txt = intentThatCalled.getStringExtra("v2txt"); 
    getLocation(m2txt); 
} 
public void getLocation(String n2txt) { 
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    criteria = new Criteria(); 
    bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString(); 
    location = locationManager.getLastKnownLocation(bestProvider); 
    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER); 
    if (isGPSEnabled==true) { 
     Log.e("TAG", "GPS is on"); 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
     Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show(); 
     searchNearestPlace(n2txt); 
    } 
} 

我仍然在Android的初學者。 請幫忙。

編輯: This問題似乎有相同的硬件型號相同的問題。這是一個硬件錯誤?如果是,是否還有其他可能。我還會在其他設備Note-4上測試並通知您。

回答

1

您的問題的解決方案是從不假設你有一個位置,只是因爲你的GPS啓用並不意味着你會得到一個位置。

在任何時候你可以得到一個null的位置,所以不必擔心GPS是否啓用,你應該擔心你的位置返回是否爲空。如果沒有最後的位置

+0

我試過,但

getLastKnownLocation()可以返回一個空當我做到這一點,它要求其在加入打亂了我的應用程序的權限'ACCESS_FINE_LOCATION'。 –

+0

還有別的辦法嗎? –

+0

試過你什麼,檢查一個空?如果你想從GPS獲取數據,你需要有'ACCESS_FINE_LOCATION'權限 – tyczj