網頁原始碼檢視器
阿新 • • 發佈:2019-01-04
- 網頁原始碼檢視器
- 程式碼實現步驟
- [1]搭建UI
- [2]httpurlconnection類基本用法
@OnClick(R.id.btn) public void onViewClicked() { final String url = mEt.getText().toString().trim(); if (TextUtils.isEmpty(url)) { Toast.makeText(this, "網址不能為空" + url, Toast.LENGTH_SHORT).show(); }new Thread(new Runnable() { @Override public void run() { try { URL Url = new URL(url); HttpURLConnection conn = (HttpURLConnection) Url.openConnection(); int code = conn.getResponseCode(); Log.d(TAG,"run: " + code); if (code == 200) { InputStream is = conn.getInputStream(); Log.d(TAG, "run: " + is); String name = StreamUtils.StreamToString(is); Log.d(TAG, "run: " + name); Message message= mHandler.obtainMessage(); message.obj = name; mHandler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }).start(); }
-
- [3]把流轉換為String工具類
public class StreamUtils { private static ByteArrayOutputStream mBaos; public static String StreamToString(InputStream is) { try { mBaos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) { mBaos.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } return mBaos.toString(); } }
-
- [4]聯網要加上聯網許可權
<uses-permission android:name="android.permission.INTERNET" />
-
-
- 當加上許可權後 也會報如下錯誤
- android.os.NetworkOnMainThreadException 主執行緒(UI執行緒)訪問網路的異常. 主執行緒這個概念是谷歌提出的.
- 為什麼會報這個異常.谷歌要求 在主執行緒不能進行耗時(拷貝資料 連線網路)的操作,如果在主執行緒中進行耗時操作會報anr(應用無響應)異常; 如何解決?我們可以自己建立一個執行緒 來訪問網路.
- [5]當我們把訪問訪問的操作放到子執行緒又會報如下錯誤:
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
- 只有主執行緒(UI執行緒)才可以更新UI
- [6].handler(助手)的使用 —->負責執行緒的切換
- 6.1建立handler物件
-
@SuppressLint("HandlerLeak") private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { Log.d(TAG, "handleMessage: callback"); return false; } }) { @Override public void handleMessage(Message msg) { Log.d(TAG, "handleMessage: handlemessage"); String name = (String) msg.obj; mTv.setText(name); super.handleMessage(msg); } };
-
-
- 6.2 發訊息
-
Message message = mHandler.obtainMessage(); message.obj = name; mHandler.sendMessage(message);
-
- 7.scrollView 垂直滾動的view
<ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> </ScrollView>
-
-
- 注意:scrollView控制元件只能包裹一個孩子.如果想包裹多個在外面套一個佈局.
-