天天看點

Android-網絡監聽

直接在BaseActivity中引下面代碼:

private ConnectivityManager.NetworkCallback networkCallback;
private ConnectivityManager connectivityManager;



//網絡監聽
networkCallback = new NetworkCallbackImpl();
NetworkRequest.Builder builder = new NetworkRequest.Builder();
NetworkRequest request = builder.build();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(request, networkCallback);



private class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {

        /**
         * 網絡可用的回調連接配接成功
         */
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mNetErrorView != null) {
                        mNetErrorView.setVisibility(View.GONE);
                    }
                }
            });
        }

        /**
         * 實踐中在網絡連接配接正常的情況下,丢失資料會有回調
         */
        @Override
        public void onLosing(Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
        }

        /**
         * 網絡不可用時調用和onAvailable成對出現
         */
        @Override
        public void onLost(Network network) {
            super.onLost(network);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mNetErrorView != null) {
                        mNetErrorView.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

    }
           

mNetErrorView 是無網絡時顯示的一個view,寫一個這個view的布局net_status_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/net_status_bar_top"
    android:layout_width="match_parent"
    android:layout_height="@dimen/net_height"
    android:background="@drawable/net_warning_bar_bg"
    android:clickable="true"
    android:gravity="center_vertical"
    android:paddingLeft="@dimen/padding_normal"
    android:visibility="gone" >

    <TextView
        android:id="@+id/net_status_bar_info_top"
        android:layout_width="0.0dip"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginRight="@dimen/margin_normal"
        android:layout_weight="1.0"
        android:drawableLeft="@drawable/net_warning"
        android:drawablePadding="@dimen/padding_normal"
        android:gravity="center_vertical"
        android:text="@string/net_state_info"
        android:textColor="@color/black"
        android:textSize="@dimen/font_size_normal" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/margin_normal"
        android:contentDescription="@string/app_name"
        android:src="@drawable/net_warning_redirect"
        android:visibility="gone" />

</LinearLayout>
           

再在需要用到網絡監聽的Activity中繼承BaseActivity,再在目前Activity中

mNetErrorView = findViewById(R.id.net_status_bar_top);
           

最後在目前Activity的布局中适當的位置引入這個布局檔案即可

<include layout="@layout/net_status_bar" />
           

到此就完成了實時網絡監聽

如果需要已進入就監聽到網絡,需要在BaseActivity的onResume中監聽

if (!NetUtil.isNetConnected(this)) {
            if (mNetErrorView != null) {
                mNetErrorView.setVisibility(View.VISIBLE);
            }
        } else {
            if (mNetErrorView != null) {
                mNetErrorView.setVisibility(View.GONE);
            }
        }
           

監聽代碼

public static boolean isNetConnected(Context context) {
        boolean isNetConnected;
        // 獲得網絡連接配接服務
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
//			String name = info.getTypeName();
            isNetConnected = true;
        } else {
            isNetConnected = false;
        }
        return isNetConnected;
    }
           

再在onDestroy中取消注冊

connectivityManager.unregisterNetworkCallback(networkCallback);
           

上面代碼中所需要的一些尺寸,圖檔等可以自行先随意設定,先看效果,後期可換成項目所需的對應資源

最近自己寫了一個小程式,大家可以關注一下,附帶源碼:

Android-網絡監聽

搬磚之餘看個電影放松,掃碼關注,最新,最全的各種影視資源,省去各種VIP,直接觀看,你值得擁有

Android-網絡監聽