轉自:http://www.cnblogs.com/tony-yang-flutter/p/androidtimeout.html
以用戶登錄爲例介紹用戶訪問網絡時的請求超時處理的兩種方法:
一. 使用android提供的工具類AsyncTask類,此類提供了一個AsyncTask.execute().get(timeout, unit);方法用於處理用戶的請求超時的操作,可以設置請求超時的時間(timeout)以及請求時間的單位(unit)。
例如:設置超時時間爲2秒,單位爲毫秒
try { AsyncTask(此處應該是它的實例化對象).execute().get(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { //此處用來處理用戶超時後的操作,例如:跳轉界面,彈出提示框。 //備註:此處不能直接進行界面操作,否則回報ANR異常。如果相處理界面操作,則和handler進行結合 }二. 第二種方法相對來說就比較複雜了,你需要自定義請求超時操作
1)自定義一個TimerTask,用於向handler發送請求超時消息
class MyTimerTask extends TimerTask{ @Override public void run() { handler.sendEmptyMessage(5000); } }
2)定義一個設置請求超時的方法,超時時間爲5秒
private void checkTimeOut(){ try{ timer = new Timer(); task = new MyTimerTask(); timer.schedule(task, 5000); }catch(Exception e){ Log.e("timer", e.getMessage()); } }
3)開發登錄線程
private class LoginThread extends Thread{ @Override public void run() { try{ try { checkTimeOut(); //下面用於編寫請求網絡數據的代碼 } catch (JSONException e) { e.printStackTrace(); } handler.sendEmptyMessage(5000); }catch(Exception e){ Log.e("LoginThread", e.getMessage()); } } }
4)在handler中處理請求超時或者請求成功的操作
Handler handler = new Handler() { public void handleMessage(Message msg) { switch(msg.what){ case 5000: //關掉timer timer.cancel(); //處理請求超時時要做的操作 break; } }; };
每天進步一點點!