編輯:關於 Android 程式設計
這個範例示範一個完整的天氣查詢流程:使用者輸入城市名稱、按下查詢、顯示等待對話框、在背景取得 XML 資料、解析後把結果填進表格。即使 Google 天氣 API 早已停止服務,這個範例在「背景執行緒 + Handler 更新 UI」以及「SAX 解析 XML」這兩個技術點上仍有參考價值。
public class WeatherActivity extends Activity {
private TextView txCity;
private Button btnSearch;
private Handler weatherhandler;
private Dialog progressDialog;
private Timer timer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timer = new Timer();
txCity = (TextView)findViewById(R.id.txCity);
btnSearch = (Button)findViewById(R.id.btnSearch);
progressDialog = new AlertDialog.Builder(this)
.setTitle("讀取數據中")
.setMessage("正在加載數據,請稍等")
.create();
weatherhandler = new Handler(){
public void handleMessage(Message msg){
final String cityName = txCity.getText().toString().trim();
searchWeather(cityName);
progressDialog.hide();
}
};
btnSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressDialog.show();
timer.schedule(new TimerTask() {
@Override
public void run() {
Message msg = new Message();
msg.setTarget(weatherhandler);
msg.sendToTarget();
}
},100);
}
});
}
private void searchWeather(String city){
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
XmlHandler handler = new XmlHandler();
reader.setContentHandler(handler);
URL url = new URL("https://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode(city));
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "GBK");
InputSource source = new InputSource(isr);
reader.parse(source);
List<Weather>weatherList = handler.getWeatherList();
TableLayout table = (TableLayout)findViewById(R.id.table);
table.removeAllViews();
for(Weather weather:weatherList){
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_VERTICAL);
ImageView img = new ImageView(this);
img.setImageDrawable(loadImage(weather.getImageUrl()));
img.setMinimumHeight(80);
row.addView(img);
TextView day = new TextView(this);
day.setText(weather.getDay());
day.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(day);
TextView temp = new TextView(this);
temp.setText(weather.getLowTemp()+"℃-"+weather.getHighTemp()+"℃");
temp.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(temp);
TextView condition = new TextView(this);
condition.setText(weather.getCondition());
condition.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(condition);
table.addView(row);
}
} catch (Exception e) {
e.printStackTrace();
new AlertDialog.Builder(this)
.setTitle("解析錯誤")
.setMessage("獲取天氣數據失敗,請稍候再試。")
.setNegativeButton("確定", null)
.show();
}
}
private Drawable loadImage(String imageUrl) {
try {
return Drawable.createFromStream((InputStream) new URL("https://www.google.com/"+imageUrl).getContent(), "test");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Android 規定只有建立 UI 執行緒的那條線程才能操作控制項。這裡的做法是:按鈕點擊後用 Timer 排一個稍後執行的任務,任務中發送 Message 給 weatherhandler,而 searchWeather() 的實際執行落在 Handler 所屬的執行緒上。這是早期 Android 常見的寫法。
天氣資料是 XML,這裡選用 SAX 串流解析(XmlHandler 繼承自 DefaultHandler,在 callbacks 中逐步收集元素)。相對於把整份文件載入記憶體的 DOM,SAX 在記憶體佔用上更有優勢,特別適合行動裝置。
結果以表格呈現,程式碼先 removeAllViews() 清空舊資料再逐列 addView,這是動態刷新表格的標準做法。
誠實說,這段程式碼有多處已不符合現代 Android 開發規範,列舉如下:
new Handler() 無指定 Looper,容易隱式綁定到錯誤的 Looper;建議顯式傳入 Looper.getMainLooper()。loadImage() 在解析迴圈中同步下載圖片,會嚴重拖慢畫面。應改用 Glide、Picasso 等圖片載入庫。如果你要的是「今天能用的天氣 App」,建議改用 OpenWeatherMap、中央氣象署開放資料平台等現行服務,搭配 Retrofit + Kotlin 協程 + 快取策略來實作。
微信怎麼用?加好友、建群與發紅包的入門教學
「怎麼使用微信」是個很大的問題,因為它能做的事太多:分享音樂與圖片、轉發連結、開群聊、發紅包,經營公眾號之後還能做內容與行銷。以下把最基礎的三件事——加好友、建群、發紅包
Android Framework 啟動流程解析:從 Zygote 到 SystemServer
Framework 啟動的整體目標Android 開機的過程,可以視為逐步建立系統運行所需環境的過程。從核心層、init 到 Zygote,再到 SystemServer
Fragment 完全解析(上):從誕生背景到動態使用
曾經有段時間,好像聊什麼都能扯到 Fragment,做什麼都要先問一句「Fragment 能不能實現」。玩笑歸玩笑,Fragment 之所以被反覆提起,是因為它確實解決了
安卓快速入門指南(中):動手做出一台計算機
第 3 節 計算機小應用 從這節開始,我們正式動手開發一個「計算機」應用。 3.1 計算機介面配置 這一節先把外觀做出來,讓它長得像一台計算機。 介面是由版面檔定義的,