2013-07-16 97 views
1

我有問題,我有一個按鈕,當我按下按鈕 - > button.setOnclickListener - >我會得到當前的GPS位置。但是當我沒有按下按鈕,並且我的應用程序正在運行時我想要獲取位置時,它是錯誤的。我不明白。 這是按鈕代碼如何獲取Android中的當前GPS位置?

btn.setOnClickListener(new View.OnClickListener() { 

@Override 
public void onClick(View arg0) { 
    // TODO Auto-generated method stub 
    getAdd(); 
} 

});

public void getAdd() 
{ 
    Location currentLocation = mLocationClient.getLastLocation(); 

      Geocoder geocoder = new Geocoder(context, Locale.getDefault()); 
     // Location location = params[0]; 
      List<Address> addresses = null; 
      try { 
       addresses = geocoder.getFromLocation(currentLocation.getLatitude(), 
         currentLocation.getLongitude(), 1); 
      } catch (IOException exception1) { 
       exception1.printStackTrace(); 
      } catch (IllegalArgumentException exception2) { 
       exception2.printStackTrace(); 
      } 
      if (addresses != null && addresses.size() > 0) { 
       Address address = addresses.get(0); 
       String addressText = context.getString(
         R.string.address_output_string, 
         address.getMaxAddressLineIndex() > 0 ? address 
           .getAddressLine(0) : "", 
         address.getLocality(), 
         address.getCountryName()); 
       mAddress.setText(addressText); 
      } 
} 

確實如此。但是,當我的應用程序運行時,我調用getAdd()函數。 Textview mAddress.setText(addressText)爲false。如果我按下按鈕,它就會成立。我應該怎麼做,以便在第一次運行應用程序時獲取我的地址?

+2

在onCreate()方法中運行getAdd()函數? – Razgriz

+0

是的,我想我的文本視圖setText我的地址,當應用程序運行 –

回答

0

如果我說得對,你第一次運行應用程序時顯示的地址是正確的?一種方法是調用您在onCreate()函數中創建的getAdd()函數,這樣,當您的應用程序運行時,地址將已經顯示在您的textView中。

+0

是的,我想得到我的onCreate()地址,不需要按下按鈕 –

+0

幫助我:(我無法獲得地址在我的OnCreate() –

+0

只需將'getAdd();'放在onCreate()中,最好在函數的末尾。 – Razgriz

0
public class MyLocationListener implements LocationListener { 
     public void onLocationChanged(Location location) { 
      mMap.clear(); 
      if(!mProgress.isShowing()) 
      { 
      mProgress.show(); 
      } 
      LatLng lat=new LatLng(location.getLatitude(), location.getLongitude()); 
      mopt.position(lat); 
      mopt.title("Loading...").snippet("").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lat,14.0f)); 
      myMarker=mMap.addMarker(mopt); 
      myMarker.showInfoWindow(); 

     new ReverseAddress(getBaseContext()).execute(lat); 

     } 
     public void onStatusChanged(String s, int i, Bundle b) {    
     } 
     public void onProviderDisabled(String s) { 
     } 
     public void onProviderEnabled(String s) {    
     } 
    } 

使用此方法獲取當前位置也會更改當前位置。 要使用此代碼,請使用

//  Location Manager 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATE, 
            MINIMUM_DISTANCECHANGE_FOR_UPDATE, 
            new MyLocationListener() 
        ); 
+0

它不起作用 –