所有
我仔细阅读了本网站上的许多相关问答,但没有任何帮助。这是我的代码,它可以正常使用GPS,但一旦关闭GPS就出错了。
/**
*
* @author Jimmy Chiang
*
*/
public class GetLocationTask extends AsyncTask<Context, Void, Location> {
private OnLocationListener[] mGpsListeners;
private Location location;
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location lo) {
location = lo;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public interface OnLocationListener {
public void onLocationGot(Location location);
}
public GetLocationTask setOnLocationListener(
OnLocationListener... listeners) {
mGpsListeners = listeners;
return this;
}
@Override
protected Location doInBackground(Context... params) {
LocationManager locationManager = (LocationManager) params[0]
.getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.NETWORK_PROVIDER;
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
}
location = locationManager.getLastKnownLocation(provider);
while (location == null) {
locationManager.requestLocationUpdates(provider, 1000, 1,locationListener);
}
return location;
}
@Override
protected void onPostExecute(Location location) {
for (OnLocationListener listener : mGpsListeners) {
listener.onLocationGot(location);
}
}
}
例外情况显示:
无法在未调用的线程内创建处理程序 looper.prepare()
有些帖子显示问题应该是在UI Thread中调用someting,但我找不到任何这个。非常感谢,如果你知道发生了什么〜
答案 0 :(得分:7)
变化
locationManager.requestLocationUpdates(provider, 1000, 1,locationListener);
带
locationManager.requestLocationUpdates(provider, 1000, 1,locationListener, Looper.getMainLooper());
作为文档中的标记
Looper.getMainLooper()
返回应用程序的主循环程序,它位于主线程中 的 应用
requestLocationUpdate的looper参数是一个Looper对象,其消息队列将用于实现回调机制,或null以在调用线程上进行回调。
如果您希望AsyncTask成为将接收您必须使用的消息的
Looper.myLooper().prepare();
locationManager.requestLocationUpdates(provider, 1000, 1,locationListener, Looper.myLooper());