我現在正在一個項目中工作,我想要獲取使用gps的用戶的當前位置。我讀過很多教程並試圖編寫代碼。該代碼在模擬器中運行良好。每當我使用DDMS發送latittude和longitude時,仿真器都會檢測到。主要問題是它不適用於真實的設備。雖然,我嘗試過的設備具有互聯網接入功能,並且GPS已打開。我已將所需的權限添加到清單文件。在Android中使用GPS獲取當前位置
public class MainActivity extends Activity {
TextView lat;
TextView lon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat=(TextView)findViewById(R.id.textView2);
lon=(TextView)findViewById(R.id.textView4);
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, ll);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class myLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null){
double pLat=location.getLatitude();
double pLong=location.getLongitude();
lat.setText(Double.toString(pLat));
lon.setText(Double.toString(pLong));
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
清單文件
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
允許我需要幫助,請。
你可以使用這個庫爲一個簡單的位置API:https://github.com/delight-im/Android-SimpleLocation – caw
@Marco W github.com/delight-im/Android-SimpleLocation工作不正常,它總是返回0.0經度和緯度。 – TejaDroid
@TejaDroid這兩個支持問題應該可以幫助你:https://github.com/delight-im/Android-SimpleLocation/issues/3和https://github.com/delight-im/Android-SimpleLocation/issues/4 – caw