如何在Android上使用gps输出位置

时间:2013-05-04 07:37:03

标签: java android

我正在尝试将位置输出到textview中。 我使用了locationManager.toString(),但它只给我输出android.location.LocationManager@44ee7718。 我想输出像洛杉矶,CA 90501这样的位置。

LocationManager的代码:

LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    //conversion
    Criteria criteria = new Criteria();
    String bp = lm.getBestProvider(criteria, false);
    Location location = lm.getLastKnownLocation(bp);
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    Geocoder gc = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
        try{
            addresses = gc.getFromLocation(lat, lon, 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    Address address = addresses.get(0);
    final String ad = address.getAddressLine(0);
    //ends here

按钮的代码:

Red.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent (Intent.ACTION_VIEW);
            intent.putExtra("sms_body", ad);
            intent.setType("vnd.android-dir/mms-sms");
            startActivity(intent);
        }
    });

2 个答案:

答案 0 :(得分:2)

尝试以下代码

try {
                // Get the location manager
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                    Criteria criteria = new Criteria();
                    bestProvider = locationManager.getBestProvider(criteria, false);
                    Location location = locationManager
                            .getLastKnownLocation(bestProvider);
                    double lat = location.getLatitude();
                    double lon = location.getLongitude();
                    Geocoder gc = new Geocoder(this);
                    List<Address> lstAdd = gc.getFromLocation(lat, lon, 1);
                    Address ad = lstAdd.get(0);
                    String str = ad.getAddressLine(0);
                Toast tst = Toast.makeText(this, "Your current location is " + str,
                        Toast.LENGTH_LONG);
                tst.show();
} catch (Exception e) {
                Toast tst = Toast.makeText(this,"Please check your gps settings",
                        Toast.LENGTH_LONG);
                tst.show();
}

希望这有帮助。

答案 1 :(得分:0)

调用适当的位置方法(getLatitude(),getLongitude())

阅读本文http://developer.android.com/reference/android/location/Location.html

同样,为了转换为人类可读的名称,您需要使用GeoCoding

阅读本文http://developer.android.com/reference/android/location/Geocoder.html

此外,http://developer.android.com/training/basics/location/geocoding.html