使用单个处理程序更新UI



我试图编写一个气象应用程序,根据位置给出天气状况,所有似乎都在工作,除了当位置改变时,UI不更新,我试图使用处理程序,但我不太知道如何正确使用它。

我是这样使用处理程序的:'
private final android.os.Handler handler=new android.os.Handler();
private final Runnable run = new Runnable() {
    @Override
    public void run() {
        displayLocation();
}
};
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    Toast.makeText(getApplicationContext(), "Location changed!",
            Toast.LENGTH_SHORT).show();
    handler.post(run);
}


private void displayLocation() {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    String city = null;
    String country=null;
    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
            city = address.get(0).getLocality();
            country=address.get(0).getCountryName();


            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("city",city);
            editor.putString("country", country);
            editor.commit();

        } catch (IOException e) {}
        catch (NullPointerException e) {}
    } else{
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        city =prefs.getString("city", "Austin");
       country=prefs.getString("country","TX");
        service = new YahooWeatherService(this);
        service.refreshWeather(city + ", " + country);
    }
    service = new YahooWeatherService(this);
    service.refreshWeather(city + ", " + country);
}

  @Override
public void serviceSucces(Channel channel) {
    dialog.hide();
    Item item = channel.getItem();
    int resourcesId = getResources().getIdentifier("drawable/icon_" + channel.getItem().getCondition().getCode(),
            null, getPackageName());
    @SuppressWarnings("deprecation")
    Drawable weatherIconDrawable = getResources().getDrawable(resourcesId);
    weatherIconImageView.setImageDrawable(weatherIconDrawable);
    locationTextView.setText(service.getLocation());
    conditionTextView.setText(item.getCondition().getDescription());
    temperatureTextView.setText(item.getCondition().getTemperature() + " u00B0 " + channel.getUnits().getTemperature());

}

例如,当我第一次在没有激活位置的情况下运行应用程序时,它显示默认位置"Austin, TX",但当我激活位置时,OnlocationChanged()被触发,但界面不更新

"

试试这个

  @Override
  public void onLocationChanged(Location location) {
        mLastLocation = location;
        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();
        handler.post(new Runnable() {
        @Override
        public void run() {
            displayLocation();
        }
    });
  }

最新更新