位置管理器 - requestLocationUpdates 崩溃

Location Manager - requestLocationUpdates crashes

我正在尝试获取当前用户位置 - 城市,使用以下代码:

private String getCurrentLocation() {

        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locListener = new MyLocationListener();
try {
            gps_enabled = locManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = locManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

   if(!gps_enabled){
      // Show alert dialog
    }

   if (gps_enabled) {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    1000, 1, locListener,Looper.getMainLooper());
        }

        if (gps_enabled) {
            location = locManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }

        if (network_enabled && location == null) {
            locManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 1000, 1, locListener,Looper.getMainLooper());
        }

        if (network_enabled && location == null) {
            location = locManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

  Fetch city code...
...

}

因为这需要一些时间来加载我正在使用异步任务在 activity 启动时显示加载器。

private class GetLocationTask extends AsyncTask<String, Integer, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showProgress();
        }

        @Override
        protected String doInBackground(String... params) {
            return getCurrentLocation();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            onFinshGetLocationTask(result);
        }
    }

它崩溃了,所以我在请求位置更新时使用了 looper

locManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1, locListener,Looper.getMainLooper());

但应用程序仍然崩溃并提示 "Only one Looper may be created per thread"

查了很多帖还是没解决。

因为您不需要在 Asynctask 中执行此操作。只需调用它而不使用线程。它将创建自己的线程。

并尝试在没有循环器的情况下使用它。

使用这个方法

requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)

并调用 getCurrentLocation();不使用异步任务。

并且在Asynctask的doInBackGround中

@Override
        protected Object doInBackground(Object[] params) {
         Looper.prepare();
         //do your task
         Looper.myLooper().quit();

            return null;
        }