2013-05-04 25 views
0

我正在嘗試將位置輸出到textview中。 我已經使用locationManager.toString(),但它只會給我輸出[email protected]。 我想輸出像洛杉磯的位置,CA 90501.如何在Android上使用gps輸出位置

爲的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

嘗試下面的代碼

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

希望這有助於。

+0

嗯..謝謝你的回答,但我想讓嘗試和捕獲gc.getFromLocation(拉特,lon,1)? – user2349228 2013-05-05 04:53:56

+0

我不認爲我應該使用嘗試和趕上,但它會給我一個錯誤沒有它... – user2349228 2013-05-06 21:20:36

+0

是的,你是對的,更新了帖子 – CRUSADER 2013-05-07 05:53:38