我正在測試使用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上測試並通知您。
我試過,但
getLastKnownLocation()
可以返回一個空當我做到這一點,它要求其在加入打亂了我的應用程序的權限'ACCESS_FINE_LOCATION'。 –還有別的辦法嗎? –
試過你什麼,檢查一個空?如果你想從GPS獲取數據,你需要有'ACCESS_FINE_LOCATION'權限 – tyczj