2011-11-07 36 views
1

我仍然在獲取android上的第一個位置時遇到問題。我使用的標準像在Android上獲取第一個位置並停止更新

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_COARSE); 
     criteria.setSpeedRequired(true); 
     String provider = lm.getBestProvider(criteria, true); 

     if(provider!=null && provider.length()>0){ 
      lm.requestLocationUpdates(provider, 0, 0, this); 
     } 

我需要停下來時,第一次像lm.removeUpdates獲得位置(本); 該放哪一行代碼?在onLocationChanged?

回答

1
public class GPSLocatorActivity extends Activity { 
    double current_lat, current_lng; 
    MapView mapView; 
    boolean flag = true; 

    /** Called when the activity is first created. */ 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     /* Use the LocationManager class to obtain GPS locations */ 

     LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     LocationListener mlocListener = new MyLocationListener(); 

     mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, 
       mlocListener); 

    } 

    /* Class My Location Listener */ 

    public class MyLocationListener implements LocationListener 

    { 


     public void onLocationChanged(Location loc) { 
      current_lat = loc.getLatitude(); 
      current_lng = loc.getLongitude(); 

      if (flag == true) { 
       flag = false; 
       go(current_lat, current_lng); 

      } 
     } 


     public void onProviderDisabled(String provider) { 
      Toast.makeText(getApplicationContext(), "Gps Disabled !!! Please Enable It.", 
        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 MyLocationListener */ 

    protected boolean isRouteDisplayed() { 
     // TODO Auto-generated method stub 
     return false; 

    public void go(double c_lat, double c_lng) { 
       System.out.println("your current Lat :: " + c_lat);  
       System.out.println("your current Lng :: " + c_lng); 

      /*turn of gps now */ 
       turnGPSOff(); 
     } 
    private void turnGPSOff() { 
     String provider = Settings.Secure.getString(getContentResolver(), 
       Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 

     if (provider.contains("gps")) { // if gps is enabled 
      final Intent poke = new Intent(); 
      poke.setClassName("com.android.settings", 
        "com.android.settings.widget.SettingsAppWidgetProvider"); 
      poke.addCategory(Intent.CATEGORY_ALTERNATIVE); 
      poke.setData(Uri.parse("3")); 
      sendBroadcast(poke); 
     } 
    } 

}/* End of UseGps Activity */ 
2

是的。將在每個位置更新上調用onLocationChanged。如果你只需要一個,你可以在那裏刪除它。

相關問題