Я строю проект, который нуждается в текущем местоположении пользователей. Я использую обратное геокодирование, чтобы получить точный адрес пользователя. Я использую asynctask для запуска потока, который ищет точный адрес в background.This мой код:Android: обратное геокодирование - как сохранить адрес для последующего использования?
package com.prince.geolocationtest;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView text, text2, text3;
LocationManager location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String bestProvider = location.getBestProvider(criteria, true);
try {
location.requestLocationUpdates(bestProvider, 0, 0, this);
} catch (SecurityException e) {
Log.e("Permission_Exception", "Permission Not granted");
}
// text=(TextView)findViewById(R.id.textView);
text2 = (TextView) findViewById(R.id.textView2);
Toast.makeText(getApplicationContext(), "Provider=" + bestProvider, Toast.LENGTH_SHORT).show();
}
public void AddDisp(String add) {
text3 = (TextView) findViewById(R.id.textView3);
text3.setText(add);
}
@Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
AsyncTry obj = new AsyncTry(this);
obj.execute(lat, lon);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case 0:
Toast.makeText(getApplicationContext(), "Out Of Service", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "Temporarily Unavailable", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Available", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS is off", 3).show();
Intent GPSIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(GPSIntent);
}
public class AsyncTry extends AsyncTask<Double, Integer, String> {
Context context;
String add;
public AsyncTry(Context context) {
this.context = context;
}
@Override
protected String doInBackground(Double... params) {
try {
StringBuilder str = new StringBuilder();
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
if (geocoder.isPresent()) {
List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
// str.append("Address:"+addresses.get(0).getLocality());
// str.append("\n"+addresses.get(0).getAdminArea());
// //String zip = addresses.get(0).getPostalCode();
// str.append("\n"+addresses.get(0).getCountryName());
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
str.append(fetchedAddress.getAddressLine(i)).append("\n");
}
}
add = str.toString();
//str.toString();
} else {
add = "Geocoder implementation doesnt exists";
}
} catch (Exception e) {
Log.d("Exception:", e.toString());
}
MainActivity.this.runOnUiThread(new Runnable() {
Location loc;
@Override
public void run() {
// TODO Auto-generated method stub
text2.setText(add);
}
});
return add;
}
protected void onpostExecute(String result) {
// super.onPostExecute(result);
if (result != null) {
text = (TextView) findViewById(R.id.textView);
text.setText(result);
AddDisp(result);
// Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Хотя программа возвращает адрес и отображает его в основной теме, используя runOnUiThread
, я не могу отправить адрес onPostExecute
метод asyncTask
. Мне нужно использовать адрес для последующего использования, а не просто его отображение. Как я могу это сделать? Я использую IDE для Android.
Тогда как насчет метода, который я вызываю из onPostExecute с адресом в качестве параметра ?? –