如何檢查Android網絡連接狀態
在發送任何HTTP請求前最好檢查下網絡連接狀態,這樣可以避免異常。這個教程將會介紹怎樣在你的應用中檢測網絡連接狀態。
創建新的項目
1.在Eclipse IDE中創建一個新的項目并把填入必須的信息。 File->New->Android Project
2.創建新項目后的第一步是要在AndroidManifest.xml文件中添加必要的權限。
- 為了訪問網絡我們需要 INTERNET 權限
- 為了檢查網絡狀態我們需要 ACCESS_NETWORK_STATE 權限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.detectinternetconnection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidDetectInternetConnectionActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
3.創建一個新的類,名為ConnectionDetector.java,并輸入以下代碼。
ConnectionDetector.java
package com.example.detectinternetconnection;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
4.當你需要在你的應用中檢查網絡狀態時調用isConnectingToInternet()函數,它會返回true或false。
ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false
5.在這個教程中為了測試我僅僅簡單的放置了一個按鈕。只要按下這個按鈕就會彈出一個 alert dialog 顯示網絡連接狀態。
6.打開 res/layout 目錄下的 main.xml 并創建一個按鈕。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Detect Internet Status" />
<Button android:id="@+id/btn_check"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Check Internet Status"
android:layout_centerInParent="true"/>
</RelativeLayout>
7.最后打開你的 MainActivity 文件并粘貼下面的代碼。在下面的代碼中我用一個 alert dialog 來顯示預期的狀態信息。
package com.example.detectinternetconnection;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AndroidDetectInternetConnectionActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
/**
* Check Internet status button click event
* */
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",
"You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
});
}
/**
* Function to display simple Alert Dialog
* @param context - application context
* @param title - alert dialog title
* @param message - alert message
* @param status - success/failure (used to set icon)
* */
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
運行并測試下你的程序吧!你將會得到類似下面的結果。
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!