admin 管理员组

文章数量: 887006

动手实现天气预报App(三)——切换城市手动更新+后台服务自动刷新

文章目录

  • 手动更新和后台服务自动刷新及切换城市
    • 手动更新天气
    • 切换城市
    • 后台自动更新
      • 1.使用清单文件声明服务
      • 2.创建启动服务
      • 3.启动服务
      • 4.创建绑定服务
    • 测试

手动更新和后台服务自动刷新及切换城市

手动更新天气

采用下拉刷新的来实现

<androidx.swiperefreshlayout.widget.SwipeRefreshLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/swipe_refresh"><ScrollViewandroid:id="@+id/weather_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbars="none"android:overScrollMode="never"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:fitsSystemWindows="true"><include layout="@layout/title"/><include layout="@layout/now"/><include layout="@layout/forecast"/><include layout="@layout/aqi"/><include layout="@layout/suggestion"/></LinearLayout></ScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

使用SwipeRefreshLayout将ScrollView内容包裹住,实现下拉刷新,然后需要更改WeatherActivity中的逻辑,这部分发现书中代码有些许问题,导致切换城市再刷新后仍然显示第一次缓存中的天气信息,故修改代码修复此处bug。主要是通过将WeatherId定义为一个全局变量private String mWeatherId来解决。

private String mWeatherId;@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);if (Build.VERSION.SDK_INT >= 21) {View decorView = getWindow().getDecorView();decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);getWindow().setStatusBarColor(Color.TRANSPARENT);}setContentView(R.layout.activity_weather);// 初始化各控件...swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);swipeRefresh.setColorSchemeResources(R.color.colorPrimary);drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);navButton = (Button) findViewById(R.id.nav_button);SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);String weatherString = prefs.getString("weather", null);if (weatherString != null) {// 有缓存时直接解析天气数据Weather weather = Utility.handleWeatherResponse(weatherString);mWeatherId = weather.basic.weatherId;showWeatherInfo(weather);} else {// 无缓存时去服务器查询天气mWeatherId = getIntent().getStringExtra("weather_id");weatherLayout.setVisibility(View.INVISIBLE);requestWeather(mWeatherId);}swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {@Overridepublic void onRefresh() {

本文标签: 动手实现天气预报App(三)切换城市手动更新后台服务自动刷新