2014-02-23 217 views
0

我希望能夠僅使用GPS獲取當前座標。使用GPS獲取當前位置

目前我的代碼獲取座標一次,然後一旦它們被存儲後再次使用它們。我正在尋找關於如何修改代碼的解決方案,以便單擊按鈕時獲取當前座標。

下面的代碼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //Setting TextViews for the coordinates 
    startLatitudeField = (TextView) findViewById(R.id.TextView02); 
    startLongitudeField = (TextView) findViewById(R.id.TextView04); 
    endLatitudeField = (TextView) findViewById(R.id.textView06); 
    endLongitudeField = (TextView) findViewById(R.id.textView08); 


    //Button 
    Button button = (Button) findViewById(R.id.button1); 
    button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 


      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      Criteria criteria = new Criteria(); 
      provider = locationManager.getBestProvider(criteria, false); 
      Location location = locationManager.getLastKnownLocation(provider); 
      //find out how to get the current location using gps 
      //not what is stored 

      if (startLat != 0) { 
       onLocationChanged(location); 
      } else { 
      onLocationChanged(location); 
      Button button = (Button) findViewById(R.id.button1); 
      button.setText("Get me home"); 
      } 


     } 


    }); 
}; 

@Override 
public void onLocationChanged(Location location) { 

    if (startLat == 0) { 
     startLat = (double) (location.getLatitude()); 
     startLng = (double) (location.getLongitude()); 
     startLatitudeField.setText(String.valueOf(startLat)); 
     startLongitudeField.setText(String.valueOf(startLng)); 
    } 
    else { 

     endLat = (double) (location.getLatitude()); 
     endLng = (double) (location.getLongitude()); 
     endLatitudeField.setText(String.valueOf(endLat)); 
     endLongitudeField.setText(String.valueOf(endLng)); 
    } 

} 
+0

如果您需要獲得點擊按鈕的座標,那麼爲什麼還需要'onLocationChanged'? – mangusta

+0

不確定。我正在跟隨一個指導,並將其與我擁有的一點知識結合在一起。如果我知道答案,我會說... – Bob21

回答

2

所有你需要的權限添加到清單文件的第一:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

你在這裏有答案在計算器: How do I get the current GPS location programmatically in Android?

和示例應用程序的位置: http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html

+0

感謝您的支持。我已經獲得了該許可。 – Bob21

+0

因此,示例工作? –

+0

我得到了基礎,但需要幫助讓它正常工作。 這裏是與答案,如果你想查看它的帖子:http://stackoverflow.com/questions/21988087/gps-app-runs-but-shuts-down-on-button-click?answertab =活動#標籤-最佳 – Bob21