Android:反向地理编码 - 如何保存地址供以后使用?

时间:2016-02-03 13:21:22

标签: android android-asynctask locationmanager reverse-geocoding

我正在构建一个需要用户当前位置的项目。我使用反向地理编码来获取用户的确切地址。我正在使用asynctask运行线程在后台找到确切的地址。这是我的代码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $THE_REMOTE_URL_YOU_ARE_POSTING_TO);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "file" => "@c:\\file_location.txt", // note the double \\ when used within double quotes
    'api_password' => 12345
  )); 
$response = curl_exec($ch);
?>

虽然程序返回地址并使用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的{​​{1}}方法。我需要使用该地址以供以后使用而不是仅仅显示它..我该怎么做?我正在使用android studio IDE。

3 个答案:

答案 0 :(得分:0)

使用SharedPreferences:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
    .putString("ADDRESS", add)
    .apply();

从SharedPreferences获取它:

String address = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("ADDRESS", "");

答案 1 :(得分:0)

您错误地声明了onPostExecute。它应该是这样的:

@Override
protected void onPostExecute (String result);

答案 2 :(得分:0)

稍微改写了你的AsyncTask。您应该将要显示地址的TexView传递给AsyncTask。它现在有效吗?

public class AsyncTry extends AsyncTask<Double, Integer, String> {

    Context context;
    TextView textView;
    String add;

    public AsyncTry(Context context, TextView textView) {
        this.context = context;
        this.textView = textView;
    }

    @Override
    protected String doInBackground(Double... params) {
        try {
            StringBuilder str = new StringBuilder();
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
            str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
            if (geocoder.isPresent()) {
                List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
                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();
            } else {
                add = "Geocoder implementation doesnt exists";
            }
        } catch (Exception e) {
            Log.d("Exception:", e.toString());
        }
        return add;
    }

    protected void onPostExecute(String result) {
        if (result != null) {
            textView.setText(result);
        }
    }


}