我使用以下代码请求位置更新。在单独的处理程序线程中请求位置更新,但它仍影响主线程。任何人都可以建议一个解决方案。
private LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mLongitude = location.getLongitude();
mLatitude = location.getLatitude();
mBearing = location.getBearing();
}
}
mLocationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
UPDATE_LOCATION_INTERVAL,
UPDATE_LOCATION_MINIMUM_DISTANCE,
mLocationListener, looper);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
UPDATE_LOCATION_INTERVAL,
UPDATE_LOCATION_MINIMUM_DISTANCE,
mLocationListener, looper);
答案 0 :(得分:0)
最可能的问题似乎是当你拨打Looper looper = handlerThread.getLooper();
时,活套还没有准备就绪。这最终导致looper
null,这会导致位置更新发生在主线程上。以下是getLooper()函数的更多信息。试试这个:
public class LocationThread extends HandlerThread {
private static final long UPDATE_LOCATION_INTERVAL = 0; //Set this to whatever you had it at
private static final float UPDATE_LOCATION_MINIMUM_DISTANCE = 0.0f; //Same with this
private LocationManager mLocationManager;
private LocationListener mLocationListener;
public LocationThread(String name){
super(name);
}
//Pass in your location manager and listener to this. This assumes they are not null!
public void startLocationUpdates(LocationManager locationManager, LocationListener locationListener){
mLocationManager = locationManager;
mLocationListener = locationListener;
start();
}
//Use this to stop the updates and kill the thread.
public void stopLocationUpdates(){
if(mLocationManager != null){
mLocationManager.removeUpdates(mLocationListener);
mLocationListener = null;
mLocationManager = null;
}
quit();
}
@Override
protected void onLooperPrepared() {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
UPDATE_LOCATION_INTERVAL,
UPDATE_LOCATION_MINIMUM_DISTANCE,
mLocationListener, getLooper());
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
UPDATE_LOCATION_INTERVAL,
UPDATE_LOCATION_MINIMUM_DISTANCE,
mLocationListener, getLooper());
}
}
对于此课程,请勿使用start()
或quit()
函数,因为它们已在内部使用。