Здравствуйте, никогда раньше не сталкивался с AsyncTask и вот подошло время. Мне нужно, в AsyncTask засунуть определение местоположения. Я делаю так:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Geolocation();
}
private void Geolocation() {
final ProgressDialog progressDialog = new ProgressDialog(this);
new AsyncTask<Void, Integer, Void>() {
private Exception m_error = null;@Override
protected void onPreExecute() {
progressDialog.setMessage("Search ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
protected void doInBackground() {
//-------------------------Местоположение---------------------------//
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
}
// обновляем progressDialog
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int)((values[0] / (float) values[1]) * 100));
};
protected void onPostExecute() {
// отображаем сообщение, если возникла ошибка
if (m_error != null) {
m_error.printStackTrace();
return;
}
// закрываем прогресс и удаляем временный файл
progressDialog.hide();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
};
}
Но почему-то не работает. Подскажите, пожалуйста. Хотя если убрать AsyncTask и вставить код между комментариями "местоположение" в OnCreate, то все будет работать, но мне нужно, чтобы оно работало в AsyncTask.
ОБНОВЛЕНО:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {//постоянное обновление.
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status, Bundle extras){ }
};
@SuppressLint("NewApi")
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.location);
String addressString = "No address found";
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getCountryName() != null) {
country_location = address.getCountryName();
}
if (address.getLocality() != null) {
city_location = address.getLocality();
}
if (address.getThoroughfare() != null) {
street_location = address.getThoroughfare();
}
if (address.getFeatureName() != null) {
house_location = address.getFeatureName();
}
geolocation.append(country_location).append(",");
geolocation.append(city_location).append(",");
geolocation.append(street_location).append(",");
geolocation.append(house_location).append(".");
}
addressString = geolocation.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
updateWithNewLocation(location);
}
myLocationText.setText(addressString);
}
ОБНОВЛЕНО 2:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_consumption);
//-------------------------Местоположение---------------------------//
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
// Location location = locationManager.getLastKnownLocation(provider);
Location location;
// updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
//-------------------------Местоположение---------------------------//
mt = new MyTask();
mt.execute();
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
@SuppressLint("NewApi")
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.location);
String addressString = "No address found";
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getCountryName() != null) {
country_location = address.getCountryName();
}
if (address.getLocality() != null) {
city_location = address.getLocality();
}
if (address.getThoroughfare() != null) {
street_location = address.getThoroughfare();
}
if (address.getFeatureName() != null) {
house_location = address.getFeatureName();
}
geolocation.append(country_location).append(",");
geolocation.append(city_location).append(",");
geolocation.append(street_location).append(",");
geolocation.append(house_location).append(".");
}
addressString = geolocation.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
updateWithNewLocation(location);
}
myLocationText.setText(addressString);
}
class MyTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
updateWithNewLocation(location);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ОБНОВЛЕНО :
private void updateWithNewLocation(Location location) {
String latLongString;
myLocationText = (TextView)findViewById(R.id.location);
String addressString = "No address found";
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
mt = new MyTask();
mt.execute(latitude,longitude);
}
}
class MyTask extends AsyncTask<Double, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Double... params) {
String addressString = "No address found";
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getCountryName() != null) {
country_location = address.getCountryName();
geolocation.append(country_location).append(",");
}
if (address.getLocality() != null) {
city_location = address.getLocality();
geolocation.append(city_location).append(",");
}
if (address.getThoroughfare() != null) {
street_location = address.getThoroughfare();
geolocation.append(street_location).append(",");
}
if (address.getFeatureName() != null) {
house_location = address.getFeatureName();
geolocation.append(house_location).append(".");
}
addressString = geolocation.toString();
}
return addressString;
}
}
protected void onPostExecute(String addressString) {
myLocationText.setText(addressString);
}
}