java Android的网络连接接收器。无论何时连接或断开网络,都会通知您

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Android的网络连接接收器。无论何时连接或断开网络,都会通知您相关的知识,希望对你有一定的参考价值。

private class ConnectivityBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
                || mListening == false) {
            Log.w(TAG, "onReceived() called with " + mState.toString()
                    + " and " + intent);
            return;
        }
        boolean noConnectivity = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        if (noConnectivity) {
            mState = State.NOT_CONNECTED;
        } else {
            mState = State.CONNECTED;
        }
        mNetworkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        mOtherNetworkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
        mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
        mIsFailover = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_IS_FAILOVER, false);
        if (DBG) {
            Log.d(TAG,
                    "onReceive(): mNetworkInfo="
                            + mNetworkInfo
                            + " mOtherNetworkInfo = "
                            + (mOtherNetworkInfo == null ? "[none]"
                                    : mOtherNetworkInfo + " noConn="
                                            + noConnectivity) + " mState="
                            + mState.toString());
        }
        // Notifiy any handlers.
        Iterator<Handler> it = mHandlers.keySet().iterator();
        while (it.hasNext()) {
            Handler target = it.next();
            Message message = Message.obtain(target, mHandlers.get(target));
            // TODO add extra data
            target.sendMessage(message);
        }
    }
};

以上是关于java Android的网络连接接收器。无论何时连接或断开网络,都会通知您的主要内容,如果未能解决你的问题,请参考以下文章

Android 9.0/P http 网络请求的问题

如何使用java套接字编程知道网络何时关闭

Android:检测何时安装应用程序

java Android网络状态接收器。

如何检测何时在 Android 中设置了新警报

使用不安全的 RFCOMM 蓝牙套接字时,android 何时显示配对对话框?