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

Android:反向地理编码如何保存地址供日后使用?,android,android-asynctask,locationmanager,reverse-geocoding,Android,Android Asynctask,Locationmanager,Reverse Geocoding,我正在构建一个需要用户当前位置的项目。我正在使用反向地理编码获取用户的确切地址。我正在使用asynctask运行线程,在后台查找确切地址。这是我的代码: package com.prince.geolocationtest; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Criteria; impo

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

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();
            }

        }


    }

}
package com.prince.geolocationtest;
导入android.content.Context;
导入android.content.Intent;
导入android.location.Address;
导入android.location.Criteria;
导入android.location.Geocoder;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.AsyncTask;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.util.List;
导入java.util.Locale;
公共类MainActivity扩展AppCompatActivity实现LocationListener{
TextView文本、text2、text3;
地点经理地点;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location=(LocationManager)getSystemService(Context.location\u服务);
标准=新标准();
标准.设定准确度(标准.准确度/精细度);
标准。setAltitudeRequired(false);
标准。需要设置(假);
条件.setCostAllowed(true);
标准。设置功率要求(标准。功率低);
字符串bestProvider=location.getBestProvider(条件为true);
试一试{
RequestLocationUpdate(bestProvider,0,0,this);
}捕获(安全异常e){
Log.e(“许可\例外”、“未授予许可”);
}
//text=(TextView)findViewById(R.id.TextView);
text2=(TextView)findViewById(R.id.textView2);
Toast.makeText(getApplicationContext(),“Provider=“+bestProvider,Toast.LENGTH_SHORT).show();
}
公共void AddDisp(字符串添加){
text3=(TextView)findViewById(R.id.textView3);
text3.setText(添加);
}
@凌驾
已更改位置上的公共无效(位置){
双纬度=location.getLatitude();
double lon=location.getLongitude();
AsyncTry obj=新的AsyncTry(此);
执行对象(横向、纵向);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
开关(状态){
案例0:
Toast.makeText(getApplicationContext(),“停止服务”,Toast.LENGTH\u SHORT.show();
打破
案例1:
Toast.makeText(getApplicationContext(),“暂时不可用”,Toast.LENGTH_SHORT.show();
打破
案例2:
Toast.makeText(getApplicationContext(),“可用”,Toast.LENGTH_SHORT.show();
打破
}
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Toast.makeText(getApplicationContext(),“GPS关闭”,3.show();
Intent gpsinent=新的Intent(android.provider.Settings.ACTION\u LOCATION\u SOURCE\u Settings);
起始触觉(gpsInt);
}
公共类AsyncTry扩展了AsyncTask{
语境;
字符串添加;
公共异步尝试(上下文){
this.context=上下文;
}
@凌驾
受保护的字符串背景(双参数){
试一试{
StringBuilder str=新的StringBuilder();
Geocoder Geocoder=新的地理编码器(getBaseContext(),Locale.getDefault());
str.append(“纬度:“+params[0]+”\n长度:“+params[1]+”\n”);
if(geocoder.isPresent()){
列表地址=geocoder.getFromLocation(参数[0],参数[1],1);
//str.append(“地址:+地址.get(0.getLocation());
//str.append(“\n”+地址.get(0.getAdminArea());
////字符串zip=addresses.get(0.getPostalCode();
//str.append(“\n”+地址.get(0.getCountryName());
如果(地址!=null){
地址fetchedAddress=地址。获取(0);
对于(int i=0;i
虽然程序返回地址并使用
runOnUiThread
在主线程中显示,但我无法将地址发送到
asyncTask
onPostExecute
方法。我需要使用该地址供以后使用,而不仅仅是显示它。。我该怎么做?我正在使用android studio IDE。

使用共享参考:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
    .putString("ADDRESS", add)
    .apply();
String address = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("ADDRESS", "");
要从SharedReferences获取它,请执行以下操作:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
    .putString("ADDRESS", add)
    .apply();
String address = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("ADDRESS", "");