我创建了一个AsyncTask来检索20米精度的GPS位置。
我想执行一段时间的循环,直到精度提高为止。

问题是当我请求更新职位时出现异常。

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。

我所做的-我在其他地方读过-是添加Looper.getMainLooper()作为requestLocationUpdates()的最后一个参数。

所以,代替这个

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,activity);

你会有
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this, Looper.getMainLooper());

如果您阅读了整个FusedLocationProviderApi页面,您将看到该方法将根据参数执行不同的操作。

10-08 17:32