2

全部

我仔细阅读了这个网站上的许多相关问答,但没有任何帮助。这是我的代码,它在 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,但我找不到任何这些。要是知道怎么回事就万分感谢了~

4

1 回答 1

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());
于 2013-06-15T07:35:59.143 回答