編輯:關於 Android 開發
之前做過一版天氣預報,功能有了,但畫面實在很醜,所以上一篇根本沒臉貼截圖。這次做了兩件事:介面重做,並在原本的即時天氣之外加上未來七天預報。
先看對比:

這個 App 其實是寫給楊凌一位閨蜜的,順便練技術,所以中間那段文字是刻意寫給她的話——你可以把這個位置換成穿衣建議、紫外線提醒或任何自訂文案。
需要連網,所以先加入 http 套件並申請權限。
1. 加入相依套件
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile files('libs/httpclient-4.4.1.jar')
compile files('libs/httpcore-4.4.1.jar')
}
那兩個 http 開頭的就是這次要用的網路套件。要注意的是,加入這類套件時還必須在 android 區塊裡補上 packagingOptions,排除 META-INF 下的衝突檔案,否則會出現重複檔案的編譯錯誤:
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
}
2. Manifest 權限
寫在 application 之外:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
把這些前置作業做完,後面寫code會少掉很多莫名其妙的錯誤。
老實說我的版面寫得不精緻,基本上就是最簡單的元件堆出來的,絕大部分顯示都用 TextView。先貼完整程式碼,因為後面 Java 那邊還要回頭查這些 id。
結構是:一個 LinearLayout 當背景 → 城市名 → 天氣描述 → 大號溫度 → 自訂提醒 → 七列「星期/天氣/高溫/低溫」→ 底部的城市切換輸入框。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@mipmap/sunny_overcast"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp" />
<TextView
android:id="@+id/city"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="楊凌"
android:textSize="40dp" />
<TextView
android:id="@+id/weather_day"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="happy"
android:textSize="20dp" />
<TextView
android:id="@+id/wendu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="15"
android:textSize="90dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<TextView
android:id="@+id/remind"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:textSize="20dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<!-- 七列未來天氣:la ~ lg,每列結構相同 -->
<!-- la:day_one / image_one / high_one / low_one -->
<!-- lb:day_two / image_two / high_two / low_two -->
<!-- lc:day_three / image_three / high_three / low_three -->
<!-- ld:day_four / image_four / high_four / low_four -->
<!-- le:day_five / image_five / high_five / low_five -->
<!-- lf:day_six / image_six / high_six / low_six -->
<!-- lg:day_seven / image_seven / high_seven / low_seven -->
<LinearLayout
android:id="@+id/la"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.2" />
<TextView
android:id="@+id/day_one"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:text="星期"
android:textSize="20dp" />
<TextView
android:id="@+id/image_one"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:layout_gravity="center" />
<TextView
android:id="@+id/high_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="high" />
<TextView
android:id="@+id/low_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="low" />
</LinearLayout>
<!-- lb ~ lg 的寫法與 la 完全一樣,僅 id 換成 two / three / four / five / six / seven -->
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/serach_city"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight="3"
android:background="@drawable/shape"
android:hint="Input City"
android:text="楊凌"
android:textColorHint="#ee9999"
android:textSize="20dp" />
<Button
android:id="@+id/change"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="@drawable/btn"
android:text="切換城市"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
補充兩點:原本的 SwipeRefreshLayout 是先準備著要做下拉更新的,後來沒真的派上用場,把這個元件拿掉也能跑。另外因為收信人是楊凌人,輸入框的預設值就直接寫成「楊凌」了。
整個專案只有一個 Activity。程式碼如下(保留了一些除錯用的 log,懶得刪就留著了):
public class MainActivity extends AppCompatActivity {
private TextView city, weather_day, wendu, remind;
private EditText search_city;
private Button change;
private LinearLayout bei, la, lb, lc, ld, le, lf, lg;
// 七天的 day_*/image_*/high_*/low_* 共 28 個 TextView 這裡省略宣告
private static Handler handler;
private static Handler handler_now;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
if (!isNetworkConnected()) {
Toast toast = Toast.makeText(getApplicationContext(),
"寶寶你手機沒有網", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
// 開兩個執行緒:一個抓即時天氣,一個抓未來七天
startWeatherThreads();
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 切換城市就是再跑一次
startWeatherThreads();
}
});
}
private void startWeatherThreads() {
new Thread(new Weather_Thread()).start();
new Thread(new Weather_now_Thread()).start();
handler = new Myhandler();
handler_now = new Myhandler_now();
}
/** 對指定網址發 GET,回傳整包字串 */
public static String getURLConnection(String path) {
StringBuilder xml = new StringBuilder();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String list = buffer.readLine();
while (list != null) {
xml.append(list);
list = buffer.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return xml.toString();
}
/** 未來七天 */
public class Weather_Thread implements Runnable {
public void run() {
String first = "https://api.k780.com:88/?app=weather.future&weaid=";
String city = search_city.getText().toString().trim();
String last = "&&appkey=18276&sign=3f37...&format=json";
String Weather = getURLConnection(first + city + last);
Message msg1 = new Message();
Bundle bundle1 = new Bundle();
bundle1.putString("Weather", Weather);
msg1.setData(bundle1);
handler.sendMessage(msg1);
}
}
/** 即時天氣 */
public class Weather_now_Thread implements Runnable {
public void run() {
String first = "https://api.k780.com:88/?app=weather.today&weaid=";
String city = search_city.getText().toString().trim();
String last = "&&appkey=18276&sign=3f37...&format=json";
String Weather_now = getURLConnection(first + city + last);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Weather_now", Weather_now);
msg.setData(bundle);
handler_now.sendMessage(msg);
}
}
}
流程就是:初始化 → 開執行緒 → 收訊息更新 UI。三個步驟,確實不複雜。
網路請求是耗時操作,必須放在子執行緒;但更新 UI 只能回到主執行緒,所以透過 Handler 把字串傳回來。以未來七天為例:
public class Myhandler extends Handler {
public void handleMessage(Message msg) {
String Weather = msg.getData().getString("Weather");
if (Weather == null || Weather.equals("")) return;
try {
JSONArray jsonObjs = new JSONObject(Weather).getJSONArray("result");
for (int i = 0; i < jsonObjs.length(); i++) {
JSONObject obj = jsonObjs.getJSONObject(i);
switch (i) {
case 0:
day_one.setText(obj.getString("week"));
image_one.setText(obj.getString("weather"));
high_one.setText(obj.getString("temp_high") + "°");
low_one.setText(obj.getString("temp_low") + "°");
break;
case 1:
day_two.setText(obj.getString("week"));
image_two.setText(obj.getString("weather"));
high_two.setText(obj.getString("temp_high") + "°");
low_two.setText(obj.getString("temp_low") + "°");
break;
case 2:
day_three.setText(obj.getString("week"));
image_three.setText(obj.getString("weather"));
high_three.setText(obj.getString("temp_high") + "°");
low_three.setText(obj.getString("temp_low") + "°");
break;
case 3:
day_four.setText(obj.getString("week"));
image_four.setText(obj.getString("weather"));
high_four.setText(obj.getString("temp_high") + "°");
low_four.setText(obj.getString("temp_low") + "°");
break;
case 4:
day_five.setText(obj.getString("week"));
image_five.setText(obj.getString("weather"));
high_five.setText(obj.getString("temp_high") + "°");
low_five.setText(obj.getString("temp_low") + "°");
break;
case 5:
day_six.setText(obj.getString("week"));
image_six.setText(obj.getString("weather"));
high_six.setText(obj.getString("temp_high") + "°");
low_six.setText(obj.getString("temp_low") + "°");
break;
case 6:
day_seven.setText(obj.getString("week"));
image_seven.setText(obj.getString("weather"));
high_seven.setText(obj.getString("temp_high") + "°");
low_seven.setText(obj.getString("temp_low") + "°");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
JSON 解析我自己也是剛學,說法未必精準,但核心就是「用鍵取值」這個動作:拿到 result 陣列後,依長度用迴圈把每一筆取出來填進畫面。即時天氣那部分的執行緒邏輯完全一樣,只是解析時不必處理陣列,比這裡單純一些。
天氣字串回來後,換背景圖並調整透明度:
public void Init_Image(String str) {
if (str.equals("晴")) {
bei.setBackgroundDrawable(getResources().getDrawable(R.mipmap.sunny));
Init_T();
} else if (str.equals("多雲轉小雨") || str.equals("小雨轉多雲") || str.equals("小雨")) {
bei.setBackgroundDrawable(getResources().getDrawable(R.mipmap.light_rain));
Init_T();
} else if (str.equals("多雲轉晴") || str.equals("晴轉多雲")
|| str.equals("多雲轉陰") || str.equals("陰轉多雲") || str.equals("多雲")) {
bei.setBackgroundDrawable(getResources().getDrawable(R.mipmap.cloudy));
Init_T();
} else {
bei.setBackgroundDrawable(getResources().getDrawable(R.mipmap.frost));
Init_T();
}
}
/** 七列的半透明處理 */
public void Init_T() {
la.getBackground().setAlpha(100);
lb.getBackground().setAlpha(100);
lc.getBackground().setAlpha(100);
ld.getBackground().setAlpha(100);
le.getBackground().setAlpha(100);
lf.getBackground().setAlpha(100);
lg.getBackground().setAlpha(100);
}
中間那段自訂文案則依星期切換:
public void Init(String week) {
if (week.equals("星期一")) {
remind.setText("水力學,水文地質學,工程結構,馬克思主義基本原理");
} else if (week.equals("星期二")) {
remind.setText("地理信息系統,工程測量,工程結構");
} else if (week.equals("星期三")) {
remind.setText("工程結構,地理信息系統,水文地質學,水力學");
} else if (week.equals("星期四")) {
remind.setText("工程結構,工程測量,水力學,馬克思主義基本原理");
} else if (week.equals("星期五")) {
remind.setText("體育,水力學");
} else if (week.equals("星期六")) {
remind.setText("寶寶今天是周六 好好休息 看看電視想想我");
} else if (week.equals("星期日")) {
remind.setText("寶寶今天是周末,明天就是星期一了 今天你該去運動的!愛你愛你");
} else {
remind.setText("寶寶你要是看到這句話就證明世界末日了!!!!!!");
}
}
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
寫完回頭看,有幾個地方可以更好:
include 或 RecyclerView + 自訂 Adapter,Java 那邊也不必寫七組 if。HttpURLConnection 或 OkHttp。ExecutorService、Coroutine 或 ViewModel + LiveData,避免直接 new Thread 造成生命週期與記憶體問題。以上如果你只想直接拿source code,到這裡就可以了;想理解怎麼實作的,希望上面的拆解有幫上忙。
GridView 的簡單使用:打造九宮格列表
GridView 的簡單使用:打造九宮格列表 GridView 常用於展示網格式數據,比如九宮格。下面是一個完整的測試示例。 activity_main.xml: &l
PostgreSQL 9.5 新特性導覽:用 IMPORT FOREIGN SCHEMA 一鍵搬移外部表
PostgreSQL 9.5 新特性導覽:用 IMPORT FOREIGN SCHEMA 一鍵搬移外部表 下面用一個情境故事來說明:一位沒有跟上版本演進、也沒有主動學習
Android 架構模式整理:Flux、Clean Architecture、MVP 與 RxJava 實踐
Android 架構模式整理本文整理常見 Android 架構方向,包含 Flux、Clean Architecture、MVP,以及 MVP 搭配 RxJava 與 E
Android 建構系統解析:從資源編譯到 APK 打包
建構系統的角色Android 建構系統負責編譯、測試、打包與簽名應用。它可整合於 Android Studio,也可透過命令列執行,並支援自訂與擴充。主要能力建構系統可自