最近买了本书《Android第一行代码》,通篇看了下感觉不错,书本最后有个实战项目酷欧天气,闲来无事就照着敲了一遍代码,主要在请求天气接口和背景优化做了些小改动,现在来记录下。

(1) android studio完成代码目录结构

      

其中activity包存放天气所有活动有关的代码,db包用于存放所有数据库相关的代码,model包存放所有模型相关的代码,receiver包用于存放所有广播接收器相关的代码,service包用于存放所有服务相关的代码,util包用于存放所有工具相关的代码。

(2) 创建好数据库和表

在db包下新建一个BtWeatherOpenHelper类,这里我准备建立三张表,ProviceCityCounty,分别用于存放省、市、县,代码如下:

 public class BtWeatherOpenHelper extends SQLiteOpenHelper {

     /**
* Province表建表语句
*/
public static final String CREATE_PROVINCE = "create table Province ("
+ "id integer primary key autoincrement,"
+ "province_name text,"
+ "province_code text)"; /**
* City表建表语句
*/
public static final String CREATE_CITY = "create table City ("
+ "id integer primary key autoincrement,"
+ "city_name text, "
+ "city_code text, "
+ "province_id integer)"; /**
* County表建表语句
*/
public static final String CREATE_COUNTY = "create table County ("
+ "id integer primary key autoincrement, "
+ "county_name text, "
+ "county_code text, "
+ "city_id integer)"; public BtWeatherOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
} @Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PROVINCE); // 创建Province表
db.execSQL(CREATE_CITY); // 创建City表
db.execSQL(CREATE_COUNTY); // 创建County表
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

对于Province建表语句里,其中id是自增长主键,province_name表示省名,province_code表示省级代号;

对于City建表语句里,其中id是自增长主键,city_name表示城市名,city_code表示市级代号,province_id是City表关联Province表的外键;

对于County建表语句里,其中id是自增长主键,county_name表示县名,county_code表示县级代号,city_id是County表关联City表的外键。

接下来我们要在每张表写一个对应的实体类,这样方便我们后续的开发工作。因此,在model包下新建一个Province类,如下:

 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;
}
}

同理也在model包下新建一个City和County类,可以看到实体类的内容非常简单,基本就是生成数据库表对应字段的get和set方法就可以了。接着我们还需要创建一个BtWeatherDB类,这个类会把一些常用的数据库操作封装起来,以方便我们后面实用,代码如下:

 public class BtWeatherDB {
/**
* 数据库名
*/
public static final String DB_NAME = "Bt_weather"; /**
* 数据库版本
*/
public static final int VERSION = 1;
private static BtWeatherDB btWeatherDB;
private SQLiteDatabase db; /**
* 将构造方法私有化
*/
private BtWeatherDB(Context context){
BtWeatherOpenHelper dbHelper = new BtWeatherOpenHelper(context,DB_NAME,null,VERSION);
db = dbHelper.getWritableDatabase();
} /**
* 获取BtWeatherDB的实例
*/
public synchronized static BtWeatherDB getInstance(Context context){
if (btWeatherDB == null){
btWeatherDB = new BtWeatherDB(context);
}
return btWeatherDB;
} /**
* 将Province实例存储到数据库
*/
public void saveProvince(Province province){
if (province != null){
ContentValues values = new ContentValues();
values.put("province_name",province.getProvinceName());
values.put("province_code",province.getProvinceCode());
db.insert("Province",null,values);
}
} /**
* 从数据库获取全国所有省份信息
*/
public List<Province> loadProvince(){
List<Province> list = new ArrayList<Province>();
Cursor cursor = db.query("Province",null,null,null,null,null,null);
if (cursor.moveToFirst()){
do{
Province province = new Province();
province.setId(cursor.getInt(cursor.getColumnIndex("id")));
province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
list.add(province);
} while(cursor.moveToNext());
}
if (cursor != null){
cursor.close();
}
return list;
} /**
* 将City实例存储到数据库
*/
public void saveCity(City city){
if (city != null){
ContentValues values = new ContentValues();
values.put("city_name",city.getCityName());
values.put("city_code",city.getCityCode());
values.put("province_id",city.getProvinceId());
db.insert("City",null,values);
}
} /**
* 将数据库读取某省下所有的城市信息
*/
public List<City> loadCities(int provinceId){
List<City> list = new ArrayList<City>();
Cursor cursor = db.query("City",null,"province_id = ?",
new String[]{String.valueOf(provinceId)},null,null,null); if (cursor.moveToFirst()){
do{
City city = new City();
city.setId(cursor.getInt(cursor.getColumnIndex("id")));
city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
city.setProvinceId(provinceId);
list.add(city);
}while (cursor.moveToNext());
}
if (cursor != null){
cursor.close();
}
return list;
} /**
* 将County实例存储到数据库
*/
public void saveCounty(County county){
if (county != null){
ContentValues values = new ContentValues();
values.put("county_name",county.getCountyName());
values.put("county_code",county.getCountyCode());
values.put("city_id",county.getCityId());
db.insert("County",null,values);
}
} /**
* 从数据库读取某城市下所有的县信息
*/
public List<County> loadCounties(int cityId){
List<County> list = new ArrayList<County>();
Cursor cursor = db.query("County",null,"City_id = ?",
new String[] {String.valueOf(cityId)},null,null,null);
if (cursor.moveToFirst()){
do{
County county = new County();
county.setId(cursor.getInt(cursor.getColumnIndex("id")));
county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name")));
county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code")));
county.setCityId(cityId);
list.add(county);
} while(cursor.moveToNext());
}
if (cursor != null){
cursor.close();
}
return list;
}
}

从上面可以看到,BtWeatherDB是一个单例类,我们将它的构造方法私有化,并提供一个getInstance()方法来获取BtWeatherDB的实例,这样就可以保证全局范围内只有一个BtWeathereDB的实例。接下来我们在BtWeatherDB中提供了六组方法,saveProvince()、loadProvince()、saveCity()、loadCities()、saveCounty()、loadCounties(),分别用于存储省份数据、读取所有省份数据、存储城市数据、读取某省内所有城市数据、存储县数据、读取某市内所有县的数据。

(3) 遍历全国省市县数据

我们知道,全国省市县的数据都是通过网络请求服务器端获得的,因此这里和服务器的交互必不可少,所以我们在util包下先增加一个HttpUtil类,代码如下:

 public class HttpUtil {
public static void sendHttpRequest(final String address, final 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();
}
}

HttpUtil类中使用到了HttpCallbackListener接口来回调服务返回的结果,因此我们需要在util包下添加这个接口,如下:

 public interface HttpCallbackListener {
void onFinish(String response); void onError(Exception e);
}

另外,由于服务器返回的省市县数据都是“代号|城市,代号|城市”这种格式的,所以我们最好在提供一个工具类来解析和处理这种数据,故在util包下新建一个Utility类,代码如下:

 public class Utility {

     /**
* 解析和处理服务器返回的省级数据
*/
public synchronized static boolean handleProvinceResponse(BtWeatherDB btWeatherDB,String response){
if (!(TextUtils.isEmpty(response))){
String[] allProvince = response.split(",");
if (allProvince != null && allProvince.length > 0){
for (String p : allProvince){
String[] array = p.split("\\|");
Province province = new Province();
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
// 将解析出来的数据存储到Province类
btWeatherDB.saveProvince(province);
}
return true;
}
}
return false;
} /**
* 解析和处理服务器返回的市级数据
*/
public static boolean handleCitiesResponse(BtWeatherDB btWeatherDB,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类
btWeatherDB.saveCity(city);
}
return true;
}
}
return false;
} /**
* 解析和处理服务器返回的县级数据
*/
public static boolean handleCountiesResponse(BtWeatherDB btWeatherDB,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);
btWeatherDB.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();
}
} /**
* 将服务器返回的所有的天气信息存储到SharePreferences文件中
*/
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.CANADA);
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();
}
}

可以看到,我们提供了 handleProvinceResponse()、handleCitiesResponse()、handleCountiesResponse()、handleWeatherResponse()、saveWeatherInfo()这五个方法,分别用于解析和处理服务器返回的省级、市级、县级数据,用于JSON格式的天气信息解析出来和保存天气信息到文件里。

然后我们写下界面,在res/layout目录中新建choose_area.xml布局,代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#484E61"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp"
android:id="@+id/title_text"/>
</RelativeLayout> <ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_view">
</ListView> </LinearLayout>

接下来最关键一步,就是要编写用于遍历省市县数据的活动了,在activity包下新建ChooseAreaActivity继承于Activity,代码如下:

 public class ChooseAreaActivity extends Activity {

     public static final String TAG = ChooseAreaActivity.class.getSimpleName();
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private BtWeatherDB btWeatherDB;
private List<String> dataList = new ArrayList<String>(); // 省列表
private List<Province> provinceList; // 市列表
private List<City> cityList; // 县列表
private List<County> countyList; // 选中的省份
private Province selectedProvince; // 选中的城市
private City selectedCity; // 当前选中的级别
private int currentLevel; /**
* 是否从WeatherActivity中跳转过来
*/
private boolean isFromWeatherActivity; protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity",false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// 已经选择了城市且不是从WeatherActivity跳转过来,才会直接跳转到WeatherActivity
if (prefs.getBoolean("city_selected",false) && !isFromWeatherActivity){
Intent intent = new Intent(this,WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView = (ListView)findViewById(R.id.list_view);
titleText = (TextView)findViewById(R.id.title_text);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
btWeatherDB = BtWeatherDB.getInstance(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE){
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY){
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY){
String countyCode = countyList.get(position).getCountyCode();
Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class);
intent.putExtra("county_code",countyCode);
startActivityForResult(intent,1);
}
}
});
queryProvinces(); // 加载省级数据
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode){
case RESULT_OK:
break;
default:
break;
}
} /**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces(){
provinceList = btWeatherDB.loadProvince();
if (provinceList.size() > 0){
dataList.clear();
for (Province province : provinceList){
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("中国");
currentLevel = LEVEL_PROVINCE;
} else {
queryFromServer(null,"province");
}
} /**
* 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器查询
*/
private void queryCities(){
cityList = btWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0){
dataList.clear();
for (City city : cityList){
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
} else {
queryFromServer(selectedProvince.getProvinceCode(),"city");
}
} /**
* 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器查询
*/
private void queryCounties(){
countyList = btWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0){
dataList.clear();
for (County county : countyList){
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
} else {
queryFromServer(selectedCity.getCityCode(),"county");
}
} /**
* 根据传入的代号和类型从服务器上查询省市县数据
*/
private void queryFromServer(final String code ,final String type){
String address;
if (!TextUtils.isEmpty(code)){
address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
} else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = false;
if ("province".equals(type)){
result = Utility.handleProvinceResponse(btWeatherDB,response);
} else if ("city".equals(type)){
result = Utility.handleCitiesResponse(btWeatherDB,response,selectedProvince.getId());
} else if ("county".equals(type)){
result = Utility.handleCountiesResponse(btWeatherDB,response,selectedCity.getId());
}
if (result){
// 通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)){
queryProvinces();
} else if ("city".equals(type)){
queryCities();
} else if ("county".equals(type)){
queryCounties();
}
}
});
}
} @Override
public void onError(Exception e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this,"加载失败",Toast.LENGTH_SHORT).show();
}
});
}
});
} /**
* 显示进度对话框
*/
private void showProgressDialog(){
if (progressDialog == null){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
} /**
* 关闭进度对话框
*/
private void closeProgressDialog(){
if (progressDialog != null){
progressDialog.dismiss();
}
} /**
* 捕获Back键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出
*/
public void onBackPressed(){
if (currentLevel == LEVEL_COUNTY){
queryCities();
} else if (currentLevel == LEVEL_CITY){
queryProvinces();
} else {
finish();
}
} }

这个类里面代码比较多,可以逻辑并不复杂,首先onCreate()方法中先是获取一些控件的实例,然后去初始化ArrayAdapter,将它设置为ListView的适配器。之后又去获取到了BtWeatherDB的实例,并给ListView设置了点击事件,到这里我们的初始化工作就算是完成了。在onCreate()方法的最后,调用了queryProvince()方法,也就是从这里开始加载省级数据。queryProvince()方法的内部会首先调用BtWeatherDB的loadProvince()方法来从数据库中读取省级数据,如果读取到了就直接将数据显示到桌面上,如果没有读取到就调用queryFromServer()方法来从服务器上查询数据。

queryFromServer()方法会先根据传入的参数来拼装查询地址,确定了查询地址之后,接下来就调用HttpUtil的sendHttpRequest()方法来向服务器发送请求,响应的数据会回调到onFinish()方法中,然后我们在这里去调用Utility的handleProvinceResponse()方法来解析和处理服务器返回的数据,并存储到数据库中。接下来在解析和处理完数据之后,我们再次调用了queryProvince()方法来重新加载省级数据,由于queryProvince()方法牵扯到了UI操作,因此必须要在主线程中调用,这里借助了runOnUiThread()方法来实现从子线程切换到主线程,它的实现原理其实也是基于异步消息处理机制的。现在数据库中已经存在了数据,因此调用queryProvince()就会直接将数据显示到界面上。当你点击某个省的时候会进入到ListView的onItemClick()方法中,这个时候会根据当前的级别来判断去调用queryCities()方法还是queryCounties()方法,queryCities方法查询市级数据,而queryCounties()方法是查询县级数据。至于onBackPressed()方法来覆盖默认Back键的行为,这里会根据当前的级别来判断返回市级列表、省级列表,还是直接退出。

(4) 显示天气信息

在res/layout目录中新建weather_layout.xml,代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#484E61"> <Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="@drawable/home"
android:id="@+id/switch_city"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp"
android:id="@+id/city_name"/> <Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginRight="16dp"
android:layout_marginTop="10dp"
android:background="@drawable/refresh"
android:id="@+id/refresh_weather"/>
</RelativeLayout> <RelativeLayout
android:id="@+id/weather_background"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#27A5F9"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textColor="#FFF"
android:textSize="18sp"
android:id="@+id/publish_text"/> <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:id="@+id/weather_info_layout"> <TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center"
android:textColor="#FFF"
android:textSize="18sp"
android:id="@+id/current_date"/> <TextView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textColor="#FFF"
android:textSize="40sp"
android:id="@+id/weather_desp"/> <LinearLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#FFF"
android:textSize="40sp"
android:id="@+id/temp1"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="~"
android:textColor="#FFF"
android:textSize="40sp"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#FFF"
android:textSize="40sp"
android:id="@+id/temp2"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </LinearLayout>

接下来在activity包下新建WeatherActivity继承自Activity,这里要注意一点书中提供访问天气代号接口已经失效了, 就是这个地址"http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"已经不能访问了,另外通过天气代号查询天气信息地址也要改为"http://www.weather.com.cn/adat/cityinfo/*/.html",不过我想到另外方法那就是下载个本地数据库有县级所对应的天气代号就可以获得天气信息,在网上找了很久,终于找到比较全的有城市对应天气代号数据库文件,(数据库文件我放在res自己创建raw目录下),如下图:

我们可以查询城市CITY_ID找到对应的WEATHER_ID得到天气代号,代码如下:

  /**
* 从数据库读取县对应的天气代号
*/
private String initWeatherData(final String wt_id) {
String weatherdata = null;
String result_str = null;
String selection = "CITY_ID=?" ;
String[] selectionArgs = new String[]{ wt_id };
// 导入外部数据库复制到手机内存
copyDataBase(); Cursor cursor = db.query("city_table",new String[]{"WEATHER_ID"},selection, selectionArgs, null, null, null);
while (cursor.moveToNext()){
weatherdata = cursor.getString(0);
if (wt_id == weatherdata){
break;
}
}
result_str = weatherdata;
return result_str;
} /**
* 复制工程raw目录下数据库文件到手机内存里
*/
private void copyDataBase() {
try {
String weatherfileName = getCacheDir() + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
if (!dir.exists()) {
dir.mkdir();
}
try {
InputStream is = this.getResources().openRawResource(R.raw.citychina);
FileOutputStream fos = new FileOutputStream(weatherfileName);
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
// 根据数据库文件路径打开数据库
db = SQLiteDatabase.openOrCreateDatabase(
weatherfileName, null);
if (db != null) {
KLog.v(TAG,"db build success!");
} else {
KLog.v(TAG,"db build failed!");
}
} catch (Exception e) {
e.printStackTrace();
}
}

 附数据库文件下载地址http://download.csdn.net/detail/wofa1648/9564085

 (5) 切换城市和手动更新天气

首先在布局中加入切换城市和更新天气的按钮,初始化后再修改WeatherActivity中代码,如下:

 public void onClick(View v) {
switch (v.getId()) {
case R.id.switch_city:
Intent intent = new Intent(this, ChooseAreaActivity.class);
intent.putExtra("from_weather_activity", true);
startActivity(intent);
finish();
break;
case R.id.refresh_weather:
publishText.setText("同步中...");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String weatherCode = prefs.getString("weather_code", "");
if (!TextUtils.isEmpty(weatherCode)) {
queryWeatherChangeInfo(weatherCode);
}
else {
publishText.setText("今天" + prefs.getString("publish_time", "") + "发布");
}
}
},3000);
break;
default:
break;
}
}

(6) 后台自动更新天气

首先在service包下新建一个AutoUpdateService继承自Service,代码如下:

 public class AutoUpdateService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
} 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小时的毫秒数
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/adat/cityinfo/" + "weatherCode" + ".html";
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Utility.handleWeatherResponse(AutoUpdateService.this,response);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}

可以看到,在onStartCommand()方法中先是开启了一个子线程,然后在子线程中调用updateWeather()方法来更新天气,我们仍然会将服务器返回的天气数据交给Utility的handleWeatherResponse()方法去处理,这样就可以把最新的天气信息存储到SharedPreferences文件中,为了保证软件不会消耗过多的流量,这里将时间间隔设置为8小时,8小时后就应该执行到AutoUpdateReceiver的onReceive()方法中了,在receiver包下新建AutoUpdateReceiver继承自BroadcastReceiver,代码如下:

 public class AutoUpdateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
Intent i = new Intent(context, AutoUpdateService.class);
context.startService(i);
}
}

这里只是在onReceive()方法中再次去启动AutoUpdateService,就可以实现后台定时更新的功能了。不过我们还需要在代码某处去激活AutoUpdateService这个服务才行,继续修改WeatherActivity代码:

 private void showWeather() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
cityNameText.setText(prefs.getString("city_name", ""));
temp1Text.setText(prefs.getString("temp1", ""));
temp2Text.setText(prefs.getString("temp2", ""));
weatherDespText.setText(prefs.getString("weather_desp", ""));
publishText.setText("今天" + prefs.getString("publish_time", "") + "发布");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String date = sdf.format(new java.util.Date());
nowTime = date;
currentDateText.setText(nowTime);
WeatherKind myWeather = weather_kind.get(weatherDesp);
if (myWeather != null) {
changeBackground(myWeather);
} else {
changeBackground(WeatherKind.allwt);
}
currentDateText.setVisibility(View.VISIBLE);
weatherInfoLayout.setVisibility(View.VISIBLE);
cityNameText.setVisibility(View.VISIBLE);
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
}

最后记得在AndroidManifest.xml中注册新增的服务和广播接收器,如下:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.weather.app.btweather"> <application
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".activity.ChooseAreaActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity> <activity android:name=".activity.WeatherActivity"></activity> <service android:name=".service.AutoUpdateService"></service>
<receiver android:name=".receiver.AutoUpdateReceiver"></receiver>
</application> <uses-permission android:name="android.permission.INTERNET"/> </manifest>

 (7) 优化软件界面

打开软件,我们切换不同城市,发现软件背景都一样感觉好丑,所以我们来修改程序做到可以根据不同的天气情况自动切换背景图,修改WeatherActivity代码,如下:

 /**
* 枚举各种天气情况
*/
private enum WeatherKind {
cloudy, fog, hailstone, light_rain, moderte_rain, overcast, rain_snow, sand_storm, rainstorm,
shower_rain, snow, sunny, thundershower,allwt;
} private static Map<String,WeatherKind> weather_kind = new HashMap<String,WeatherKind>();
static {
weather_kind.put("多云",WeatherKind.cloudy);
weather_kind.put("雾", WeatherKind.fog);
weather_kind.put("冰雹", WeatherKind.hailstone);
weather_kind.put("小雨", WeatherKind.light_rain);
weather_kind.put("中雨",WeatherKind.moderte_rain);
weather_kind.put("阴",WeatherKind.overcast);
weather_kind.put("雨加雪",WeatherKind.rain_snow);
weather_kind.put("沙尘暴",WeatherKind.sand_storm);
weather_kind.put("暴雨",WeatherKind.rainstorm);
weather_kind.put("阵雨",WeatherKind.shower_rain);
weather_kind.put("小雪",WeatherKind.snow);
weather_kind.put("晴",WeatherKind.sunny);
weather_kind.put("雷阵雨",WeatherKind.thundershower);
weather_kind.put("晴转阴",WeatherKind.allwt);
weather_kind.put("晴转多云",WeatherKind.allwt);
weather_kind.put("晴转小雨",WeatherKind.allwt);
weather_kind.put("晴转中雨",WeatherKind.allwt);
weather_kind.put("晴转大雨",WeatherKind.allwt);
weather_kind.put("晴转阵雨",WeatherKind.allwt);
weather_kind.put("晴转雷阵雨",WeatherKind.allwt);
weather_kind.put("晴转小雪",WeatherKind.allwt);
weather_kind.put("晴转中雪",WeatherKind.allwt);
weather_kind.put("晴转大雪",WeatherKind.allwt);
weather_kind.put("阴转晴",WeatherKind.allwt);
weather_kind.put("阴转多云",WeatherKind.allwt);
weather_kind.put("阴转小雨",WeatherKind.allwt);
weather_kind.put("阴转中雨",WeatherKind.allwt);
weather_kind.put("阴转大雨",WeatherKind.allwt);
weather_kind.put("阴转阵雨",WeatherKind.allwt);
weather_kind.put("阴转雷阵雨",WeatherKind.allwt);
weather_kind.put("阴转小雪",WeatherKind.allwt);
weather_kind.put("阴转中雪",WeatherKind.allwt);
weather_kind.put("阴转大雪",WeatherKind.allwt);
weather_kind.put("多云转晴",WeatherKind.allwt);
weather_kind.put("多云转阴",WeatherKind.allwt);
weather_kind.put("多云转小雨",WeatherKind.allwt);
weather_kind.put("多云转中雨",WeatherKind.allwt);
weather_kind.put("多云转大雨",WeatherKind.allwt);
weather_kind.put("多云转阵雨",WeatherKind.allwt);
weather_kind.put("多云转雷阵雨",WeatherKind.allwt);
weather_kind.put("多云转小雪",WeatherKind.allwt);
weather_kind.put("多云转中雪",WeatherKind.allwt);
weather_kind.put("多云转大雪",WeatherKind.allwt);
weather_kind.put("小雨转晴",WeatherKind.allwt);
weather_kind.put("小雨转阴",WeatherKind.allwt);
weather_kind.put("小雨转多云",WeatherKind.allwt);
weather_kind.put("小雨转中雨",WeatherKind.allwt);
weather_kind.put("小雨转大雨",WeatherKind.allwt);
weather_kind.put("中雨转小雨",WeatherKind.allwt);
weather_kind.put("中雨转大雨",WeatherKind.allwt);
weather_kind.put("大雨转中雨",WeatherKind.allwt);
weather_kind.put("大雨转小雨",WeatherKind.allwt);
weather_kind.put("阵雨转小雨",WeatherKind.allwt);
weather_kind.put("阵雨转中雨",WeatherKind.allwt);
weather_kind.put("阵雨转多云",WeatherKind.allwt);
weather_kind.put("阵雨转晴",WeatherKind.allwt);
weather_kind.put("阵雨转阴",WeatherKind.allwt);
weather_kind.put("中雪转小雪",WeatherKind.allwt);
weather_kind.put("中雪转大雪",WeatherKind.allwt);
weather_kind.put("小雪转大雪",WeatherKind.allwt);
weather_kind.put("小雪转中雪",WeatherKind.allwt);
weather_kind.put("小雪转晴",WeatherKind.allwt);
weather_kind.put("小雪转阴",WeatherKind.allwt);
weather_kind.put("小雪转多云",WeatherKind.allwt);
weather_kind.put("大雪转小雪",WeatherKind.allwt);
weather_kind.put("大雪转中雪",WeatherKind.allwt);
weather_kind.put("雾转小雨",WeatherKind.allwt);
weather_kind.put("雾转中雨",WeatherKind.allwt);
weather_kind.put("雾转大雨",WeatherKind.allwt);
}
 /**
* 设置对应天气背景图
*/
private void changeBackground(WeatherKind weather){
view = findViewById(R.id.weather_background);
switch (weather){
case cloudy:
view.setBackgroundResource(R.drawable.cloudy);
break;
case fog:
view.setBackgroundResource(R.drawable.fog);
break;
case hailstone:
view.setBackgroundResource(R.drawable.hailstone);
break;
case light_rain:
view.setBackgroundResource(R.drawable.light_rain);
break;
case moderte_rain:
view.setBackgroundResource(R.drawable.moderte_rain);
break;
case overcast:
view.setBackgroundResource(R.drawable.overcast);
break;
case rain_snow:
view.setBackgroundResource(R.drawable.rain_snow);
break;
case sand_storm:
view.setBackgroundResource(R.drawable.sand_storm);
break;
case rainstorm:
view.setBackgroundResource(R.drawable.rainstorm);
break;
case shower_rain:
view.setBackgroundResource(R.drawable.shower_rain);
break;
case snow:
view.setBackgroundResource(R.drawable.snow);
break;
case sunny:
view.setBackgroundResource(R.drawable.sunny);
break;
case thundershower:
view.setBackgroundResource(R.drawable.thundershower);
break;
case allwt:
view.setBackgroundResource(R.drawable.allwt);
break;
default:
break;
}
}

 (8) 效果显示

        

       

69.Android之天气预报app的更多相关文章

  1. android入门学习-天气预报app(一)

    引言 学习<android第一行代码>根据书本开发的天气预报app,主要用于熟练操作android开发(android studio3.0平台). 今天主要分享一下从服务器上获取天气信息, ...

  2. 基于Android开发的天气预报app(源码下载)

    原文:基于Android开发的天气预报app(源码下载) 基于AndroidStudio环境开发的天气app -系统总体介绍:本天气app使用AndroidStudio这个IDE工具在Windows1 ...

  3. Android 简单天气预报

    IDE: Android studio3.1.2 界面: activity_main.xml

  4. Android实现天气预报温度/气温折线趋势图

     Android实现天气预报温度/气温折线趋势图 天气预报的APP应用中,难免会遇到绘制天气温度/气温,等关于数据趋势的折线或者曲线图,这类关于气温/温度的折线图,通常会有两条线.一条是高温线,一 ...

  5. 天气预报APP(1)

    一个天气预报APP至少应该具备以下功能: *可以罗列出全国所有的省.市.县: *可以查看全国任意城市的天气信息: *可以自由的切换城市,去查看其他城市的天气: *提供手动更新以及后台自动更新天气的功能 ...

  6. Android 7.1 - App Shortcuts

    Android 7.1 - App Shortcuts 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Shortcuts 文中如有纰漏,欢迎大家留言 ...

  7. Android中实现APP文本内容的分享发送与接收方法简述

    谨记(指定选择器Intent.createChooser()) 开始今天的内容前,先闲聊一下: (1)突然有一天头脑风暴,对很多问题有了新的看法和见解,迫不及待的想要分享给大家,文档已经写好了,我需要 ...

  8. Android 7.1 App Shortcuts使用

    Android 7.1 App Shortcuts使用 Android 7.1已经发了预览版, 这里是API Overview: API overview. 其中App Shortcuts是新提供的一 ...

  9. 在布局中使用android.support.v4.app.Fragment的注意事项

    1.Activity必须继承android.support.v4.app.FragmentActivity 2.fragment标签的name属性必须是完全限定包名,如下: <LinearLay ...

随机推荐

  1. HTML 学习笔记 CSS3 (边框)

    CSS3边框 通过CSS3边框 你能够创建远角边框 向矩形边框添加阴影 使用图片来绘制边框 . CSS3的边框属性 主要包含以下几种 border-radius 边框圆角 box-shadow 边框阴 ...

  2. nginx相关

    定时切割nginx日志#!/bin/bash #desc: cut nginx log #this script run at 00:00 LOG_PATH='/usr/local/nginx/log ...

  3. 02传智_jbpm与OA项目_部门模块

    部门模块:具有增删改查(部门)的功能. Dao层的实现: 1,定义一个DepartmentDao.java. 定义基本的数据库操作.

  4. 使用ViewBag传送数据从控制器至视图

    前一篇<ASP.NET MVC读取XML并使用ViewData显示>http://www.cnblogs.com/insus/p/4308740.html 中,在控制器中使用了ViewDa ...

  5. Cordova - 使用Cordova开发iOS应用实战1(配置、开发第一个应用)

    Cordova - 使用Cordova开发iOS应用实战1(配置.开发第一个应用) 现在比较流行使用 html5 开发移动应用,毕竟只要写一套html页面就可以适配各种移动设备,大大节省了跨平台应用的 ...

  6. swift调用oc语言文件,第三方库文件或者自己创建的oc文件——简书作者

    Swift是怎样调用OC的第三方库的呢?请看下面详情: 情况一: 1.首先打开Xcode,iOS->Application->Single View Application, 选Next. ...

  7. Datatable删除行的Delete和Remove方法

    在C#中,如果要删除DataTable中的某一行,大约有以下几种办法: 1,使用DataTable.Rows.Remove(DataRow),或者DataTable.Rows.RemoveAt(ind ...

  8. cookie记住密码功能

    很多门户网站都提供了记住密码功能,虽然现在的浏览器都已经提供了相应的记住密码功能 效果就是你每次进入登录页面后就不需要再进行用户名和密码的输入: 记住密码功能基本都是使用cookie来进行实现的,因此 ...

  9. left join 条件区别

    t1: num | name-----+------ 1      | a 2      | b 3      | c t2: num | value-----+------- 1  | xxx 3 ...

  10. JavaScript高级程序设计笔记 事件冒泡和事件捕获

    1.事件冒泡 要理解事件冒泡,就得先知道事件流.事件流描述的是从页面接收事件的顺序,比如如下的代码: <body> <div> click me! </div> & ...