2012-07-31 4 views
2

휴대 기기에서 GPS 위도와 경도를 가져 오려고합니다. 아래의 코드는 작동합니다. 즉, 장치의 "무선 네트워크 사용"설정이 선택되어 있지만 "GPS 위성 사용"이 선택되어 있지 않은 경우 원하는 방식으로 모든 정보를 제공합니다. 정보.GPS로 위도와 경도 받기

void getLatitudeAndLongitude() { 
    boolean gpsEnabled = false; 
    LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    Log.e("mLocation#####", "" + mLocMan); 

    try { 
     gpsEnabled = mLocMan 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } catch (Exception ex) { 
    } 
    boolean networkEnabled = false; 
    try { 
     networkEnabled = mLocMan 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
    } catch (Exception ex) { 
    } 
    Location mCurrentLocation = null; 

    // network***************** 

    if (networkEnabled) 
     mCurrentLocation = mLocMan 
       .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

    // gps******************** 
    if (gpsEnabled) 
     mCurrentLocation = mLocMan 
       .getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    Log.d("current location", "" + mCurrentLocation); 
    LocationProvider mGpsProv = null; 

    if (mGpsProv == null && mLocMan != null) { 
     mGpsProv = mLocMan.getProvider(LocationManager.GPS_PROVIDER); 
    } 

    if (mLocMan != null) { 

     mylocationlistener mGpsLocListener = new mylocationlistener(); 
     mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
       0 /* minTime ms */, 0 /* minDistance in meters */, 
       mGpsLocListener); 
     Log.d("Provoider1", "NETWORK_PROVIDER"); 
    } 
    if (mLocMan != null && mGpsProv != null) { 

     mylocationlistener mGpsLocListener = new mylocationlistener(); 
     mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
       0 /* minTime ms /, 0/minDistance in meters */, 0, 
       mGpsLocListener); 
     Log.d("Provoider2", "GPS_PROVIDER"); 
    } 

} 

class mylocationlistener implements LocationListener { 

    @Override 
    public void onLocationChanged(Location location) { 
     if (location != null) { 

      latitude = String.valueOf(location.getLatitude()); 
      longitude = String.valueOf(location.getLongitude()); 

      Log.e("location==", "" + location); 
      Log.e("getLatitude", location.getLatitude() + ""); 
      Log.e("getLongitude", location.getLongitude() + ""); 

      if (GlobalConfig.DEBUG) 
       Log.d("setUpIndividualWork", "location==" + location); 

      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 

       } 
      }, 1000); 

      onGPSUpdate(location); 

      Geocoder gcd = new Geocoder(setUpIndividualWorkOut.this, 
        Locale.getDefault()); 
      List<Address> addresses = null; 
      try { 
       addresses = gcd.getFromLocation(location.getLatitude(), 
         location.getLongitude(), 1); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      if (addresses != null && addresses.size() > 0) { 
       userCurrentLocation = addresses.get(0).getLocality(); 
       Log.e("current location by GPS ", "" 
         + addresses.get(0).getLocality()); 
      } 
     } 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 
} 

나는 당신의 응답을 매우 감사 할 것입니다 :

여기에 코드입니다.

+0

당신이 이것을 시도 할 때 하늘에 대한 명확한 전망이 있습니까? GPS는 대개 내부에서 작동하지 않습니다. – Craigy

+0

일부 'else'를 던집니다.'networkEnabled '와'gpsEnabled '가 모두'true '이면 해당 LastKnownLocation을 두 번 가져옵니다. 또한 mLocMan 및 mGpsProv가 둘 다 null 인 경우 해당 업데이트를 두 번 요청하는 것입니다. –

답변

1

나는 이런 식으로 그것을 사용 : 클래스 LocationHelper :

public class LocationManagerHelper { 
private static final String TAG = LocationManagerHelper.class.getSimpleName(); 
private Context mContext; 

private LocationManager mLocationManager; 
private GeoUpdateHandler mLocationListener = new GeoUpdateHandler(); 

public LocationManagerHelper(Context context) { 
    this.mContext = context; 
} 


public GeoUpdateHandler GetLocationListener() { 
    return mLocationListener; 
} 

public void SetLocationManager(LocationManager locationManager) { 
    mLocationManager = locationManager; 
} 

public LocationManager GetLocationManager() { 
    return mLocationManager; 
} 


public void Stop() { 
    if (mLocationManager != null) { 
     mLocationManager.removeUpdates(mLocationListener); 
    } 
} 

private class GeoUpdateHandler implements LocationListener { 
    @Override 
    public void onLocationChanged(Location loc) { 
     String longitude = "Longitude: " + loc.getLongitude(); 
     Log.v(TAG, longitude); 
     String latitude = "Latitude: " + loc.getLatitude(); 
     Log.v(TAG, latitude); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 
    } 

    @Override 
    public void onProviderDisabled(String s) { 
    } 
} 

}

//The using: 


private LocationManagerHelper mLocationManagerHelper; 

@Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      InitializeComponent(getArguments()); 
      mLocationManagerHelper = new LocationManagerHelper(getActivity()); 

      try { 
       Criteria criteria = new Criteria(); 
       mLocationManagerHelper.SetLocationManager((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE)); 
       mLocationManagerHelper.GetLocationManager().requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, mLocationManagerHelper.GetLocationListener()); 

       String provider = mLocationManagerHelper.GetLocationManager().getBestProvider(criteria, false); 
       Location location = mLocationManagerHelper.GetLocationManager().getLastKnownLocation(provider); 

       if (location != null) { 
        mLongitude = location.getLongitude(); 
        mLatitude = location.getLatitude(); 
       } 
      } catch (Exception ex) { 
       Log.e(TAG, "GPS", ex); 
      } 
     } 
0

이 시도 ...

@Override 

public void onCreate(Bundle savedInstanceState) 

{ 

super.onCreate(savedInstanceState); 

setContentView(R.layout.main); 



LocationManager locationManager = 
(LocationManager) getSystemService(Context.LOCATION_SERVICE); 
MyLocationListener lmh = new MyLocationListener(); 

String mlocProvider; 
Criteria hdCrit = new Criteria(); 

hdCrit.setAccuracy(Criteria.ACCURACY_COARSE); 

mlocProvider = locationManager.getBestProvider(hdCrit, true); 

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1000, lmh); 
Location currentLocation = locationManager.getLastKnownLocation(mlocProvider); 

double currentLatitude = currentLocation.getLatitude(); 
double currentLongitude = currentLocation.getLongitude(); 
Log.e("lat",""+currentLatitude); 
Log.e("lng",""+currentLongitude); 
} 

public class MyLocationListener implements LocationListener 

{ 

public void onLocationChanged(Location loc) 

{ 

loc.getLatitude(); 

loc.getLongitude(); 

String Text = "My current location is:" + 

"Latitud = "+ loc.getLatitude() + 

"Longitud = " + loc.getLongitude(); 

Toast.makeText(getApplicationContext(), 

Text, 

Toast.LENGTH_SHORT).show(); 

} 



public void onProviderDisabled(String provider) 

{ 

Toast.makeText(getApplicationContext(), 

"Gps Disabled", 

Toast.LENGTH_SHORT).show(); 

} 


public void onProviderEnabled(String provider) 

{ 

Toast.makeText(getApplicationContext(), 

"Gps Enabled", 

Toast.LENGTH_SHORT).show(); 

} 



public void onStatusChanged(String provider, int status, Bundle extras) 

{ 

} 

}/* End of Class MyLocati 
0

을이 시도 :

package loca.loca; 

import java.util.Timer; 
import java.util.TimerTask; 
import android.app.Activity; 
import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.widget.Toast; 


public class LocationActivity extends Activity { 

    double x,y; 

    Timer timer; 
    LocationManager lm; 
    boolean gps_enabled = false; 
    boolean network_enabled = false; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 


      lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 



      gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
      network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 



     if (!gps_enabled && !network_enabled) { Context context = getApplicationContext(); 
      int duration = Toast.LENGTH_SHORT; 
      Toast toast = Toast.makeText(context, "nothing is enabled", duration); 
      toast.show(); 

     } 




     if (gps_enabled) 
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, 
        locationListenerGps); 
     if (network_enabled) 
      lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, 
        locationListenerNetwork); 
     timer=new Timer(); 
     timer.schedule(new GetLastLocation(), 20000); 

    } 

    LocationListener locationListenerGps = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      timer.cancel(); 
      x =location.getLatitude(); 
      y = location.getLongitude(); 
      lm.removeUpdates(this); 
      lm.removeUpdates(locationListenerNetwork); 

      Context context = getApplicationContext(); 
      int duration = Toast.LENGTH_SHORT; 
      Toast toast = Toast.makeText(context, "gps enabled "+x + "\n" + y, duration); 
      toast.show(); 
     } 

     public void onProviderDisabled(String provider) { 
     } 

     public void onProviderEnabled(String provider) { 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 
    }; 

    LocationListener locationListenerNetwork = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      timer.cancel(); 
      x = location.getLatitude(); 
      y = location.getLongitude(); 
      lm.removeUpdates(this); 
      lm.removeUpdates(locationListenerGps); 

      Context context = getApplicationContext(); 
      int duration = Toast.LENGTH_SHORT; 
      Toast toast = Toast.makeText(context, "network enabled"+x + "\n" + y, duration); 
      toast.show(); 
     } 

     public void onProviderDisabled(String provider) { 
     } 

     public void onProviderEnabled(String provider) { 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 
    }; 

    class GetLastLocation extends TimerTask { 
     @Override 
     public void run() { 
      lm.removeUpdates(locationListenerGps); 
      lm.removeUpdates(locationListenerNetwork); 

      Location net_loc=null, gps_loc=null; 
      if(gps_enabled) 
       gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      if(network_enabled) 
       net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

      //if there are both values use the latest one 
      if(gps_loc!=null && net_loc!=null){ 
       if(gps_loc.getTime()>net_loc.getTime()) 
       {x = gps_loc.getLatitude(); 
       y = gps_loc.getLongitude(); 
        Context context = getApplicationContext(); 
        int duration = Toast.LENGTH_SHORT; 
        Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration); 
        toast.show(); 
       } 
       else 
       {x = net_loc.getLatitude(); 
       y = net_loc.getLongitude(); 
       Context context = getApplicationContext(); 
       int duration = Toast.LENGTH_SHORT; 
       Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration); 
       toast.show(); 

       } 

      } 

      if(gps_loc!=null){ 
        {x = gps_loc.getLatitude(); 
       y = gps_loc.getLongitude(); 
        Context context = getApplicationContext(); 
        int duration = Toast.LENGTH_SHORT; 
        Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration); 
        toast.show(); 
        } 

      } 
      if(net_loc!=null){ 
       {x = net_loc.getLatitude(); 
       y = net_loc.getLongitude(); 
       Context context = getApplicationContext(); 
       int duration = Toast.LENGTH_SHORT; 
       Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration); 
       toast.show(); 

       } 
      } 
      Context context = getApplicationContext(); 
      int duration = Toast.LENGTH_SHORT; 
      Toast toast = Toast.makeText(context, "no last know avilable", duration); 
      toast.show(); 

} 
}} 
관련 문제