我无法使用下面的代码从 GPS 接收任何数据,而且我不确定自己做错了什么,似乎我的代码与我在网上看到的所有内容都匹配。我想最终将它添加到后台服务以记录 gps 坐标,即使 Activity 不可见或其他应用程序打开并且速度大于某个定义的数量,但此时我不能甚至可以显示任何数据。我是 android 的新手,但我不知道我做错了什么?
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) {}
}
}
最佳答案
您需要先使用权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
接下来你在 onCreate() 方法中使用下面的代码来访问 GPS。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 1, this);
}
现在,如果 GPS 未启用,则需要引用以下代码。详细解释可以引用how to get[DEAD LINK] [current location in android] 1教程。
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
这里我们使用 intents 将用户重定向到位置设置页面,以便他可以在位置设置下启用 GPS。
关于android - 如何使用 Android LocationManager 和 Listener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21085497/