檢查網路狀態

檢查網路狀態是Android常用的方法, 在使用網路需要判斷手機是否連至網路開發者可以根據網路的狀態下, 引導UI要怎麼做, 或是怎麼處理錯誤等等, 相當的重要

方法如下:AndroidManifest.xml

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

檢查手機網路的方法1

 

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo != null) {
    //網路是否已連線(true or false)
    Boolean isConnect = networkInfo.isConnected();
    Log.d(TAG, "isConnected = " + isConnect);

    //網路連線方式名稱(WIFI or mobile)
    String typeName = networkInfo.getTypeName();
    Log.d(TAG, "typeName = " + typeName);

    //網路連線狀態
    NetworkInfo.State state = networkInfo.getState();
    Log.d(TAG, "networkInfo state = " + state);

    //網路是否可使用
    Boolean isAvailable = networkInfo.isAvailable();
    Log.d(TAG, "isAvailable = " + isAvailable);

    //網路是否已連接or連線中
    Boolean isConnectedOrConnecting = networkInfo.isConnectedOrConnecting();
    Log.d(TAG, "isConnectedOrConnecting = " + isConnectedOrConnecting);

    //網路是否故障有問題
    Boolean isFailover = networkInfo.isFailover();
    Log.d(TAG, "isFailover = " + isFailover);

    //網路是否在漫遊模式
    Boolean isRoaming = networkInfo.isRoaming();
    Log.d(TAG, "isRoaming = " + isRoaming);
}

通常的方法使用getActiveNetworkInfo就可以取得手機的網路狀態

方法2(只能使用在API21)

 
ConnectivityManager connectivityManager;
if ((connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)) != null) {
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    connectivityManager.registerNetworkCallback(builder.build(), new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {
            //有網路
            Log.d(TAG, "isConnected = true");

        }

        @Override
        public void onLost(Network network) {
            //未連網
            Log.d(TAG, "isConnected = false");
        }
    });
}

gitgub連結:

https://github.com/shineshane2000/Android_CheckNetwork


參考網頁:

http://dean-android.blogspot.com/2013/08/android-connectivity-network-active.html

https://stackoverflow.com/questions/27144026/how-can-i-receive-a-notification-when-the-device-loses-network-connectivity-in-a

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *