diff --git a/.gitignore b/.gitignore index f6b286c..603b140 100644 --- a/.gitignore +++ b/.gitignore @@ -1,40 +1,14 @@ -# Built application files -*.apk -*.ap_ - -# Files for the ART/Dalvik VM -*.dex - -# Java class files -*.class - -# Generated files -bin/ -gen/ -out/ - -# Gradle files -.gradle/ -build/ - -# Local configuration file (sdk path, etc) -local.properties - -# Proguard folder generated by Eclipse -proguard/ - -# Log Files -*.log - -# Android Studio Navigation editor temp files -.navigation/ - -# Android Studio captures folder -captures/ - -# Intellij *.iml -.idea/workspace.xml - -# Keystore files -*.jks +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..bd720a1 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +CoolWeather \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..681f41a --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,116 @@ + + + + + + + +
+ + + + xmlns:android + + ^$ + + + +
+
+ + + + xmlns:.* + + ^$ + + + BY_NAME + +
+
+ + + + .*:id + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + .*:name + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + name + + ^$ + + + +
+
+ + + + style + + ^$ + + + +
+
+ + + + .* + + ^$ + + + BY_NAME + +
+
+ + + + .* + + http://schemas.android.com/apk/res/android + + + ANDROID_ATTRIBUTE_ORDER + +
+
+ + + + .* + + .* + + + BY_NAME + +
+
+
+
+
+
\ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml index fe72da5..d291b3d 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -3,16 +3,13 @@ diff --git a/.idea/libraries/android_android_24.xml b/.idea/libraries/android_android_24.xml index 80d5c10..06b3964 100644 --- a/.idea/libraries/android_android_24.xml +++ b/.idea/libraries/android_android_24.xml @@ -1,7 +1,7 @@ - + diff --git a/.idea/misc.xml b/.idea/misc.xml index 7c1371c..37a7509 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,40 +1,6 @@ - - - - - - - - - - - - - - - + diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 35eb1dd..288b36b 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -1,6 +1,7 @@ - + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 3a4576e..9050e9b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,30 +1,43 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 24 - buildToolsVersion "24.0.2" - + compileSdkVersion 29 + buildToolsVersion "29.0.2" defaultConfig { applicationId "com.coolweather.android" minSdkVersion 15 - targetSdkVersion 24 - versionCode 2 - versionName "1.1" + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } +// signingConfigs { +// config { +// storeFile file('C:/Users/administrator/Documents/guolin.jks') +// storePassword '12345678' +// keyAlias 'guolindev' +// keyPassword '12345678' +// } +// } buildTypes { release { minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' +// signingConfig signingConfigs.config } } } dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - testCompile 'junit:junit:4.12' - compile 'com.android.support:appcompat-v7:24.2.1' - compile 'com.github.bumptech.glide:glide:3.7.0' - compile 'org.litepal.android:core:1.3.2' - compile 'com.squareup.okhttp3:okhttp:3.4.1' - compile 'com.google.code.gson:gson:2.7' + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' + implementation 'com.squareup.okhttp3:okhttp:4.2.2' + implementation 'com.google.code.gson:gson:2.8.6' + implementation 'com.github.bumptech.glide:glide:4.10.0' + implementation 'org.litepal.android:core:1.4.1' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0' } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 21e2d3c..f1b4245 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -1,17 +1,21 @@ # Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in C:\Users\Administrator\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. +# 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 -# Add any project specific keep options here: - # 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/com/coolweather/android/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/coolweather/android/ExampleInstrumentedTest.java new file mode 100644 index 0000000..cd97fb9 --- /dev/null +++ b/app/src/androidTest/java/com/coolweather/android/ExampleInstrumentedTest.java @@ -0,0 +1,27 @@ +package com.coolweather.android; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.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.getInstrumentation().getTargetContext(); + + assertEquals("com.coolweather.android", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 548f5b1..05948c4 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -9,8 +9,15 @@ android:allowBackup="true" android:icon="@mipmap/logo" android:label="@string/app_name" + android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> + + + @@ -18,12 +25,6 @@ - - - \ No newline at end of file diff --git a/app/src/main/assets/litepal.xml b/app/src/main/assets/litepal.xml index b4806e0..19ff24f 100644 --- a/app/src/main/assets/litepal.xml +++ b/app/src/main/assets/litepal.xml @@ -1,14 +1,9 @@ - - - - - - + + - - - + + + - \ No newline at end of file diff --git a/app/src/main/java/com/coolweather/android/AutoUpdateService.java b/app/src/main/java/com/coolweather/android/AutoUpdateService.java new file mode 100644 index 0000000..8d859aa --- /dev/null +++ b/app/src/main/java/com/coolweather/android/AutoUpdateService.java @@ -0,0 +1,97 @@ +package com.coolweather.android; + +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 com.coolweather.android.gson.Weather; +import com.coolweather.android.util.HttpUtil; +import com.coolweather.android.util.Utility; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Response; + +public class AutoUpdateService extends Service { + public AutoUpdateService() { + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId){ + updateWeather(); + updateBingPic(); + AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); + int anHour = 8*60*60*1000; // 8 hour milliseconds count + long triggerAtTime = SystemClock.elapsedRealtime() + anHour; + Intent i = new Intent(this, AutoUpdateService.class); + PendingIntent pi = PendingIntent.getService(this, 0, i,0); + manager.cancel(pi); + manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); + return super.onStartCommand(intent, flags, startId); + } + + private void updateWeather() { + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + String weatherString = prefs.getString("weather",null); + if (weatherString != null){ + Weather weather = Utility.handleWeatherResponse(weatherString); + String weatherId = weather.basic.weatherId; + String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+ + "&key=a22c8fe29ad84e509abf1856cc1b3cde"; + HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + e.printStackTrace(); + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + String responseText = response.body().string(); + Weather weather = Utility.handleWeatherResponse(responseText); + if (weather != null && "ok".equals(weather.status)){ + SharedPreferences.Editor editor = PreferenceManager. + getDefaultSharedPreferences(AutoUpdateService.this).edit(); + editor.putString("weather", responseText); + editor.apply(); + } + } + }); + } + } + + private void updateBingPic() { + String requestBingPic = "http://guolin.tech/api/bing_pic"; + HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + e.printStackTrace(); + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + String bingPic = response.body().string(); + SharedPreferences.Editor editor = PreferenceManager. + getDefaultSharedPreferences(AutoUpdateService.this).edit(); + editor.putString("bing_pic", bingPic); + editor.apply(); + } + }); + + } + +} diff --git a/app/src/main/java/com/coolweather/android/ChooseAreaFragment.java b/app/src/main/java/com/coolweather/android/ChooseAreaFragment.java index 1fc1c4f..7069ca1 100644 --- a/app/src/main/java/com/coolweather/android/ChooseAreaFragment.java +++ b/app/src/main/java/com/coolweather/android/ChooseAreaFragment.java @@ -3,8 +3,6 @@ import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -15,6 +13,8 @@ import android.widget.TextView; import android.widget.Toast; +import androidx.fragment.app.Fragment; + import com.coolweather.android.db.City; import com.coolweather.android.db.County; import com.coolweather.android.db.Province; @@ -32,61 +32,26 @@ import okhttp3.Response; public class ChooseAreaFragment extends Fragment { - - private static final String TAG = "ChooseAreaFragment"; - 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 Button backButton; - private ListView listView; - private ArrayAdapter adapter; - private List dataList = new ArrayList<>(); - /** - * 省列表 - */ private List provinceList; - - /** - * 市列表 - */ private List cityList; - - /** - * 县列表 - */ private List countyList; - - /** - * 选中的省份 - */ private Province selectedProvince; - - /** - * 选中的城市 - */ private City selectedCity; - - /** - * 当前选中的级别 - */ private int currentLevel; - @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + Bundle savedInstanceState){ View view = inflater.inflate(R.layout.choose_area, container, false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); @@ -97,39 +62,40 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, } @Override - public void onActivityCreated(Bundle savedInstanceState) { + public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - if (currentLevel == LEVEL_PROVINCE) { + if (currentLevel == LEVEL_PROVINCE){ selectedProvince = provinceList.get(position); queryCities(); - } else if (currentLevel == LEVEL_CITY) { + }else if (currentLevel == LEVEL_CITY){ selectedCity = cityList.get(position); queryCounties(); - } else if (currentLevel == LEVEL_COUNTY) { + }else if (currentLevel == LEVEL_COUNTY){ String weatherId = countyList.get(position).getWeatherId(); - if (getActivity() instanceof MainActivity) { + if (getActivity() instanceof MainActivity){ Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id", weatherId); startActivity(intent); getActivity().finish(); - } else if (getActivity() instanceof WeatherActivity) { + } else if (getActivity() instanceof WeatherActivity){ WeatherActivity activity = (WeatherActivity) getActivity(); activity.drawerLayout.closeDrawers(); activity.swipeRefresh.setRefreshing(true); activity.requestWeather(weatherId); } + } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if (currentLevel == LEVEL_COUNTY) { + if (currentLevel == LEVEL_COUNTY){ queryCities(); - } else if (currentLevel == LEVEL_CITY) { + }else if (currentLevel == LEVEL_CITY){ queryProvinces(); } } @@ -137,99 +103,91 @@ public void onClick(View v) { queryProvinces(); } - /** - * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。 - */ private void queryProvinces() { titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); - if (provinceList.size() > 0) { + if (provinceList.size()>0){ dataList.clear(); - for (Province province : provinceList) { + for (Province province:provinceList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; - } else { - String address = "http://guolin.tech/api/china"; + }else { + String address = "http://guolin.tech/api/china/"; queryFromServer(address, "province"); } } - /** - * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。 - */ private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); - cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class); - if (cityList.size() > 0) { + cityList = DataSupport.where("provinceid=?", String.valueOf(selectedProvince + .getId())).find(City.class); + if (cityList.size()>0){ dataList.clear(); - for (City city : cityList) { + for (City city:cityList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; - } else { + }else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address, "city"); } } - /** - * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。 - */ private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); - countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); - if (countyList.size() > 0) { + countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())) + .find(County.class); + if (countyList.size() > 0){ dataList.clear(); - for (County county : countyList) { + for (County county:countyList){ dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; - } else { + }else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); - String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; + String address = "http://guolin.tech/api/china/" + provinceCode +"/"+ cityCode; queryFromServer(address, "county"); } } - /** - * 根据传入的地址和类型从服务器上查询省市县数据。 - */ private void queryFromServer(String address, final String type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { + @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); - boolean result = false; - if ("province".equals(type)) { + boolean result = false; + if ("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); - } else if ("city".equals(type)) { + }else if ("city".equals(type)){ result = Utility.handleCityResponse(responseText, selectedProvince.getId()); - } else if ("county".equals(type)) { + }else if ("county".equals(type)){ result = Utility.handleCountyResponse(responseText, selectedCity.getId()); } - if (result) { + + if (result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); - if ("province".equals(type)) { + if ("province".equals(type)){ queryProvinces(); - } else if ("city".equals(type)) { + }else if ("city".equals(type)){ queryCities(); - } else if ("county".equals(type)) { + }else if ("county".equals(type)){ queryCounties(); } } @@ -239,23 +197,19 @@ public void run() { @Override public void onFailure(Call call, IOException e) { - // 通过runOnUiThread()方法回到主线程处理逻辑 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); - Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show(); + Toast.makeText(getContext(), "加载失败",Toast.LENGTH_SHORT).show(); } }); } }); } - /** - * 显示进度对话框 - */ private void showProgressDialog() { - if (progressDialog == null) { + if (progressDialog == null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); @@ -263,13 +217,9 @@ private void showProgressDialog() { progressDialog.show(); } - /** - * 关闭进度对话框 - */ private void closeProgressDialog() { - if (progressDialog != null) { + if (progressDialog != null){ progressDialog.dismiss(); } } - } diff --git a/app/src/main/java/com/coolweather/android/MainActivity.java b/app/src/main/java/com/coolweather/android/MainActivity.java index adbf574..cb5500a 100644 --- a/app/src/main/java/com/coolweather/android/MainActivity.java +++ b/app/src/main/java/com/coolweather/android/MainActivity.java @@ -1,11 +1,11 @@ package com.coolweather.android; +import androidx.appcompat.app.AppCompatActivity; + import android.content.Intent; import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.support.v7.app.ActionBar; -import android.support.v7.app.AppCompatActivity; import android.os.Bundle; +import android.preference.PreferenceManager; public class MainActivity extends AppCompatActivity { @@ -14,11 +14,10 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); - if (prefs.getString("weather", null) != null) { + if (prefs.getString("weather", null)!=null){ Intent intent = new Intent(this, WeatherActivity.class); startActivity(intent); finish(); } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/com/coolweather/android/WeatherActivity.java b/app/src/main/java/com/coolweather/android/WeatherActivity.java index fe25164..773f99f 100644 --- a/app/src/main/java/com/coolweather/android/WeatherActivity.java +++ b/app/src/main/java/com/coolweather/android/WeatherActivity.java @@ -1,15 +1,16 @@ package com.coolweather.android; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; + import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; -import android.support.v4.view.GravityCompat; -import android.support.v4.widget.DrawerLayout; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; @@ -21,11 +22,13 @@ import com.bumptech.glide.Glide; import com.coolweather.android.gson.Forecast; +import com.coolweather.android.gson.Suggestion; import com.coolweather.android.gson.Weather; -import com.coolweather.android.service.AutoUpdateService; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import okhttp3.Call; @@ -33,50 +36,34 @@ import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { - public DrawerLayout drawerLayout; - + private Button navButton; public SwipeRefreshLayout swipeRefresh; - + private String mWeatherId; private ScrollView weatherLayout; - - private Button navButton; - private TextView titleCity; - private TextView titleUpdateTime; - private TextView degreeText; - private TextView weatherInfoText; - private LinearLayout forecastLayout; - private TextView aqiText; - private TextView pm25Text; - private TextView comfortText; - private TextView carWashText; - private TextView sportText; - private ImageView bingPicImg; - private String mWeatherId; - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if (Build.VERSION.SDK_INT >= 21) { + if (Build.VERSION.SDK_INT >= 21){ View decorView = getWindow().getDecorView(); - decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + decorView.setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather); - // 初始化各控件 bingPicImg = (ImageView) findViewById(R.id.bing_pic_img); weatherLayout = (ScrollView) findViewById(R.id.weather_layout); titleCity = (TextView) findViewById(R.id.title_city); @@ -95,14 +82,13 @@ protected void onCreate(Bundle savedInstanceState) { navButton = (Button) findViewById(R.id.nav_button); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = prefs.getString("weather", null); - if (weatherString != null) { - // 有缓存时直接解析天气数据 + if (weatherString != null){ Weather weather = Utility.handleWeatherResponse(weatherString); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); - } else { - // 无缓存时去服务器查询天气 + }else { mWeatherId = getIntent().getStringExtra("weather_id"); +// String weatherId = getIntent().getStringExtra("weather_id"); weatherLayout.setVisibility(View.INVISIBLE); requestWeather(mWeatherId); } @@ -112,41 +98,42 @@ public void onRefresh() { requestWeather(mWeatherId); } }); + String bingPic = prefs.getString("bing_pic", null); + if (bingPic != null){ + Glide.with(this).load(bingPic).into(bingPicImg); + }else { + loadBingPic(); + } navButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(GravityCompat.START); } }); - String bingPic = prefs.getString("bing_pic", null); - if (bingPic != null) { - Glide.with(this).load(bingPic).into(bingPicImg); - } else { - loadBingPic(); - } } - /** - * 根据天气id请求城市天气信息。 - */ + public void requestWeather(final String weatherId) { - String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9"; + String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+ + "&key=a22c8fe29ad84e509abf1856cc1b3cde"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override - public void onResponse(Call call, Response response) throws IOException { + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.handleWeatherResponse(responseText); runOnUiThread(new Runnable() { @Override public void run() { - if (weather != null && "ok".equals(weather.status)) { - SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); + if (weather != null && "ok".equals(weather.status)){ + SharedPreferences.Editor editor = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); - } else { - Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); + }else { + Toast.makeText(WeatherActivity.this,"获取天气信息失败", + Toast.LENGTH_SHORT).show(); } swipeRefresh.setRefreshing(false); } @@ -154,12 +141,13 @@ public void run() { } @Override - public void onFailure(Call call, IOException e) { + public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { - Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); + Toast.makeText(WeatherActivity.this,"获取天气信息失败", + Toast.LENGTH_SHORT).show(); swipeRefresh.setRefreshing(false); } }); @@ -168,36 +156,6 @@ public void run() { loadBingPic(); } - /** - * 加载必应每日一图 - */ - private void loadBingPic() { - String requestBingPic = "http://guolin.tech/api/bing_pic"; - HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { - @Override - public void onResponse(Call call, Response response) throws IOException { - final String bingPic = response.body().string(); - SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); - editor.putString("bing_pic", bingPic); - editor.apply(); - runOnUiThread(new Runnable() { - @Override - public void run() { - Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); - } - }); - } - - @Override - public void onFailure(Call call, IOException e) { - e.printStackTrace(); - } - }); - } - - /** - * 处理并展示Weather实体类中的数据。 - */ private void showWeatherInfo(Weather weather) { String cityName = weather.basic.cityName; String updateTime = weather.basic.update.updateTime.split(" ")[1]; @@ -208,8 +166,10 @@ private void showWeatherInfo(Weather weather) { degreeText.setText(degree); weatherInfoText.setText(weatherInfo); forecastLayout.removeAllViews(); - for (Forecast forecast : weather.forecastList) { - View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); + + for (Forecast forecast:weather.forecastList){ + View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, + forecastLayout,false); TextView dateText = (TextView) view.findViewById(R.id.date_text); TextView infoText = (TextView) view.findViewById(R.id.info_text); TextView maxText = (TextView) view.findViewById(R.id.max_text); @@ -220,19 +180,45 @@ private void showWeatherInfo(Weather weather) { minText.setText(forecast.temperature.min); forecastLayout.addView(view); } - if (weather.aqi != null) { + if (weather.aqi != null){ aqiText.setText(weather.aqi.city.aqi); pm25Text.setText(weather.aqi.city.pm25); } - String comfort = "舒适度:" + weather.suggestion.comfort.info; - String carWash = "洗车指数:" + weather.suggestion.carWash.info; - String sport = "运行建议:" + weather.suggestion.sport.info; + String comfort = "舒适度" + weather.suggestion.comfort.info; + String carWash = "洗车指数" + weather.suggestion.carWash.info; + String sport = "运动建议" + weather.suggestion.sport.info; comfortText.setText(comfort); carWashText.setText(carWash); sportText.setText(sport); weatherLayout.setVisibility(View.VISIBLE); + Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } + + private void loadBingPic() { + String requestBingPic = "http://guolin.tech/api/bing_pic"; + HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + e.printStackTrace(); + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + final String bingPic = response.body().string(); + SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences( + WeatherActivity.this).edit(); + editor.putString("bing_pic", bingPic); + editor.apply(); + runOnUiThread(new Runnable() { + @Override + public void run() { + Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); + } + }); + } + }); + } } diff --git a/app/src/main/java/com/coolweather/android/db/City.java b/app/src/main/java/com/coolweather/android/db/City.java index 99155d7..df18ad4 100644 --- a/app/src/main/java/com/coolweather/android/db/City.java +++ b/app/src/main/java/com/coolweather/android/db/City.java @@ -3,45 +3,40 @@ import org.litepal.crud.DataSupport; public class City extends DataSupport { - private int id; - private String cityName; - private int cityCode; - private int provinceId; - public int getId() { + public int getId(){ return id; } - public void setId(int id) { + public void setId(int id){ this.id = id; } - public String getCityName() { + public String getCityName(){ return cityName; } - public void setCityName(String cityName) { + public void setCityName(String cityName){ this.cityName = cityName; } - public int getCityCode() { + public int getCityCode(){ return cityCode; } - public void setCityCode(int cityCode) { + public void setCityCode(int cityCode){ this.cityCode = cityCode; } - public int getProvinceId() { + public int getProvinceId(){ return provinceId; } - public void setProvinceId(int provinceId) { + public void setProvinceId(int provinceId){ this.provinceId = provinceId; } - } diff --git a/app/src/main/java/com/coolweather/android/db/County.java b/app/src/main/java/com/coolweather/android/db/County.java index 284eed2..1ae1f77 100644 --- a/app/src/main/java/com/coolweather/android/db/County.java +++ b/app/src/main/java/com/coolweather/android/db/County.java @@ -2,46 +2,43 @@ import org.litepal.crud.DataSupport; -public class County extends DataSupport { +import java.security.PublicKey; +public class County extends DataSupport { private int id; - private String countyName; - private String weatherId; - private int cityId; - public int getId() { + public int getId(){ return id; } - public void setId(int id) { + public void setId(int id){ this.id = id; } - public String getCountyName() { + public String getCountyName(){ return countyName; } - public void setCountyName(String countyName) { + public void setCountyName(String countyName){ this.countyName = countyName; } - public String getWeatherId() { + public String getWeatherId(){ return weatherId; } - public void setWeatherId(String weatherId) { + public void setWeatherId(String weatherId){ this.weatherId = weatherId; } - public int getCityId() { + public int getCityId(){ return cityId; } - public void setCityId(int cityId) { + public void setCityId(int cityId){ this.cityId = cityId; } - } diff --git a/app/src/main/java/com/coolweather/android/db/Province.java b/app/src/main/java/com/coolweather/android/db/Province.java index 4a5a914..d5ffbb8 100644 --- a/app/src/main/java/com/coolweather/android/db/Province.java +++ b/app/src/main/java/com/coolweather/android/db/Province.java @@ -3,34 +3,25 @@ import org.litepal.crud.DataSupport; public class Province extends DataSupport { - private int id; - private String provinceName; - private int provinceCode; - - public int getId() { + public int getId(){ return id; } - - public void setId(int id) { + public void setId(int id){ this.id = id; } - - public String getProvinceName() { + public String getProvinceName(){ return provinceName; } - - public void setProvinceName(String provinceName) { + public void setProvinceName(String provinceName){ this.provinceName = provinceName; } - - public int getProvinceCode() { + public int getProvinceCode(){ return provinceCode; } - - public void setProvinceCode(int provinceCode) { + public void setProvinceCode(int provinceCode){ this.provinceCode = provinceCode; } } diff --git a/app/src/main/java/com/coolweather/android/gson/AQI.java b/app/src/main/java/com/coolweather/android/gson/AQI.java index a46e883..202184c 100644 --- a/app/src/main/java/com/coolweather/android/gson/AQI.java +++ b/app/src/main/java/com/coolweather/android/gson/AQI.java @@ -3,13 +3,8 @@ public class AQI { public AQICity city; - - public class AQICity { - + public class AQICity{ public String aqi; - public String pm25; - } - } diff --git a/app/src/main/java/com/coolweather/android/gson/Basic.java b/app/src/main/java/com/coolweather/android/gson/Basic.java index 0333374..ea9209b 100644 --- a/app/src/main/java/com/coolweather/android/gson/Basic.java +++ b/app/src/main/java/com/coolweather/android/gson/Basic.java @@ -3,7 +3,6 @@ import com.google.gson.annotations.SerializedName; public class Basic { - @SerializedName("city") public String cityName; @@ -12,11 +11,8 @@ public class Basic { public Update update; - public class Update { - + public class Update{ @SerializedName("loc") public String updateTime; - } - } diff --git a/app/src/main/java/com/coolweather/android/gson/Forecast.java b/app/src/main/java/com/coolweather/android/gson/Forecast.java index 54f45e8..89d5761 100644 --- a/app/src/main/java/com/coolweather/android/gson/Forecast.java +++ b/app/src/main/java/com/coolweather/android/gson/Forecast.java @@ -3,9 +3,7 @@ import com.google.gson.annotations.SerializedName; public class Forecast { - public String date; - @SerializedName("tmp") public Temperature temperature; @@ -13,18 +11,12 @@ public class Forecast { public More more; public class Temperature { - public String max; - public String min; - } public class More { - @SerializedName("txt_d") public String info; - } - } diff --git a/app/src/main/java/com/coolweather/android/gson/Now.java b/app/src/main/java/com/coolweather/android/gson/Now.java index ae50677..a6b28c0 100644 --- a/app/src/main/java/com/coolweather/android/gson/Now.java +++ b/app/src/main/java/com/coolweather/android/gson/Now.java @@ -10,11 +10,8 @@ public class Now { @SerializedName("cond") public More more; - public class More { - + public class More{ @SerializedName("txt") public String info; - } - } diff --git a/app/src/main/java/com/coolweather/android/gson/Suggestion.java b/app/src/main/java/com/coolweather/android/gson/Suggestion.java index 3db11e7..497b2c9 100644 --- a/app/src/main/java/com/coolweather/android/gson/Suggestion.java +++ b/app/src/main/java/com/coolweather/android/gson/Suggestion.java @@ -3,7 +3,6 @@ import com.google.gson.annotations.SerializedName; public class Suggestion { - @SerializedName("comf") public Comfort comfort; @@ -12,25 +11,18 @@ public class Suggestion { public Sport sport; - public class Comfort { - + public class Comfort{ @SerializedName("txt") public String info; - } - public class CarWash { - + public class CarWash{ @SerializedName("txt") public String info; - } - public class Sport { - + public class Sport{ @SerializedName("txt") public String info; - } - } diff --git a/app/src/main/java/com/coolweather/android/gson/Weather.java b/app/src/main/java/com/coolweather/android/gson/Weather.java index d8459b7..45cb72e 100644 --- a/app/src/main/java/com/coolweather/android/gson/Weather.java +++ b/app/src/main/java/com/coolweather/android/gson/Weather.java @@ -5,18 +5,13 @@ import java.util.List; public class Weather { - public String status; - + public Basic basic; - public AQI aqi; - public Now now; - public Suggestion suggestion; @SerializedName("daily_forecast") public List forecastList; - } diff --git a/app/src/main/java/com/coolweather/android/util/HttpUtil.java b/app/src/main/java/com/coolweather/android/util/HttpUtil.java index 27640ca..ea426fe 100644 --- a/app/src/main/java/com/coolweather/android/util/HttpUtil.java +++ b/app/src/main/java/com/coolweather/android/util/HttpUtil.java @@ -4,11 +4,9 @@ import okhttp3.Request; public class HttpUtil { - - public static void sendOkHttpRequest(String address, okhttp3.Callback callback) { + public static void sendOkHttpRequest(String address, okhttp3.Callback callback){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } - } diff --git a/app/src/main/java/com/coolweather/android/util/Utility.java b/app/src/main/java/com/coolweather/android/util/Utility.java index 2149e03..ac922a6 100644 --- a/app/src/main/java/com/coolweather/android/util/Utility.java +++ b/app/src/main/java/com/coolweather/android/util/Utility.java @@ -13,15 +13,11 @@ import org.json.JSONObject; public class Utility { - - /** - * 解析和处理服务器返回的省级数据 - */ - public static boolean handleProvinceResponse(String response) { - if (!TextUtils.isEmpty(response)) { + public static boolean handleProvinceResponse(String response){ + if(!TextUtils.isEmpty(response)){ try { JSONArray allProvinces = new JSONArray(response); - for (int i = 0; i < allProvinces.length(); i++) { + for (int i=0;i + + + + + + + + + + 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..0d025f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index f59e44b..55d8ff9 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -1,6 +1,5 @@ - @@ -8,6 +7,6 @@ android:id="@+id/choose_area_fragment" android:name="com.coolweather.android.ChooseAreaFragment" android:layout_width="match_parent" - android:layout_height="match_parent" /> + android:layout_height="match_parent"/> \ No newline at end of file diff --git a/app/src/main/res/layout/activity_weather.xml b/app/src/main/res/layout/activity_weather.xml index 65d8e05..ae3ed27 100644 --- a/app/src/main/res/layout/activity_weather.xml +++ b/app/src/main/res/layout/activity_weather.xml @@ -9,14 +9,16 @@ android:id="@+id/bing_pic_img" android:layout_width="match_parent" android:layout_height="match_parent" - android:scaleType="centerCrop" /> + android:scaleType="centerCrop"/> - - @@ -34,30 +36,20 @@ android:layout_height="wrap_content" android:fitsSystemWindows="true"> - - - - - - - - - + + + + + - - - - + - - - - + android:layout_gravity="start"/> + + \ No newline at end of file diff --git a/app/src/main/res/layout/aqi.xml b/app/src/main/res/layout/aqi.xml index 6c4af5e..1f1e533 100644 --- a/app/src/main/res/layout/aqi.xml +++ b/app/src/main/res/layout/aqi.xml @@ -11,7 +11,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" - android:layout_marginTop="15dp" + android:layout_marginRight="15dp" android:text="空气质量" android:textColor="#fff" android:textSize="20sp"/> @@ -38,25 +38,22 @@ android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="#fff" - android:textSize="40sp" - /> + android:textSize="40sp"/> - - + android:textSize="40sp"/> + android:text="PM2.5 指数" + android:textColor="#fff"/> - - \ No newline at end of file diff --git a/app/src/main/res/layout/choose_area.xml b/app/src/main/res/layout/choose_area.xml index 0e4fd6b..c52a1dc 100644 --- a/app/src/main/res/layout/choose_area.xml +++ b/app/src/main/res/layout/choose_area.xml @@ -1,6 +1,5 @@ - -