關於android4.0中訪問網路不能在主線程中進行以及Handler的使用

來源:互聯網
上載者:User

Google在4.0系統以後就禁止在主線程中進行網路訪問了,原因是:

主線程是負責UI的響應,如果在主線程進行網路訪問,超過5秒的話就會引發強制關閉,所以這種耗時的操作不能放在主線程裡。放在子線程裡,而子線程裡是不能對主線程的UI進行改變的,因此就引出了Handler,主線程裡定義Handler,子線程裡使用。



主線程的Handler定義:

Handler loginHandler = new Handler() {public void handleMessage(Message msg) {isNetError = msg.getData().getBoolean("isNetError");System.out.println(isNetError);if (proDialog != null) {proDialog.dismiss();}if (isNetError) {Toast.makeText(LoginActivity.this, "登陸失敗:\n1.請檢查您網路連接.\n2.請聯絡我們!",Toast.LENGTH_LONG).show();}// 使用者名稱和密碼錯誤else {Toast.makeText(LoginActivity.this, noticeMsg,Toast.LENGTH_LONG).show();// 清除以前的SharePreferences密碼clearSharePassword();}}};
主線程裡進行登入時候的子線程:

// 開一個線程進行登入驗證,主要是用於失敗,成功直接通過startAcitivity(Intent)轉向Thread loginThread = new Thread(new LoginFailureHandler());loginThread.start();

子線程的對Handler的使用:

/** * 登入處理函數 * @author wangfeng * @date 2013-12-19 09:25:42 * */class LoginFailureHandler implements Runnable {@Overridepublic void run() {/*userName = userNameEdit.getText().toString();password = loginPasswordEdit.getText().toString();*///驗證地址String validateURL=url+"/login";boolean loginState = validateLocalLogin(userNameEdit.getText().toString(), loginPasswordEdit.getText().toString(),validateURL);Log.d(this.toString(), "validateLogin");// 登陸成功//測試---開始loginState = true;//---測試結束if (loginState) {// 需要傳輸資料到登陸後的介面,Intent intent = new Intent();intent.setClass(LoginActivity.this, ListViewActivity.class);Bundle bundle = new Bundle();/*bundle.putString("MAP_USERNAME", userNameEdit.getText().toString());intent.putExtras(bundle);*/// 轉向登陸後的頁面proDialog.dismiss();startActivity(intent);} else {// 通過調用handler來通知UI主線程更新UI,Message message = new Message();Bundle bundle = new Bundle();bundle.putBoolean("isNetError", isNetError);message.setData(bundle);loginHandler.sendMessage(message);}}}
通過messgae.setData方法吧Budle帶進去,然後通過Handler.sendMessage把message放進去.在Handler的handlerMessage中處理。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.