android 檢查能否上網

來源:互聯網
上載者:User

文章一:

首先在,AndroidManifest.xml 中增加存取權限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
然後在*.java中增加一個函數,如果不能訪問串連,那麼就退出,可以自己設定:
//檢查當前網路連接
public void checkInternet()
{
ConnectivityManager cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info=cm.getActiveNetworkInfo();
if(info!=null&&info.isConnected())
{
//能串連Internet
return;
}
else
{
//不能串連到
DisplayToast("you get not connect to the Internet,please log!");
try {
this.wait(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.finish();
}
}
android 許可權可以訪問下面連結:

http://developer.android.com/reference/android/Manifest.permission.html

文章二:Android檢查網路是否可用及上網請求

Android手機連網方式有以下幾種,要適應所有的方式。

Wifi

cmnet

cmwap

wifi和cmnet串連上就可以用了, cmwap是通過移動代理上網的, 有代理服務。但是移動聯通電信的代理IP和都不一樣。

先檢查網路是否可用及網路類型:

public static boolean isNetworkAvailable(Context ctx) {
boolean isConnection=false;
try {
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if(info != null ){
String typeName = info.getTypeName().toLowerCase(); // WIFI/MOBILE
if(!typeName.equals("wifi")){
if(null != info.getExtraInfo() ){
String wap = info.getExtraInfo().toLowerCase();
//3gnet/3gwap/uninet/uniwap/cmnet/cmwap/ctnet/ctwap
if(wap.endsWith("wap"))
isWap = true;
}
}
proxy=getproxy(ctx);
if(proxy != null && !typeName.equals("wifi"))
isWap =true;
isConnection= info.isAvailable();
}
} catch (Exception e) {
e.printStackTrace();
}
return isConnection;
}

設定HttpURLConnection串連參數

private static HttpURLConnection connectionNetWap(String nameUrl,String endUrl) throws IOException {
HttpURLConnection connection = null;
if(isWap){
URL url = new URL("http://"+proxy+":80/"+endUrl); //移動網關
connection = (HttpURLConnection )url.openConnection();
connection.setRequestProperty("X-Online-Host",nameUrl);
connection.setRequestProperty("Accept","*/*");
}else {
URL url = new URL(nameUrl+endUrl);
connection = (HttpURLConnection )url.openConnection();
}
return connection;
}

使用

public static String sendPostRequest(HashMap<String ,Object> params,String strUrl)
{
String result = null;
BufferedReader br = null;
HttpURLConnection connection = null;
DataOutputStream out = null;
InputStream instream = null;
try
{
// 參數
StringBuilder paraUrl = new StringBuilder();
int index=0;
if(params != null && !params.isEmpty() ){
for(Iterator it=params.entrySet().iterator();it.hasNext();){
Map.Entry e=(Map.Entry) it.next();
if(index >0 )
paraUrl.append("&");
paraUrl.append(e.getKey().toString());
paraUrl.append("=");
paraUrl.append(URLEncoder.encode(e.getValue().toString(), "utf-8"));
index++;
}
}

//非WAP方式, 這樣就可以了:
// URL url = new URL(strUrl);
// connection = (HttpURLConnection)url.openConnection();
//適應所有方式
connection=connectionNetWap(serviceUrl,strUrl);//support wap and net

// 設定是否向connection輸出,因為這個是post請求,參數要放在http本文內,因此需要設為true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post 請求不能使用緩衝
connection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成員函數,僅作用於當前函數
connection.setInstanceFollowRedirects(true);
// 配置本次串連的Content-type,配置為application/x-www-form-urlencoded的
// 意思是本文是urlencoded編碼過的form參數,下面我們可以看到我們對本文內容使用URLEncoder.encode進行編碼
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 串連,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會隱含的進行connect。
connection.connect();
out = new DataOutputStream(connection
.getOutputStream());
// 本文,本文內容其實跟get的URL中'?'後的參數字串一致
out.writeBytes(paraUrl.toString());
out.flush();
StringBuilder sBuilder = new StringBuilder();
//取得輸入資料流,並使用Reader讀取
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
instream=connection.getInputStream();
InputStreamReader isr = new InputStreamReader(instream, "utf-8");
int ichar;

while ((ichar = isr.read()) != 0) {
sBuilder.append((char) ichar);
}

result = sBuilder.toString();
//isr.close();
}
}
catch(Exception e)
{
Log.d("HTTP",e.getMessage());
LogMgr.getLogger(HttpUtil.class).warning(e.getMessage());
}finally{
if(null != connection)
connection.disconnect();
try{

if(null != out)
out.close(); // flush and close
}catch(IOException ioe){
Log.d("HTTP",ioe.getMessage());
}
}
return result;
}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.