如果数据库建好了那下一步我要搞什么呢?当然是根据数据库的表在本地也建一个数据类的模型呗。
我们在数据库中建了表一,省(province):
package com.coolweather.app.coolweather.model; public class Province { private int id; private String provinceName; private String provinceCode; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } }
还有一个表二,市(city):
public class City { private int id; private String cityName; private String cityCode; private int provinceId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } }
最后一个表,县(county):
package com.coolweather.app.coolweather.model; public class County { private int id; private String countyName; private String countyCode; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getCountyCode() { return countyCode; } public void setCountyCode(String countyCode) { this.countyCode = countyCode; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }建好数据,现在就有了操作对象:
他们之间的关系:
省:id 名字 代号
市:id 名字 代号 所属省id
县:id 名字 代号 所属市id
到此我们就开始业务逻辑的处理了:
先搞个广播接收,来接收来自系统的广播,接到广播开启更新服务:
public class AutoUpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AutoUpdateService.class); context.startService(i); } }
既然要开启服务,肯定要有服务这个东西嘛:
public class AutoUpdateService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { updateWeather(); } }).start(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); // int anHour = 8 * 60 * 60 * 1000; // 这是8小时的毫秒数 int anHour = 3 * 1000; // 这是8小时的毫秒数 long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AutoUpdateReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } /** * 更新天气信息。 */ private void updateWeather() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { Log.d("TAG", response); Utility.handleWeatherResponse(AutoUpdateService.this, response); } @Override public void onError(Exception e) { e.printStackTrace(); } }); } }更新就要向服务器请求数据,请求到的数据就要解柝json串:
public class Utility { /** * 解析和处理服务器返回的省级数据 */ public synchronized static boolean handleProvincesResponse( CoolWeatherDB coolWeatherDB, String response) { if (!TextUtils.isEmpty(response)) { String[] allProvinces = response.split(","); if (allProvinces != null && allProvinces.length > 0) { for (String p : allProvinces) { String[] array = p.split("\\|"); Province province = new Province(); province.setProvinceCode(array[0]); province.setProvinceName(array[1]); // 将解析出来的数据存储到Province表 coolWeatherDB.saveProvince(province); } return true; } } return false; } /** * 解析和处理服务器返回的市级数据 */ public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB, String response, int provinceId) { if (!TextUtils.isEmpty(response)) { String[] allCities = response.split(","); if (allCities != null && allCities.length > 0) { for (String c : allCities) { String[] array = c.split("\\|"); City city = new City(); city.setCityCode(array[0]); city.setCityName(array[1]); city.setProvinceId(provinceId); // 将解析出来的数据存储到City表 coolWeatherDB.saveCity(city); } return true; } } return false; } /** * 解析和处理服务器返回的县级数据 */ public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB, String response, int cityId) { if (!TextUtils.isEmpty(response)) { String[] allCounties = response.split(","); if (allCounties != null && allCounties.length > 0) { for (String c : allCounties) { String[] array = c.split("\\|"); County county = new County(); county.setCountyCode(array[0]); county.setCountyName(array[1]); county.setCityId(cityId); // 将解析出来的数据存储到County表 coolWeatherDB.saveCounty(county); } return true; } } return false; } /** * 解析服务器返回的JSON数据,并将解析出的数据存储到本地。 */ public static void handleWeatherResponse(Context context, String response) { try { JSONObject jsonObject = new JSONObject(response); JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo"); String cityName = weatherInfo.getString("city"); String weatherCode = weatherInfo.getString("cityid"); String temp1 = weatherInfo.getString("temp1"); String temp2 = weatherInfo.getString("temp2"); String weatherDesp = weatherInfo.getString("weather"); String publishTime = weatherInfo.getString("ptime"); saveWeatherInfo(context, cityName, weatherCode, temp1, temp2, weatherDesp, publishTime); } catch (JSONException e) { e.printStackTrace(); } } /** * 将服务器返回的所有天气信息存储到SharedPreferences文件中。 */ public static void saveWeatherInfo(Context context, String cityName, String weatherCode, String temp1, String temp2, String weatherDesp, String publishTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA); SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(context).edit(); editor.putBoolean("city_selected", true); editor.putString("city_name", cityName); editor.putString("weather_code", weatherCode); editor.putString("temp1", temp1); editor.putString("temp2", temp2); editor.putString("weather_desp", weatherDesp); editor.putString("publish_time", publishTime); editor.putString("current_date", sdf.format(new Date())); editor.commit(); } }
package com.coolweather.app.coolweather.util; public class HttpUtil { public static void sendHttpRequest(final String address, final com.coolweather.app.coolweather.util.HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } if (listener != null) { // 回调onFinish()方法 listener.onFinish(response.toString()); } } catch (Exception e) { if (listener != null) { // 回调onError()方法 listener.onError(e); } } finally { if (connection != null) { connection.disconnect(); } } } }).start(); } }
package com.coolweather.app.coolweather.util; public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
到这里准备工作就差不多了吧。