我有一个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!
}
谢谢你的时间!
你的建议完成了这项工作。谢谢。 –