Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 項目實戰:完整拆解天氣預報應用的實現過程

編輯:關於 Android 程式設計

需求很直白:輸入城市名,點擊查詢,列表依次展示未來七天的天氣,並帶有入場動畫。

一、搞定數據來源

提供天氣服務的網站不少,通常都會開放 API 供開發者調用。這裡以聚合數據(https://www.juhe.cn/)為例:

註冊並登錄後進入控制台:

在左側菜單找到「我的數據」:

點擊「申請新數據」,這一步需要實名認證:

回到首頁選擇 API 標頁,找到免費的天氣預報接口:

申請後會獲得一定的免費調用額度:

接著複製平台分配的 AppKey(請使用你自己賬號下申請到的 Key,不要沿用示例中的值):

文檔中給出了請求示例,按規則拼接參數後即可在瀏覽器中直接驗證返回結果:

具體字段含義以官方文檔為準:

對應的數據模型類:

二、封裝網絡訪問工具類

先在 util 包下定義回調接口,把「請求」與「結果處理」解耦:

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

再實現基於 HttpURLConnection 的工具類,關鍵是內部開子線程發請求,避免阻塞主線程:

public class HttpUtil {
    public static void sendHttpRequest(final String address,
                                       final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            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);
                    connection.setDoInput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader =
                        new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

先單獨驗證接口

動手寫 UI 之前,先寫個測試用例確認接口能通、返回結構符合預期,這能省下大量排查時間:

public class WeatherGetTest extends AndroidTestCase {
    public void testGetData() {
        try {
            String cityName = URLEncoder.encode("菏澤", "utf-8");
            String weatherUrl = "https://v.juhe.cn/weather/index?format=2"
                    + "&cityname=" + cityName + "&key=" + YOUR_APP_KEY;
            HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
                public void onFinish(String response) {
                    System.out.println(response);
                }
                public void onError(Exception e) { }
            });
        } catch (Exception e) { }
    }
}

千萬別忘了加網絡權限:

<uses-permission android:name="android.permission.INTERNET" />

三、UI 層設計

主界面 activity_weather.xml:頂部是輸入框加查詢按鈕,下方是帶入場動畫的 ListView。

<RelativeLayout
    android:background="@drawable/city"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText android:id="@+id/etCity"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/etcity"
            android:hint="@string/etCity" />

        <ImageButton android:id="@+id/btnQuery"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/serch" />
    </LinearLayout>

    <ListView android:id="@+id/lvFutureWeather"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout1"
        android:layoutAnimation="@anim/weather_list_layout_animation" />
</RelativeLayout>

單條天氣的布局 activity_weather_listitem.xml,包含星期、日期、溫度、天氣四個文本:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_item_shape"
    android:padding="10dp">

    <TextView android:id="@+id/tvDayofWeek"
        android:layout_alignParentLeft="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/tvDate"
        android:layout_alignParentRight="true"
        android:layout_alignBaseline="@+id/tvDayofWeek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/tvTemperature"
        android:layout_below="@+id/tvDayofWeek"
        android:layout_alignLeft="@+id/tvDayofWeek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/tvWeather"
        android:layout_below="@+id/tvTemperature"
        android:layout_alignLeft="@+id/tvTemperature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

入場動畫怎麼做

動畫分兩個文件協作。先在 res/ 下新建 anim 目錄,定義單個 item 的縮放動畫 weather_list_animation.xml:

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <scale android:fromXScale="0.0" android:toXScale="1.0"
           android:fromYScale="0.0" android:toYScale="1.0"
           android:duration="1000"
           android:interpolator="@android:anim/accelerate_decelerate_interpolator" />
</set>

再用 layoutAnimation 把它應用到整個列表,delay 控制逐條出現的間隔:

<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:animation="@anim/weather_list_animation"
    android:animationOrder="normal"
    android:delay="2" />

四、數據模型與適配器

Weather 實體類持有四個字段:星期、日期、溫度、天氣,並提供完整的 getter/setter。

自定義 WeatherAdapter 繼承 ArrayAdapter,在 getView() 中做 ViewHolder 復用優化:

public class WeatherAdapter extends ArrayAdapter<Weather> {
    private int resourceId;

    public WeatherAdapter(Context context, int textViewResourceId,
                          List<Weather> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Weather weather = getItem(position);
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(getContext())
                    .inflate(resourceId, null);
            holder.tvDayOfWeek = convertView.findViewById(R.id.tvDayofWeek);
            holder.tvDate = convertView.findViewById(R.id.tvDate);
            holder.tvTemperature = convertView.findViewById(R.id.tvTemperature);
            holder.tvWeather = convertView.findViewById(R.id.tvWeather);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tvDayOfWeek.setText(weather.getDayOfWeek());
        holder.tvDate.setText(weather.getDate());
        holder.tvTemperature.setText(weather.getTemperature());
        holder.tvWeather.setText(weather.getWeather());
        return convertView;
    }

    private class ViewHolder {
        TextView tvDayOfWeek, tvDate, tvTemperature, tvWeather;
    }
}

五、Activity 串起全流程

WeatherActivity 的職責分三塊:回應點擊、發請求、解析並刷新列表。

public class WeatherActivity extends Activity {
    private EditText ecCity;
    private ImageButton btnQuery;
    private ListView lvFutureWeather;
    public static final int SHOW_RESPONSE = 1;
    private List<Weather> data;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == SHOW_RESPONSE) {
                String response = (String) msg.obj;
                if (response != null) {
                    parseWithJSON(response);
                    WeatherAdapter adapter = new WeatherAdapter(
                            WeatherActivity.this,
                            R.layout.activity_weather_listitem, data);
                    lvFutureWeather.setAdapter(adapter);

                    ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1);
                    scale.setDuration(1000);
                    LayoutAnimationController controller =
                            new LayoutAnimationController(scale, 0.6f);
                    lvFutureWeather.setLayoutAnimation(controller);
                }
            }
        }
    };

    private void parseWithJSON(String response) {
        data = new ArrayList<Weather>();
        JsonParser parser = new JsonParser();
        JsonObject obj = (JsonObject) parser.parse(response);
        String resultcode = obj.get("resultcode").getAsString();
        if ("200".equals(resultcode)) {
            JsonObject resultObj = obj.get("result").getAsJsonObject();
            JsonArray future = resultObj.get("future").getAsJsonArray();
            for (int i = 0; i < future.size(); i++) {
                JsonObject o = future.get(i).getAsJsonObject();
                data.add(new Weather(
                        o.get("week").getAsString(),
                        o.get("date").getAsString(),
                        o.get("temperature").getAsString(),
                        o.get("weather").getAsString()));
            }
        }
    }

    private void setListeners() {
        btnQuery.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String cityName = ecCity.getText().toString();
                try {
                    cityName = URLEncoder.encode(cityName, "utf-8");
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                String weatherUrl = "https://v.juhe.cn/weather/index?format=2"
                        + "&cityname=" + cityName + "&key=" + YOUR_APP_KEY;
                HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
                    public void onFinish(String response) {
                        Message message = new Message();
                        message.what = SHOW_RESPONSE;
                        message.obj = response;
                        handler.sendMessage(message);
                    }
                    public void onError(Exception e) {
                        System.out.println("訪問失敗");
                    }
                });
            }
        });
    }
}

六、兩個實踐要點

編碼必須處理。城市名包含中文,直接拼接會導致服務端無法識別,一定要先轉碼:

cityName = URLEncoder.encode("菏澤", "utf-8");

線程模型要清晰。網絡請求在子線程完成,解析與 UI 刷新通過 Handler 回到主線程。這是 Android 網絡開發的固定套路,寫錯了要麼卡頓,要麼直接拋 NetworkOnMainThreadException。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved