这是我的代码,为什么它会停止?我想尝试从手机上获取GPS数据? LocationListener是问题,我不知道我的错误:/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.textView2);
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
text.setText("Bitte schlate deine GPS Funktion ein!");
return;
}
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation != null) text.setText(""+lastKnownLocation);
else {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
text.setText(""+location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
text.setText("Wird gesucht...");
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
答案 0 :(得分:0)
LocationListener
不应阻止UI线程。尝试将其放入不同的Thread/Looper
查看示例here
答案 1 :(得分:0)
请进行更改,它会起作用。
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
到
LocationManager locManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);