我沒有任何運氣使用下面的代碼從GPS接收任何數據,我不知道我做錯了什麼,它似乎像我的代碼匹配我看到的一切線上。我想最終添加到後臺服務來記錄GPS座標,即使活動不可見或其他應用程序已打開並且速度大於某個確定數量時也是如此,但此時我無法即使得到任何數據顯示。我相對較新的Android,但我無法弄清楚我做錯了什麼?如何使用Android LocationManager和監聽器
public class MainActivity extends Activity {
TextView textView;
MyLocationListener myLocationListener;
LocationManager lm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView = (TextView)findViewById(R.id.message);
addLocationListener();
}
@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;
}
private void addLocationListener()
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
final String PROVIDER = lm.getBestProvider(c, true);
this.myLocationListener = new MyLocationListener();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, this.myLocationListener);
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, myLocationListener);
Log.d("LOC_SERVICE", "Service RUNNING!");
}
public void updateLocation(Location location)
{
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
int mph = convertSpeed(location.getSpeed());
Log.d("LOC_SERVICE", "mph: "+mph);
this.textView.setText(this.textView.getText()+"\n"+"lat: "+latitude+" lng: "+longitude+" mph: "+mph);
}
private int convertSpeed(float speed) {
int mph =(int)(2.236936D * speed);
return mph;
}
class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
Log.d("LOC_SERVICE", "Listener RUNNING!");
updateLocation(location);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
我沒有看到任何錯誤,只是你需要刪除'onDestroy'中的位置監聽器。 – gunar