问题描述
我创建了一个AsyncTask来检索20米精度的GPS位置.我想执行一段时间的循环直到精度提高为止.
I've created a AsyncTask to retrieve a GPS position with a 20-meter accuracy.I would like to execute a while do cycle until accuracy is accetable.
问题是我请求更新职位时遇到异常.
The problem is that I got an exception when I request an update of position.
java.lang.NullPointerException: Calling thread must be a prepared Looper thread.
这是出错的代码
@Override
protected String doInBackground(Void... params) {
if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}
mLocationRequest.setInterval(100);
mLocationRequest.setPriority(100);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
while (mLastLocation == null || (mLastLocation.getAccuracy()>Float.parseFloat("20.0") && mLastLocation.hasAccuracy())){
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,activity);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
} catch (SecurityException secex) {
}
}
return null;
}
推荐答案
我在整天的工作中都遇到了麻烦.我在服务内部的后台运行了FusedLocationApi.
I had troubles with this a full work day. I have the FusedLocationApi running in background within a Service.
我所做的-我在其他地方读过-添加Looper.getMainLooper()作为requestLocationUpdates()
的最后一个参数.
What I a did -I read it somewhere else- is add Looper.getMainLooper() as the last parameter of requestLocationUpdates()
.
所以,而不是这个
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,activity);
您将拥有
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this, Looper.getMainLooper());
如果您阅读了整个 FusedLocationProviderApi 页面上,您会看到该方法将根据参数执行不同的操作.
If your read the whole FusedLocationProviderApi page, you will see that the method will do different thing depending on the parameters.
这篇关于Android:“调用线程必须是准备好的Looper线程"我使用AsyncTask时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!