我正在尝试使用google-services位置API获取最后的位置,但无济于事。我只知道有关Java和android中线程的点点滴滴,所以随时给我一些改进建议。
@Override
protected void onStart() {
super.onStart();
Thread weatherDataThread = new Thread(this::getData);
weatherDataThread.start();
try {
weatherDataThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView temperatureTextView = findViewById(R.id.temperatureLabel);
String currentText = temperatureTextView.getText().toString();
Objects.requireNonNull(weatherData);
try {
String updatedText = currentText + " " + weatherData.getJSONObject("main").getDouble("temp") + "\u00B0C";
temperatureTextView.setText(updatedText);
} catch (JSONException e) {
e.printStackTrace();
}
}
@SuppressLint("MissingPermission")
private void getData() {
String[] permissions = new String[]{Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION};
if (!checkPermissions(permissions)) {
ActivityCompat.requestPermissions(this, permissions, INTERNET_LOCATION_PERMISSIONS);
}
locationProviderClient.getLastLocation()
.addOnSuccessListener(this, location -> {
WeatherApiCall weatherApiCall = new WeatherApiCall();
String weatherResult = weatherApiCall.getWeatherResult("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
try {
weatherData = new JSONObject(weatherResult);
} catch (JSONException e) {
e.printStackTrace();
}
});
}