編輯:關於 Android 程式設計
網路請求絕對不能寫在主執行緒上,否則畫面會整個卡住。本篇就用 AsyncTask 把下載動作丟到背景執行緒,同時在前景掛上一個等待提示。
public class downloadActivity extends Activity {
private TextView myTextView = null;
private Button button = null;
private static final String path = "https://192.168.0.179:8080/Myweb/download.do";
private ProgressDialog progressDialog = null;
private URL url = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
// 取出註冊頁面用 Intent 帶過來的使用者名稱
Intent intent = getIntent();
String value = intent.getStringExtra("username");
value = "hello" + " " + value;
myTextView = (TextView) findViewById(R.id.textView1);
myTextView.setText(value);
button = (Button) this.findViewById(R.id.download_btn);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setTitle("提示");
progressDialog.setMessage("請耐心等待,檔案正在下載中....");
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new DownloadFilesTask().execute(url);
}
});
}
private class DownloadFilesTask extends AsyncTask<URL, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(URL... urls) {
httpUtils.sendDownloadPost(urls[0]);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
宣告 AsyncTask 時需要指定三個型別,各自代表不同階段所使用的資料:
本文沒有做進度條,只用了 ProgressDialog 顯示等待提示,因此第二個參數留空;而檔案已經在 httpUtils 中直接寫入 SD 卡,不需要回傳結果,所以第三個參數也留空。
把耗時的網路下載交給 AsyncTask,主執行緒就能保持順暢,使用者的等待過程也有明確回饋。
Cordova 將網頁打包成 Android APK 完整流程
使用 Cordova 把網頁專案打包成 Android APK,適合已有 H5 頁面或希望快速封裝 Web 應用的開發者。整個流程主要包含環境準備、專案建立、平台新增、插
深入 Android Scroller 與 scrollTo:滑屏效果的原理與實作全解
本文從最基礎的座標概念出發,釐清 scrollTo() 與 scrollBy() 的差異,再帶入 Scroller 與 computeScroll() 的搭配用法,最後組
Android ActionBar 實作:以「下拉清單」作為導航模式
上一篇我們聊過 ActionBar 是 Android 3.0 的重要更新之一。這篇直接動手,寫一個開發中很常用的場景——用 ActionBar 實作基於下拉清單的導航。
仿 QQ 圓形頭像個性名片的實作解析
個性名片常見於社交與個人展示頁面,核心是把頭像、光環、氣泡與動畫結合。本文以仿 QQ 風格為例,說明自訂 ViewGroup 如何完成氣泡環繞與弧形展開效果。 氣泡位置