編輯:關於 Android 程式設計
本範例做一個極簡版的瀏覽器雛形:上方一個輸入框與一個按鈕,下方用可滾動的文字區顯示該網址回傳的 HTML 原始碼。整個流程涵蓋了版面配置、子執行緒網路請求、Handler 更新 UI、編碼判斷與網路狀態檢查,是相當完整的 Networking 入門練習。

<EditText
android:id="@+id/et_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:text="@string/url_text" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_ie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_url"
android:onClick="sendHttp"
android:text="@string/btn_text" />
<ScrollView
android:id="@+id/sv_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_ie" >
<TextView
android:id="@+id/tv_ie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ie_text" />
</ScrollView>
用 ScrollView 包住 TextView 是必要的,因為網頁源碼往往遠超一屏高度。
strings.xml 中的文字資源:
<string name="url_text">https://luochuang.iteye.com/blog/1606231</string> <string name="btn_text">瀏覽</string> <string name="ie_text">顯示瀏覽網頁內容</string>
public class MainActivity extends Activity {
public EditText et_url;
public TextView tv_ie;
public NetWorkUtils netWorkUtils;
private Handler handler;
public String content;
public static final int TEXT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_url = (EditText) findViewById(R.id.et_url);
tv_ie = (TextView) findViewById(R.id.tv_ie);
netWorkUtils = new NetWorkUtils(this);
handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXT:
tv_ie.setText(content);
break;
default:
break;
}
}
};
}
public void sendHttp(View v) {
// 先確認網路可用,再啟動子執行緒
boolean flag = netWorkUtils.setActiveNetWork();
if (flag) {
new Thread(new Runnable() {
@Override
public void run() {
send();
handler.sendEmptyMessage(TEXT);
}
}).start();
}
}
public void send() {
String path = et_url.getText().toString();
if (path.isEmpty()) {
Toast.makeText(MainActivity.this, "訪問的 url 地址不能為空",
Toast.LENGTH_LONG).show();
} else {
content = HttpUtils.sendGet(path);
}
}
}
public class HttpUtils {
public static String sendGet(String path) {
String content = null;
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
if (httpURLConnection.getResponseCode() == 200) {
InputStream is = httpURLConnection.getInputStream();
byte data[] = StreamTools.isToData(is);
content = new String(data);
// 依內容自行判斷編碼
if (content.contains("gb2312")) {
content = new String(data, "gb2312");
}
}
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
讀流的部分抽成獨立工具,方便日後 reuse:
public class StreamTools {
public static byte[] isToData(InputStream is) throws IOException {
ByteArrayOutputStream bops = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
bops.write(buffer, 0, len);
}
return bops.toByteArray();
}
}
public class NetWorkUtils {
private Context context;
public ConnectivityManager connectivityManager;
public NetWorkUtils(Context context) {
this.context = context;
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public boolean setActiveNetWork() {
boolean flag = false;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
new AlertDialog.Builder(context)
.setTitle("網絡不可用")
.setMessage("可以設置網絡?")
.setPositiveButton("確認", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 直接跳去系統設定頁
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings"));
intent.setFlags(0x10200000);
context.startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
})
.show();
}
if (networkInfo != null) {
flag = true;
}
return flag;
}
}
偵測不到網路時不該直接失敗,而是詢問使用者是否前往設定開啟——這是很基本但常被忽略的體感細節。實務上更常用 Settings.ACTION_WIRELESS_SETTINGS 這個明確的 action 來開啟網路設定頁,比指定 ComponentName 更能相容不同 ROM。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
兩者缺一不可:INTERNET 讓你能連線,ACCESS_NETWORK_STATE 讓你能查詢連線狀態。
這份程式碼的結構清楚,適合當入門範例,但實際上線前建議調整:
content.contains("gb2312") 猜編碼不可靠,應優先讀取回應標頭的 Content-Type charset,再回退到解析 meta 標籤。setReadTimeout()。
應用內懸浮窗怎麼做?從 WindowManager 到服務與權限的完整拆解
先搞清楚懸浮窗是什麼 懸浮窗本質上就是一個系統級視窗,凌駕於應用之上。Android 把所有的視窗交給 WindowManagerService(WMS)統一管理,對 W
Android 好奇寶寶(05):PopupWindow 與懸浮窗
之所以把 PopupWindow 與懸浮窗放在一起講,是因為兩者的實現原理基本一致,只是細節上略有差異。 原理 使用系統服務 WindowManagerService,把
Android 利用簽名 SHA1 進行安全校驗的方法詳解
最近做安卓項目用到了百度地圖 API,申請 key 時需要填入「簽名的 SHA1」和「客戶端包名」,百度才會為我們生成 key。 於是就引出一個疑問:百度為何需要我們客戶
Android 中 Context 的應用總結與內存洩漏防範
概述 作為一名 Android 開發人員,每天使用最多的類中,恐怕 Context 可以排得上號了。因為 Context 對象在我們的項目裏實在是太常見了:加載資源、啟動