2013-07-16 52 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

它不起作用 –