編輯:關於 Android 程式設計
Handler 機制在 Android 開發中主要用於主線程與子線程的溝通:子線程發起網絡請求並把結果發送給主線程,再由主線程更新 UI。下面是一個使用 HttpURLConnection 訪問網絡並透過 Handler 回傳結果的完整示例:
package com.example.webview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private TextView reponseText;
private Button sendButton;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 接收消息並更新 UI 線程上的控件
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
reponseText.setText(response);
break;
default:
Toast.makeText(MainActivity.this, "show fail!!", Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = (Button) findViewById(R.id.send_request_id);
reponseText = (TextView) findViewById(R.id.text_id);
sendButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
sendRequestWithHttpURLConnection();
}
/** 開啟子線程發起網絡請求 */
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000); // 連接超時
connection.setReadTimeout(8000); // 讀取超時
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 透過 handler 把結果發送給主線程
Message message = handler.obtainMessage();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
這個示例濃縮了 Handler 通信的經典套路:handler.obtainMessage() 從消息池取一個 Message,設置好 what 與 obj 後透過 sendMessage() 發送;主線程的 handleMessage() 收到後再安全地更新 UI。這樣既遵守了「只有創建 View 的線程才能更新 View」的規則,又實現了子線程網絡請求與主線程界面刷新的解耦。
Android Scroller 滾動機制完全解析
Android 的 View 本身就具備滾動能力,核心方法是 scrollTo 與 scrollBy。若想做出更順滑、可控的滾動動畫,則需要搭配 Scroller 與 c
OpenCV for Android 人臉識別入門:從相冊選圖到框選臉部
在 Android 上做人臉識別,OpenCV 是常見的選擇。透過 Java API,開發者可以較快完成環境建置與基本流程,例如從相冊選圖、轉換成 OpenCV 可用的
高仿 To 圈註冊錄音界面:自定義 View 全解析
先看一眼 To 圈(QQ、微信等大部分 IM 也是大同小異)註冊頁的錄音效果: 為了還原這個效果,確實花了不少功夫。回頭總結,主要難點有三處: 難點一:隨音量變化的話筒
Android 源碼解析:LruCache 與其背後的 LinkedHashMap 機制
我認為在寫涉及資料結構或演算法的原始碼解析文章時,不該急著講用法或直接翻原始碼,而是要先交代這個結構的設計背景,再從設計出發講實作,最後回到原始碼,這樣才能真正讀懂。這