首頁

如何通過廣播監聽(tīng)網絡狀态的代碼實現

網絡狀态 2018-04-23 4566

一(yī)般我(wǒ)(wǒ)們打開(kāi)無線有時候會主動連接上一(yī)些沒有密匙的無線網絡,但是這時候手機上的應用程序仍然顯示的是沒有有效的數據連接,那麽除了用浏覽器打開(kāi)檢測之外(wài),其實還有一(yī)種比較有效的辦法,那就是通過廣播監聽(tīng)網絡狀态,下(xià)面app開(kāi)發報價燚軒科技跟大(dà)家分(fēn)享一(yī)下(xià)實現代碼:

權限

<uses-permission android:name="android.permission.INTERNET"/>

 <!--允許讀取網絡狀态-->

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

<!--允許讀取wifi網絡狀态-->

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

通過廣播監聽(tīng)網絡狀态的兩種方法

靜态注冊

<receiver android:name=".network.NetworkConnectChangedReceiver">

    <intent-filter>

        <action android:name="android.NET.conn.CONNECTIVITY_CHANGE" />

        <action android:name="android.Net.wifi.WIFI_STATE_CHANGED" />

        <action android:name="android.net.wifi.STATE_CHANGE" />

    </intent-filter>

</receiver> 

動态注冊 

第一(yī)步:在AndroidMainest文件裏面注冊 

<receiver android:name=".network.NetworkConnectChangedReceiver">

        </receiver> 

第二步:調用 Context registerReceiver(Receiver,IntentFilter) 進行注冊 

IntentFilter filter = new IntentFilter();

filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");

filter.addAction("android.net.wifi.STATE_CHANGE");

registerReceiver(mNetworkChangeListener,filter);

使用我(wǒ)(wǒ)們自定義的NetworkChangeListener廣播 

至于廣播的Action主要有三種類型: 

WifiManager.WIFI_STATE_CHANGED_ACTION 

這個監聽(tīng)wifi的打開(kāi)與關閉,與wifi的連接無關

WifiManager.NETWORK_STATE_CHANGED_ACTION 

這個監聽(tīng)wifi的連接狀态即是否連上了一(yī)個有效無線路由,

當上邊廣播的狀态是WifiManager.WIFI_STATE_DISABLING

WIFI_STATE_DISABLED的時候,根本不會接到這個廣播。

在上邊廣播接到廣播是WifiManager.WIFI_STATE_ENABLED狀态的同時也會接到這個廣播,

當然剛打開(kāi)wifi肯定還沒有連接到有效的無線

ConnectivityManager.CONNECTIVITY_ACTION

這個監聽(tīng)網絡連接的設置,包括wifi和移動數據的打開(kāi)和關閉。.

最好用的還是這個監聽(tīng)。wifi如果打開(kāi),關閉,以及連接上可用的連接都會接到監聽(tīng)。

這個廣播的最大(dà)弊端是比上邊兩個廣播的反應要慢(màn),如果隻是要監聽(tīng)wifi

我(wǒ)(wǒ)覺得還是用上邊兩個配合比較合适。

/**

 * 網絡改變監控廣播

 * <p>

 * 監聽(tīng)網絡的改變狀态,隻有在用戶操作網絡連接開(kāi)關(wifi,mobile)的時候接受廣播,

 * 然後對相應的界面進行相應的操作,并将 狀态 保存在我(wǒ)(wǒ)們的APP裏面

 * <p>

 * <p>

 * Created by xujun

 */

public class NetworkConnectChangedReceiver extends BroadcastReceiver {

    private static final String TAG = "xujun";

    public static final String TAG1 = "xxx";

    @Override

    public void onReceive(Context context, Intent intent) {

        // 這個監聽(tīng)wifi的打開(kāi)與關閉,與wifi的連接無關

        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {

            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);

            Log.e(TAG1, "wifiState" + wifiState);

            switch (wifiState) {

                case WifiManager.WIFI_STATE_DISABLED:

                    APP.getInstance().setEnablaWifi(false);

                    break;

                case WifiManager.WIFI_STATE_DISABLING:

                    break;

                case WifiManager.WIFI_STATE_ENABLING:

                    break;

                case WifiManager.WIFI_STATE_ENABLED:

                    APP.getInstance().setEnablaWifi(true);

                    break;

                case WifiManager.WIFI_STATE_UNKNOWN:

                    break;

                default:

                    break;

            }

        }

        // 這個監聽(tīng)wifi的連接狀态即是否連上了一(yī)個有效無線路由,當上邊廣播的狀态是WifiManager

        // .WIFI_STATE_DISABLING,和WIFI_STATE_DISABLED的時候,根本不會接到這個廣播。

        // 在上邊廣播接到廣播是WifiManager.WIFI_STATE_ENABLED狀态的同時也會接到這個廣播,

        // 當然剛打開(kāi)wifi肯定還沒有連接到有效的無線

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {

            Parcelable parcelableExtra = intent

                    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

            if (null != parcelableExtra) {

                NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;

                State state = networkInfo.getState();

                boolean isConnected = state == State.CONNECTED;// 當然,這邊可以更精确的确定狀态

                Log.e(TAG1, "isConnected" + isConnected);

                if (isConnected) {

                    APP.getInstance().setWifi(true);

                } else {

                    APP.getInstance().setWifi(false);

                }

            }

        }

        // 這個監聽(tīng)網絡連接的設置,包括wifi和移動數據的打開(kāi)和關閉。.

        // 最好用的還是這個監聽(tīng)。wifi如果打開(kāi),關閉,以及連接上可用的連接都會接到監聽(tīng)。見log

        // 這個廣播的最大(dà)弊端是比上邊兩個廣播的反應要慢(màn),如果隻是要監聽(tīng)wifi,我(wǒ)(wǒ)覺得還是用上邊兩個配合比較合适

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {

            ConnectivityManager manager = (ConnectivityManager) context

                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            Log.i(TAG1, "CONNECTIVITY_ACTION");

            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();

            if (activeNetwork != null) { // connected to the internet

                if (activeNetwork.isConnected()) {

                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {

                        // connected to wifi

                        APP.getInstance().setWifi(true);

                        Log.e(TAG, "當前WiFi連接可用 ");

                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {

                        // connected to the mobile provider's data plan

                        APP.getInstance().setMobile(true);

                        Log.e(TAG, "當前移動網絡連接可用 ");

                    }

                } else {

                    Log.e(TAG, "當前沒有網絡連接,請确保你已經打開(kāi)網絡 ");

                }

                Log.e(TAG1, "info.getTypeName()" + activeNetwork.getTypeName());

                Log.e(TAG1, "getSubtypeName()" + activeNetwork.getSubtypeName());

                Log.e(TAG1, "getState()" + activeNetwork.getState());

                Log.e(TAG1, "getDetailedState()"

                        + activeNetwork.getDetailedState().name());

                Log.e(TAG1, "getDetailedState()" + activeNetwork.getExtraInfo());

                Log.e(TAG1, "getType()" + activeNetwork.getType());

            } else {   // not connected to the internet

                Log.e(TAG, "當前沒有網絡連接,請确保你已經打開(kāi)網絡 ");

                APP.getInstance().setWifi(false);

                APP.getInstance().setMobile(false);

                APP.getInstance().setConnected(false); 

            }

        }

    }

}

public class NetStateUtils {

    /**

     * 判斷當前網絡是否是移動網絡

     *

     * @param context

     * @return boolean

     */

    public static boolean is3G(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {

            return true;

        }

        return false;

    }

    /**

     * 判斷當前網絡是否是wifi網絡

     *

     * @param context

     * @return boolean

     */

    public static boolean isWifi(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {

            return true;

        }

        return false;

    }

    /**

     * 判斷當前網絡是否是2G網絡

     *

     * @param context

     * @return boolean

     */

    public static boolean is2G(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE

                || activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo

                .getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {

            return true;

        }

        return false;

    }

 

    /**

     * wifi是否打開(kāi)

     */

    public static boolean isWifiEnabled(Context context) {

        ConnectivityManager mgrConn = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        TelephonyManager mgrTel = (TelephonyManager) context

                .getSystemService(Context.TELEPHONY_SERVICE);

        return ((mgrConn.getActiveNetworkInfo() != null && mgrConn

                .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel

                .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);

    }

 

    /**

     * 判斷是否有網絡連接

     *

     * @param context

     * @return

     */

    public static boolean isNetworkConnected(Context context) {

        if (context != null) {

            // 獲取手機所有連接管理對象(包括對wi-fi,net等連接的管理)

            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context

                    .CONNECTIVITY_SERVICE);

            // 獲取NetworkInfo對象

            NetworkInfo networkInfo = manager.getActiveNetworkInfo();

            //判斷NetworkInfo對象是否爲空

            if (networkInfo != null)

                return networkInfo.isAvailable();

&nb

分(fēn)享:
分(fēn)享到微信朋友圈 +
打開(kāi)微信,點擊底部的“發現”,使用 “掃一(yī)掃” 即可将網頁分(fēn)享到我(wǒ)(wǒ)的朋友圈。 如何使用?
推薦文章

熱貼More +

服務範圍More +

聯系我(wǒ)(wǒ)們

請掃二維碼聯系客服

854221200@qq.com

185-3825-9583

QQ客服

關于  ·  招聘  ·  案例中(zhōng)心  ·  網站地圖

©@2018 燚軒科技版權所有 豫ICP備16015002号-4

百度提供搜索支持