【问题标题】:Save current location and retrieve保存当前位置并检索
【发布时间】:2016-12-15 12:38:34
【问题描述】:

大家好,正在进行地图活动。我想获取我的确切位置地址,即名称并保存并稍后检索信息。目前正在获取坐标和城市名称,任何有想法的人请协助。

    public class GetCurrentLocation extends Activity
        implements OnClickListener {

    private LocationManager locationMangaer = null;
    private LocationListener locationListener = null;

    private Button btnGetLocation = null;
    private EditText editLocation = null;
    private ProgressBar pb = null;

    private static final String TAG = "Debug";
    private Boolean flag = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_current_location);


        //if you want to lock screen for always Portrait mode
        setRequestedOrientation(ActivityInfo
                .SCREEN_ORIENTATION_PORTRAIT);

        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);

        editLocation = (EditText) findViewById(R.id.editTextLocation);

        btnGetLocation = (Button) findViewById(R.id.btnLocation);
        btnGetLocation.setOnClickListener(this);

        locationMangaer = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);

    }

    @Override
    public void onClick(View v) {
        flag = displayGpsStatus();
        if (flag) {

            Log.v(TAG, "onClick");

            editLocation.setText("Please!! move your device to" +
                    " see the changes in coordinates." + "\nWait..");

            pb.setVisibility(View.VISIBLE);
            locationListener = new MyLocationListener();

            locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

        } else {
            alertbox("Gps Status!!", "Your GPS is: OFF");
        }

    }

    /*----Method to Check GPS is enable or disable ----- */
    private Boolean displayGpsStatus() {
        ContentResolver contentResolver = getBaseContext()
                .getContentResolver();
        boolean gpsStatus = Settings.Secure
                .isLocationProviderEnabled(contentResolver,
                        LocationManager.GPS_PROVIDER);
        if (gpsStatus) {
            return true;

        } else {
            return false;
        }
    }

    /*----------Method to create an AlertBox ------------- */
    protected void alertbox(String title, String mymessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disable")
                .setCancelable(false)
                .setTitle("** Gps Status **")
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_SECURITY_SETTINGS);
                                startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /*----------Listener class to get coordinates ------------- */
    private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {

            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(), "Location changed : Lat: " +
                            loc.getLatitude() + " Lng: " + loc.getLongitude(),
                    Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " + loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " + loc.getLatitude();
            Log.v(TAG, latitude);

    /*----------to get City-Name from coordinates ------------- */
            String cityName = null;
            Geocoder gcd = new Geocoder(getBaseContext(),
                    Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(), loc
                        .getLongitude(), 1);
                if (addresses.size() > 0)
                    System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String s = longitude + "\n" + latitude +
                    "\n\nMy Currrent City is: " + cityName;
            editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider,
                                    int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }
}

【问题讨论】:

  • 抱歉不清楚你想要什么
  • Mishustin 我希望代码保存我当前的位置,然后检索保存的信息
  • 使用 SharedPreferences。到底是什么问题?
  • 该代码给出了我当前的位置,我想保存它并稍后检索它

标签: android google-maps google-maps-api-3


【解决方案1】:

存储您的纬度/经度值:

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("Latitude", Latitude).commit(); 

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("Longitude", Longitude).commit();

然后使用以下方法检索它:

PreferenceManager.getDefaultSharedPreferences(context).getString("Latitude", "No Latitude Value Stored");

PreferenceManager.getDefaultSharedPreferences(context).getString("Longitude", "No Longitude Value Stored");

【讨论】:

  • 使用单个字符串会删除除最后一个数据之外的所有数据,这可能不是 OP 需要的。
  • 是的,但我根据他要求保存他的“当前”位置做了一个假设,据我所知,这只是一组纬度/经度值。
  • "保存并稍后检索信息" 在我的解释中,这些信息不仅仅是上次保存的数据,但我可能错了......无论如何,你的答案没有错。他可以简单地调整代码或在需要时寻求帮助。
【解决方案2】:

使用共享偏好来存储您的数据。创建一个数组列表,将坐标更新到其中并保存。 Here's 共享首选项文档供参考。如果您需要代码 sn-ps 或任何解释,请随时提出。

更新

Set<String> Lats = new HashSet<String>();
Set<String> Longs = new HashSet<String>();
Lats.add(Latitude);
Longs.add(Longitude);
Context C = getApplicationContext();
SharedPreferences SP = C.getSharedPreferences("My_Prefs",MODE_PRIVATE);
SharedPreferences.Editor E = SP.edit();
E.clear();
E.putStringSet("Lats",Lats);
E.putStringSet("Longs",Longs);
E.commit();

这是在您最初保存时使用的。如果您已经保存了一对或多对,请检索旧值,然后添加新值并保存:

Context C = getApplicationContext();
SharedPreferences SP = C.getSharedPreferences("My_Prefs",MODE_PRIVATE);
Set<String> Lats = SP.getStringSet("Lats",null);
Set<String> Longs = SP.getStringSet("Longs",null);

希望我能帮上忙:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多