Android定位:使用AsyncTask实现简单的一次性GPS抓取
我尝试用最后一个已知的位置更新静态变量纬度和经度 类别:Android定位:使用AsyncTask实现简单的一次性GPS抓取,android,asynchronous,gps,location,Android,Asynchronous,Gps,Location,我尝试用最后一个已知的位置更新静态变量纬度和经度 类别: class FetchGPS extends AsyncTask<String, Integer, String> { @Override protected void onPreExecute() { new_latitude = 0.0; new_longitude = 0.0; } @Override protected String d
class FetchGPS extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
new_latitude = 0.0;
new_longitude = 0.0;
}
@Override
protected String doInBackground(String... params) {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
while (new_latitude == 0.0) {
try {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
new_latitude = location.getLatitude();
new_longitude = location.getLongitude();
} catch (Exception e1) {
try {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
new_latitude = location.getLatitude();
new_longitude = location.getLongitude();
} catch (Exception e2) {
}
}
}
return null;
}
问题:GPS和MobData激活20秒后,我得到0.0和0.0
AsyncTask
子类中使用静态不是最佳实践onPostExecute()
告诉您后台任务何时完成doInBackground()
调用getActivity()
不是最佳做法public class FetchGPS extends AsyncTask<Void, Void, Double[]> {
private static final String TAG = "FetchGPS";
private LocationManager mLocationManager;
public FetchGPS(Context context) {
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
@Override
protected Double[] doInBackground(Void... params) {
Double[] coords = null;
try {
Location location = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
coords = new Double[2];
coords[0] = location.getLatitude();
coords[1] = location.getLongitude();
} catch (Exception e) {
Log.e(TAG, "could not get coordinates", e);
}
return coords;
}
}
注意:在onCreateView()
中覆盖我所做的onPostExecute()
也不是很好的做法,我只是在示例中这样做的
public class FetchGPS extends AsyncTask<Void, Void, Double[]> {
private static final String TAG = "FetchGPS";
private LocationManager mLocationManager;
public FetchGPS(Context context) {
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
@Override
protected Double[] doInBackground(Void... params) {
Double[] coords = null;
try {
Location location = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
coords = new Double[2];
coords[0] = location.getLatitude();
coords[1] = location.getLongitude();
} catch (Exception e) {
Log.e(TAG, "could not get coordinates", e);
}
return coords;
}
}
FetchGPS fetchCordinates = new FetchGPS(this) {
@Override
protected void onPostExecute(Double[] result) {
if (result != null) {
double latitude = result[0];
double longitude = result[1];
// have coordinates, continue on UI thread
} else {
// error occurred
}
}
};
fetchCordinates.execute();