0

我建立這需要用戶的當前location.I正在使用反向地理編碼,以獲得user.I的確切地址正在使用的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。我需要使用地址供以後使用,而不是僅顯示它..我該怎麼做?我正在使用android studio IDE。

回答

0

使用SharedPreferences:

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

從SharedPreferences得到它:

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

你宣佈onPostExecute不正確。它應該是這樣的:

@Override 
protected void onPostExecute (String result); 
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); 
     } 
    } 


} 
+0

那麼我打電話從onPostExecute與地址作爲參數? –