1. 程式人生 > >判斷是否有網路

判斷是否有網路

private Button query; private EditText input; private TextView info;

private final int UPDATE_UI = 1;

@SuppressLint(“HandlerLeak”) private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_UI: info.setText(msg.obj.toString()); break; } } };

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

query = findViewById(R.id.query);
input = findViewById(R.id.input);
info = findViewById(R.id.info);

query.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View v) {

    if(/*!hasNetwork()*/!NetUtil.hasNetwork(PostRequestActivity.this)) {
      Toast.makeText(PostRequestActivity.this, "當前無網路", Toast.LENGTH_LONG).show();
      //
      return ;
    }

    new Thread(new Runnable() {
      @Override public void run() {
        //子執行緒呼叫查詢手機號資訊
        queryPhonNumInfo(input.getText().toString());
      }
    }).start();
  }
});

}

//是否有可用的網路 //private boolean hasNetwork() { //獲取網路連線管理服務 // ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //需要訪問網路狀態許可權 // NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isAvailable(); //}

//查詢手機號資訊 private void queryPhonNumInfo(String phonNum) { try { //1 url URL url = new URL(baseUrlStr); //2 開啟連線 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //3 請求方式 urlConnection.setRequestMethod(“POST”); //超時 urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); //標識需要輸出引數 urlConnection.setDoOutput(true); //輸出引數: tel=xxxxxxxxx String params = “tel=” + phonNum; urlConnection.getOutputStream().write(params.getBytes()); urlConnection.getOutputStream().flush(); //獲取結果 //狀態碼 int responseCode = urlConnection.getResponseCode(); String result; if (responseCode == 200) { result = stream2String(urlConnection.getInputStream(), “gbk”);

  } else {
    result = "error: " + responseCode;
  }
  //更新 ui
  mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

}

private String stream2String(InputStream is, String cs) throws IOException { StringBuilder stringBuilder = new StringBuilder();

InputStreamReader isr = new InputStreamReader(is, cs);
BufferedReader br = new BufferedReader(isr);

for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
  stringBuilder.append(tmp);
}

return stringBuilder.toString();

}