我有一個AsyncTask
類,當調用AsyncTask
時需要獲取用戶的位置。在AsyncTask中獲取GPS位置
想法是檢查位置服務是否啓用,如果沒有,位置服務切換將彈出供用戶打開它,然後它將返回到任務繼續獲取位置並完成作業。
但是,下面的代碼在onPreExecute()
的末尾附近顯示NullPointerException
行lat = location.getLatitude();
。他們說,因爲getLastKnownLocation
沒有得到任何東西,因爲它剛剛被打開,那麼在位置服務打開後我怎麼才能找到位置?
LocationManager locationManager;
LocationListener locationListener;
double lat;
double longi;
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
location = new Location(LocationManager.NETWORK_PROVIDER);
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
//I copy the part below from the internet but seems like "onProviderDisabled" and "onLocationChanged" were never be called
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",location.getLatitude()+"_"+location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0, locationListener);
lat = location.getLatitude();
longi= location.getLongitude();
Log.v("GPS Cord CHECK",lat+"_"+longi);
}
@Override
protected String doInBackground(final Checkout_Package... params) {
//Doing the job that needs lat and longi value!
}
謝謝你的時間!
你的建議完成了這項工作。謝謝。 –