2

我正在尝试使用适用于 android 的 google-location 服务获取位置。

我试图从任务包中的google api中摆弄一些方法,但似乎都失败了。更准确地说,我的应用程序开始挂起。

public class LocationTask extends AsyncTask<FusedLocationProviderClient, Void, JSONObject> {

    @SuppressLint("MissingPermission")
    @Override
    protected JSONObject doInBackground(FusedLocationProviderClient... locationProviderClients) {
        WeatherApiCall weatherApiCall = new WeatherApiCall();
        Task<Location> locationTask = locationProviderClients[0].getLastLocation();
        Location location = null ;
        try {
            location = Tasks.await(locationTask);
            weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
                    String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
            return new JSONObject(weatherApiCall.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

我也尝试使用 addOnSuccessListener,但无济于事。

try {
      locationProviderClients[0].getLastLocation()
         .addOnSuccessListener(location -> {
             if (location != null) {
                Log.d("LOCATION", location.toString());
                weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
                                    String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
                        }
                    });
            return new JSONObject(weatherApiCall.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

我知道成功侦听器在任务 locationProviderClients[0].getLastLocation() 成功完成后执行操作,但我无法从任务中获取结果。

4

0 回答 0