diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..51046d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +*.idea/ +/local.properties +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..635e686 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2018 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +apply plugin: 'com.android.application' + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "org.incoder.weather" + minSdkVersion 16 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:28.0.0' + implementation 'com.android.support.constraint:constraint-layout:1.1.3' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/org/incoder/weather/ExampleInstrumentedTest.java b/app/src/androidTest/java/org/incoder/weather/ExampleInstrumentedTest.java new file mode 100644 index 0000000..2f1a4a5 --- /dev/null +++ b/app/src/androidTest/java/org/incoder/weather/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package org.incoder.weather; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("org.incoder.weather", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9e78b0b --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/org/incoder/weather/AddressActivity.java b/app/src/main/java/org/incoder/weather/AddressActivity.java new file mode 100644 index 0000000..dfac5e7 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/AddressActivity.java @@ -0,0 +1,252 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather; + +import android.app.ProgressDialog; +import android.content.Intent; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.Toast; + +import org.incoder.weather.db.WeatherDB; +import org.incoder.weather.manager.ConstantManager; +import org.incoder.weather.model.City; +import org.incoder.weather.model.County; +import org.incoder.weather.model.Province; +import org.incoder.weather.util.HttpsCallbackListener; +import org.incoder.weather.util.HttpUtil; +import org.incoder.weather.util.Utility; + +import java.util.ArrayList; +import java.util.List; + +/** + * Utility + * + * @author : Jerry xu + * @date : 2019年3月10日 23:27 + */ +public class AddressActivity extends AppCompatActivity { + + public static final int LEVEL_PROVINCE = 0; + public static final int LEVEL_CITY = 1; + public static final int LEVEL_COUNTY = 2; + + private ProgressDialog mProgressDialog; + private ListView address; + private ArrayAdapter mAdapter; + private WeatherDB mWeatherDB; + private List dataList = new ArrayList(); + + private List mProvinceList; + private List mCityList; + private List mCountyList; + + private Province selectedProvince; + private City selectCity; + private int currentLevel; + private boolean isFromWeatherActivity; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_address); + address = findViewById(R.id.lv_content); + isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) { + Intent intent = new Intent(this, MainActivity.class); + startActivity(intent); + finish(); + } + + mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, dataList); + address.setAdapter(mAdapter); + + mWeatherDB = WeatherDB.getInstance(this); + address.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + if (currentLevel == LEVEL_PROVINCE) { + selectedProvince = mProvinceList.get(position); + queryCities(); + } else if (currentLevel == LEVEL_CITY) { + selectCity = mCityList.get(position); + queryCounties(); + } else if (currentLevel == LEVEL_COUNTY) { + String countyCode = mCountyList.get(position).getCountyCode(); + Intent intent = new Intent(AddressActivity.this, MainActivity.class); + intent.putExtra("county_code", countyCode); + startActivity(intent); + finish(); + } + } + }); + + queryProvinces(); + } + + /** + * 查询全国所有省,优先从数据库查询,如果没有查询到再从服务器上查询 + */ + private void queryProvinces() { + mProvinceList = mWeatherDB.loadProvinces(); + if (mProvinceList.size()> 0) { + dataList.clear(); + for (Province province : mProvinceList) { + dataList.add(province.getProvinceName()); + } + mAdapter.notifyDataSetChanged(); + address.setSelection(0); + currentLevel = LEVEL_PROVINCE; + } else { + queryFromServer(null, "province"); + } + } + + + /** + * 查询全国所有市,优先从数据库查询,如果没有查询到再从服务器上查询 + */ + private void queryCities() { + mCityList = mWeatherDB.loadCities(selectedProvince.getId()); + if (mCityList.size()> 0) { + dataList.clear(); + for (City city : mCityList) { + dataList.add(city.getCityName()); + } + mAdapter.notifyDataSetChanged(); + address.setSelection(0); + currentLevel = LEVEL_CITY; + } else { + queryFromServer(selectedProvince.getProvinceCode(), "city"); + } + + + } + + /** + * 查询全国所有县,优先从数据库查询,如果没有查询到再从服务器上查询 + */ + private void queryCounties() { + mCountyList = mWeatherDB.loadCounty(selectCity.getId()); + if (mCountyList.size()> 0) { + dataList.clear(); + for (County county : mCountyList) { + dataList.add(county.getCountyName()); + } + mAdapter.notifyDataSetChanged(); + address.setSelection(0); + currentLevel = LEVEL_COUNTY; + } else { + queryFromServer(selectCity.getCityCode(), "county"); + } + } + + + /** + * 根据传入的代号和类型从服务器上查询省市县数据 + */ + private void queryFromServer(String code, final String type) { + String address; + if (!TextUtils.isEmpty(code)) { + address = ConstantManager.WEATHER_CODE + code + ".xml"; + } else { + address = ConstantManager.WEATHER_CODE + ".xml"; + } + showProgressDialog(); + HttpUtil.sendHttpRequest(address, new HttpsCallbackListener() { + boolean result = false; + + @Override + public void onFinish(String response) { + if ("province".equals(type)) { + result = Utility.handleProvincesResponse(mWeatherDB, response); + } else if ("city".equals(type)) { + result = Utility.handleCitiesResponse(mWeatherDB, response, selectedProvince.getId()); + } else if ("county".equals(type)) { + result = Utility.handleCountiesResponse(mWeatherDB, response, selectCity.getId()); + } + + if (result) { + 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(new Runnable() { + @Override + public void run() { + closeProgressDialog(); + Toast.makeText(AddressActivity.this, "加载失败", Toast.LENGTH_SHORT).show(); + } + }); + } + }); + } + + private void showProgressDialog() { + if (mProgressDialog == null) { + mProgressDialog = new ProgressDialog(this); + mProgressDialog.setMessage("正在加载..."); + mProgressDialog.setCanceledOnTouchOutside(false); + } + mProgressDialog.show(); + } + + private void closeProgressDialog() { + if (mProgressDialog != null) { + mProgressDialog.dismiss(); + } + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + if (currentLevel == LEVEL_COUNTY) { + queryCities(); + } else if (currentLevel == LEVEL_CITY) { + queryProvinces(); + } else { + if (isFromWeatherActivity) { + Intent intent = new Intent(this, MainActivity.class); + startActivity(intent); + } + finish(); + } + } +} diff --git a/app/src/main/java/org/incoder/weather/MainActivity.java b/app/src/main/java/org/incoder/weather/MainActivity.java new file mode 100644 index 0000000..283e7b3 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/MainActivity.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.app.AppCompatActivity; +import android.text.TextUtils; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import org.incoder.weather.manager.ConstantManager; +import org.incoder.weather.service.AutoUpdateService; +import org.incoder.weather.util.HttpUtil; +import org.incoder.weather.util.HttpsCallbackListener; +import org.incoder.weather.util.Utility; + +/** + * Utility + * + * @author : Jerry xu + * @date : 2019年3月10日 23:27 + */ +public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { + + private TextView cityName; + private TextView publishText; + private TextView weatherDespText; + private TextView temp1Text; + private TextView temp2Text; + private TextView currentDateText; + private SwipeRefreshLayout mRefreshLayout; + + private Button mButton; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + mRefreshLayout = findViewById(R.id.srl_refresh); + cityName = findViewById(R.id.tv_city_name); + publishText = findViewById(R.id.tv_publish_text); + weatherDespText = findViewById(R.id.tv_weather_desp); + temp1Text = findViewById(R.id.tv_temp1); + temp2Text = findViewById(R.id.tv_temp2); + currentDateText = findViewById(R.id.tv_current_date); + mButton = findViewById(R.id.btn_address); + + mRefreshLayout.setOnRefreshListener(this); + String countyCode = getIntent().getStringExtra("county_code"); + if (!TextUtils.isEmpty(countyCode)) { + publishText.setText("同步中..."); + queryWeatherCode(countyCode); + } else { + // 没有县级代号时就显示本地天气 + showWeather(); + } + + mButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(MainActivity.this, AddressActivity.class); + intent.putExtra("from_weather_activity", true); + startActivity(intent); + finish(); + } + }); + } + + + private void queryWeatherCode(String countyCode) { + String address = ConstantManager.WEATHER_CODE + countyCode + ".xml"; + queryFromServer(address, "countyCode"); + } + + private void queryFromServer(String address, final String type) { + HttpUtil.sendHttpRequest(address, new HttpsCallbackListener() { + @Override + public void onFinish(String response) { + if ("countyCode".equals(type)) { + if (!TextUtils.isEmpty(response)) { + // 从服务器返回的数据中解析天气代号 + String[] array = response.split("\\|"); + if (array != null && array.length == 2) { + String weatherCode = array[1]; + queryWeatherInfo(weatherCode); + } + } + } else if ("weatherCode".equals(type)) { + // 处理服务器返回的天气信息 + Utility.handleWeatherResponse(MainActivity.this, response); + runOnUiThread(new Runnable() { + @Override + public void run() { + showWeather(); + } + }); + } + } + + @Override + public void onError(Exception e) { + publishText.setText("同步失败"); + } + }); + } + + /** + * 从 sharedPreference 文件中读取存储的天气信息,并显示在界面上 + */ + private void showWeather() { + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + cityName.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", "") + "发布"); + currentDateText.setText(prefs.getString("current_date", "")); + Intent intent = new Intent(this, AutoUpdateService.class); + startService(intent); + } + + /** + * 查询天气代号所对应的天气 + * + * @param weatherCode 天气编号 + */ + private void queryWeatherInfo(String weatherCode) { + String address = ConstantManager.WEATHER_INFO + weatherCode + ".html"; + queryFromServer(address, "weatherCode"); + } + + @Override + public void onRefresh() { + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + String weatherCode = prefs.getString("weather_code", ""); + if (!TextUtils.isEmpty(weatherCode)) { + queryWeatherInfo(weatherCode); + } + } +} diff --git a/app/src/main/java/org/incoder/weather/db/WeatherDB.java b/app/src/main/java/org/incoder/weather/db/WeatherDB.java new file mode 100644 index 0000000..6fefc6d --- /dev/null +++ b/app/src/main/java/org/incoder/weather/db/WeatherDB.java @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.db; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; + +import org.incoder.weather.model.City; +import org.incoder.weather.model.County; +import org.incoder.weather.model.Province; + +import java.util.ArrayList; +import java.util.List; + +/** + * WeatherDB. + * + * @author : Jerry xu + * @date : 2019年3月9日 22:05 + */ +public class WeatherDB { + + /** + * 数据库名 + */ + public static final String DB_NAME = "weather_t"; + + /** + * 数据库版本 + */ + public static final int VERSION = 1; + + /** + * 相关的数据库表名称 + */ + public static final String PROVINCE = "Province"; + public static final String CITY = "City"; + public static final String COUNTY = "County"; + + private static WeatherDB sWeatherDB; + + private SQLiteDatabase db; + + private WeatherDB(Context context) { + WeatherOpenHelper helper = new WeatherOpenHelper(context, DB_NAME, null, VERSION); + db = helper.getWritableDatabase(); + } + + + public synchronized static WeatherDB getInstance(Context context) { + if (sWeatherDB == null) { + sWeatherDB = new WeatherDB(context); + } + return sWeatherDB; + } + + + /** + * 将 Province 实例存储到数据库 + * + * @param province 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); + } + } + + + /** + * 从数据库读取全国所有的省份信息 + * + * @return 省信息 + */ + public List loadProvinces() { + List list = new ArrayList(); + 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()); + } + cursor.close(); + return list; + } + + /** + * 将City实例存储到数据库 + * + * @param city 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); + } + } + + + /** + * 从数据库读取某个省下所有的城市信息 + * + * @param provinceId 省id + * @return 城市信息 + */ + public List loadCities(int provinceId) { + List list = new ArrayList(); + 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()); + } + cursor.close(); + return list; + } + + /** + * 将County实例存储到数据库 + * + * @param county 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); + } + } + + + /** + * 从数据库读取某个城市下所有的县信息 + * + * @param cityId 市 id + * @return 县信息 + */ + public List loadCounty(int cityId) { + List list = new ArrayList(); + 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()); + } + cursor.close(); + return list; + } + +} diff --git a/app/src/main/java/org/incoder/weather/db/WeatherOpenHelper.java b/app/src/main/java/org/incoder/weather/db/WeatherOpenHelper.java new file mode 100644 index 0000000..e090f57 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/db/WeatherOpenHelper.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.db; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.support.annotation.Nullable; + +/** + * WeatherOpenHelper + * + * @author : Jerry xu + * @date : 2019年3月9日 21:55 + */ +public class WeatherOpenHelper 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 WeatherOpenHelper(@Nullable Context context, @Nullable String name, + @Nullable SQLiteDatabase.CursorFactory factory, int version) { + super(context, name, factory, version); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL(CREATE_PROVINCE); + db.execSQL(CREATE_CITY); + db.execSQL(CREATE_COUNTY); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + } +} diff --git a/app/src/main/java/org/incoder/weather/manager/ConstantManager.java b/app/src/main/java/org/incoder/weather/manager/ConstantManager.java new file mode 100644 index 0000000..a49dcc7 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/manager/ConstantManager.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.manager; + +/** + * ConstantManager + * + * @author : Jerry xu + * @date : 2019年3月23日 00:38 + */ +public class ConstantManager { + + public static final String WEATHER_CODE = "http://www.weather.com.cn/data/list3/city"; + + + public static final String WEATHER_INFO = "http://www.weather.com.cn/data/cityinfo/"; +} diff --git a/app/src/main/java/org/incoder/weather/model/City.java b/app/src/main/java/org/incoder/weather/model/City.java new file mode 100644 index 0000000..b8c92e9 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/model/City.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.model; + +/** + * City + * + * @author : Jerry xu + * @date : 2019年3月9日 22:03 + */ +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; + } +} diff --git a/app/src/main/java/org/incoder/weather/model/County.java b/app/src/main/java/org/incoder/weather/model/County.java new file mode 100644 index 0000000..3b89b74 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/model/County.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.model; + +/** + * County + * + * @author : Jerry xu + * @date : 2019年3月9日 22:04 + */ +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; + } +} diff --git a/app/src/main/java/org/incoder/weather/model/Province.java b/app/src/main/java/org/incoder/weather/model/Province.java new file mode 100644 index 0000000..6ce0059 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/model/Province.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.model; + +/** + * Province + * + * @author : Jerry xu + * @date : 2019年3月9日 22:02 + */ +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; + } +} diff --git a/app/src/main/java/org/incoder/weather/receiver/AutoUpdateReceiver.java b/app/src/main/java/org/incoder/weather/receiver/AutoUpdateReceiver.java new file mode 100644 index 0000000..2ff2188 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/receiver/AutoUpdateReceiver.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.receiver; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +import org.incoder.weather.service.AutoUpdateService; + +/** + * AutoUpdateReceiver + * + * @author : Jerry xu + * @date : 2019年3月23日 00:22 + */ +public class AutoUpdateReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + Intent i = new Intent(context, AutoUpdateService.class); + context.startService(i); + } +} diff --git a/app/src/main/java/org/incoder/weather/service/AutoUpdateService.java b/app/src/main/java/org/incoder/weather/service/AutoUpdateService.java new file mode 100644 index 0000000..4d3ca0e --- /dev/null +++ b/app/src/main/java/org/incoder/weather/service/AutoUpdateService.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.service; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.IBinder; +import android.os.SystemClock; +import android.preference.PreferenceManager; +import android.widget.Toast; + +import org.incoder.weather.manager.ConstantManager; +import org.incoder.weather.util.HttpUtil; +import org.incoder.weather.util.HttpsCallbackListener; +import org.incoder.weather.util.Utility; + +/** + * AutoUpdateService + * + * @author : Jerry xu + * @date : 2019年3月23日 00:15 + */ +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*/ 30 * 60 * 1000; + long triggerAtTime = SystemClock.elapsedRealtime() + anHour; + Intent i = new Intent(this, AutoUpdateService.class); + Toast.makeText(this, "测试", Toast.LENGTH_SHORT).show(); + 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", ""); + if (weatherCode != null && weatherCode.length()> 0) { + String address = ConstantManager.WEATHER_INFO + weatherCode + ".html"; + HttpUtil.sendHttpRequest(address, new HttpsCallbackListener() { + @Override + public void onFinish(String response) { + Utility.handleWeatherResponse(AutoUpdateService.this, response); + } + + @Override + public void onError(Exception e) { + + } + }); + } + } +} diff --git a/app/src/main/java/org/incoder/weather/util/HttpUtil.java b/app/src/main/java/org/incoder/weather/util/HttpUtil.java new file mode 100644 index 0000000..ba333bd --- /dev/null +++ b/app/src/main/java/org/incoder/weather/util/HttpUtil.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.util; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * HttpUtil + * + * @author : Jerry xu + * @date : 2019年3月10日 14:38 + */ +public class HttpUtil { + + public static void sendHttpRequest(final String address, final HttpsCallbackListener 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 inputStream = connection.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder response = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + response.append(line); + } + if (listener != null) { + listener.onFinish(response.toString()); + } + } catch (Exception e) { + if (listener != null) { + listener.onError(e); + } + e.printStackTrace(); + } finally { + if (connection != null) { + connection.disconnect(); + } + } + } + }).start(); + } +} diff --git a/app/src/main/java/org/incoder/weather/util/HttpsCallbackListener.java b/app/src/main/java/org/incoder/weather/util/HttpsCallbackListener.java new file mode 100644 index 0000000..8390d25 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/util/HttpsCallbackListener.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.util; + +/** + * HttpsCallbackListener. + * + * @author : Jerry xu + * @date : 2019年3月10日 22:58 + */ +public interface HttpsCallbackListener { + + /** + * 完成 + * + * @param response 响应结果 + */ + void onFinish(String response); + + /** + * 错误 + * + * @param e 错误信息 + */ + void onError(Exception e); +} diff --git a/app/src/main/java/org/incoder/weather/util/Utility.java b/app/src/main/java/org/incoder/weather/util/Utility.java new file mode 100644 index 0000000..642fd40 --- /dev/null +++ b/app/src/main/java/org/incoder/weather/util/Utility.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2019 The Jerry xu Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.incoder.weather.util; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.text.TextUtils; + +import org.incoder.weather.db.WeatherDB; +import org.incoder.weather.model.City; +import org.incoder.weather.model.County; +import org.incoder.weather.model.Province; +import org.json.JSONException; +import org.json.JSONObject; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Utility + * + * @author : Jerry xu + * @date : 2019年3月10日 23:27 + */ +public class Utility { + + /** + * 解析处理服务器返回的省级数据 + * + * @param weatherDB weatherDB + * @param response response + * @return true:处理成功;false:处理失败 + */ + public synchronized static boolean handleProvincesResponse(WeatherDB weatherDB, String response) { + if (!TextUtils.isEmpty(response)) { + String[] allProvinces = response.split(","); + if (allProvinces.length> 0) { + for (String p : allProvinces) { + String[] array = p.split("\\|"); + Province province = new Province(); + province.setProvinceCode(array[0]); + province.setProvinceName(array[1]); + // save db + weatherDB.saveProvince(province); + } + return true; + } + } + return false; + } + + /** + * 解析处理服务器返回的市级数据 + * + * @param weatherDB weatherDB + * @param response response + * @param provinceId provinceId + * @return true:处理成功;false:处理失败 + */ + public static boolean handleCitiesResponse(WeatherDB weatherDB, String response, int provinceId) { + if (!TextUtils.isEmpty(response)) { + String[] allCities = response.split(","); + if (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); + // save db + weatherDB.saveCity(city); + } + return true; + } + } + return false; + } + + /** + * 解析处理服务器返回的县级数据 + * + * @param weatherDB weatherDB + * @param response response + * @param cityId cityId + * @return true:处理成功;false:处理失败 + */ + public static boolean handleCountiesResponse(WeatherDB weatherDB, String response, int cityId) { + if (!TextUtils.isEmpty(response)) { + String[] allCounties = response.split(","); + if (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); + // save db + weatherDB.saveCounty(county); + } + return true; + } + } + return false; + } + + + /** + * 解析服务器返回的 json 数据,并将解析的数据存储到本地 + * + * @param context context + * @param response response + */ + 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中 + * + * @param context context + * @param cityName cityName + * @param weatherCode weatherCode + * @param temp1 temp1 + * @param temp2 temp2 + * @param weatherDesp weatherDesp + * @param publishTime publishTime + */ + private static void saveWeatherInfo(Context context, String cityName, String weatherCode, + String temp1, String temp2, String weatherDesp, String publishTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", 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.apply(); + } + +} diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..4b146e1 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d4c9e05 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_address.xml b/app/src/main/res/layout/activity_address.xml new file mode 100644 index 0000000..2dcb358 --- /dev/null +++ b/app/src/main/res/layout/activity_address.xml @@ -0,0 +1,28 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..228bd69 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + +