IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android网络状态变化监听 -- 结合registerNetworkCallback和广播 -> 正文阅读

[移动开发]Android网络状态变化监听 -- 结合registerNetworkCallback和广播

在这里插入图片描述

说明

??AndroidAndroid针对网络状态变化的监听,在应用内我们通用需要监听设备网络状态的变化,作出相应的业务处理,需要一个方便的、全局的监听实现。。
??针对不同设备的系统版本,使用不同的API方法实现;
??注意使用广播监听网络状态在高版本的适配问题;

??1、Build.VERSION.SDK_INT >= Build.VERSION_CODES.N,使用connectivityManager.registerDefaultNetworkCallback()方法;
??2、Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP,使用connectivityManager.registerNetworkCallback(networkRequest, new MyNetworkCallback());方法;
??3、其它系统版本使用广播监听;
??4、NetworkListenerHelper可以添加多个页面的监听,当某个页面需要监听网络时,就可以添加到监听者集合中,页面关闭时移除这个监听者,也可以使用事件总线;

核心实现

NetworkListenerHelper

package com.windfallsheng.networkstatusmonitor;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import androidx.annotation.NonNull;
import com.windfallsheng.by_lib.command.NetworkStatus;
import com.windfallsheng.by_lib.command.ObjectCachePool;
import com.windfallsheng.by_lib.utils.CollectionUtils;
import com.windfallsheng.by_lib.utils.LogUtils;
import com.windfallsheng.by_lib.utils.NetworkUtils;
import com.windfallsheng.networkstatusmonitor.broadcast.NetworkBroadcastReceiver;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:29
 * @description: 网络状态变化的监听类,根据android不同版本的系统,有 {@link ConnectivityManager#registerNetworkCallback}和注册广播两种实现方式;
 */
public class NetworkListenerHelper {

    private final String TAG = "NetworkListenerHelper";

    private Context mContext;

    private volatile CopyOnWriteArrayList<NetworkConnectedListener> mListenerList = null;

    private NetworkListenerHelper(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * 先从内存中取,若没有则创建对象,并缓存到内存中;
     */
    public static synchronized NetworkListenerHelper obtain() {
        NetworkListenerHelper obj = (NetworkListenerHelper) ObjectCachePool.getInstance()
                .getObj(NetworkListenerHelper.class);
        if (obj == null) {
            throw new NullPointerException("The NetworkListenerHelper instance has not been initialized.");
        }
        return obj;
    }
    /**
     * 先从内存中取,若没有则创建对象,并缓存到内存中;
     */
    public static synchronized NetworkListenerHelper init(Context context) {
        NetworkListenerHelper obj = (NetworkListenerHelper) ObjectCachePool.getInstance()
                .getObj(NetworkListenerHelper.class);
        if (obj == null) {
            obj = new NetworkListenerHelper(context);
        }
        ObjectCachePool.getInstance().cache(obj);
        return obj;
    }

    /**
     * 注册网络状态的监听;
     */
    @SuppressLint("MissingPermission")
    public void registerNetworkListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                LogUtils.el(TAG, "registerNetworkListener#return#connectivityManager=" + connectivityManager);
                return;
            }
            connectivityManager.registerDefaultNetworkCallback(new MyNetworkCallback());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                LogUtils.el(TAG, "registerNetworkListener#return#connectivityManager=" + connectivityManager);
                return;
            }
            final NetworkRequest.Builder builder;
            builder = new NetworkRequest.Builder();
            builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
            NetworkRequest networkRequest = builder.build();
            connectivityManager.registerNetworkCallback(networkRequest, new MyNetworkCallback());
        } else {
            // 通过广播的方式监听网络;
            NetworkBroadcastReceiver mNetworkBroadcastReceiver = new NetworkBroadcastReceiver();
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            mContext.registerReceiver(mNetworkBroadcastReceiver, filter);
            mNetworkBroadcastReceiver.setBroadcastCallback((isConnected, networkStatus) -> {
                //
                notifyAllListeners(isConnected, networkStatus);
            });
        }
    }

    /**
     * 通知所有接收者;
     *
     * @param isConnected
     * @param networkStatus
     */
    private void notifyAllListeners(boolean isConnected, NetworkStatus networkStatus) {
        if (CollectionUtils.isNotEmpty(mListenerList)) {
//            mListenerList.stream().forEach(networkConnectedListener -> {
//                networkConnectedListener.onNetworkConnected(isConnected, networdStatus);
//            });
            for (NetworkConnectedListener listener : mListenerList) {
                if (listener != null) {
                    listener.onNetworkConnected(isConnected, networkStatus);
                }
            }
        }
    }

    /**
     * 添加回调的监听者;
     */
    public synchronized void addListener(NetworkConnectedListener listener) {
        if (listener == null) {
            return;
        }
        if (mListenerList == null) {
            mListenerList = new CopyOnWriteArrayList<>();
        }
        // 防止重复添加;
        if (!mListenerList.contains(listener)) {
            mListenerList.add(listener);
        }
    }

    /**
     * 移除某个回调实例;
     *
     * @param listener
     */
    public synchronized void removeListener(NetworkConnectedListener listener) {
        if (listener != null && CollectionUtils.isNotEmpty(mListenerList)) {
            mListenerList.remove(listener);
        }
    }

    public void unregisterNetworkCallback() {
        if (mContext == null) {
            return;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            LogUtils.el(TAG, "registerNetworkListener#return#connectivityManager=" + connectivityManager);
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            connectivityManager.unregisterNetworkCallback(new ConnectivityManager.NetworkCallback());
        }
    }

    public interface NetworkConnectedListener {
        /**
         * @param isConnected
         * @param networkStatus
         */
        void onNetworkConnected(boolean isConnected, NetworkStatus networkStatus);
    }

    @SuppressLint("NewApi")
    private class MyNetworkCallback extends ConnectivityManager.NetworkCallback {

        //当用户与网络连接(或断开连接)(可以是WiFi或蜂窝网络)时,这两个功能均作为默认回调;
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);
            LogUtils.d(TAG, "onAvailable#network=" + network);
            // 需要同步获取一次网络状态;
            final NetworkStatus netWorkState = NetworkUtils.getNetWorkState(mContext);
            LogUtils.d(TAG, "onAvailable#netWorkState=" + netWorkState);
            //
            notifyAllListeners(true, netWorkState);
        }

        @Override
        public void onLost(@NonNull Network network) {
            super.onLost(network);
            LogUtils.d(TAG, "onLost#network=" + network);
            // 需要同步获取一次网络状态;
            final NetworkStatus netWorkState = NetworkUtils.getNetWorkState(mContext);
            LogUtils.d(TAG, "onLost#netWorkState=" + netWorkState);
            //
            notifyAllListeners(false, netWorkState);
        }

        @Override
        public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            LogUtils.d(TAG, "onCapabilitiesChanged#network=" + network);
//            LogUtils.d(TAG, "onCapabilitiesChanged#network=" + network + ", networkCapabilities=" + networkCapabilities);
            // 表示能够和互联网通信(这个为true表示能够上网)
            if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    LogUtils.d(TAG, "onCapabilitiesChanged#网络类型为wifi");
                } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    LogUtils.d(TAG, "onCapabilitiesChanged#蜂窝网络");
                } else {
                    LogUtils.d(TAG, "onCapabilitiesChanged#其他网络");
                }
            }
        }
    }

}

广播NetworkBroadcastReceiver

package com.windfallsheng.networkstatusmonitor.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.text.TextUtils;

import com.windfallsheng.by_lib.command.NetworkStatus;
import com.windfallsheng.by_lib.utils.LogUtils;
import com.windfallsheng.by_lib.utils.NetworkUtils;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:28
 * @description: 网络状态的监听广播
 */
public class NetworkBroadcastReceiver extends BroadcastReceiver {

    private final String TAG = "NetworkBroadcastReceiver";

    private NetworkBroadcastCallback mBroadcastCallback;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null) {
            LogUtils.el(TAG, "onReceive#intent=" + intent);
            return;
        }
        final String action = intent.getAction();
        LogUtils.d(TAG, "onReceive#action=" + action);
        if (TextUtils.equals(intent.getAction(), ConnectivityManager.CONNECTIVITY_ACTION)) {
            // 申请权限;
//        if (!XXPermissions.isGrantedPermission(context, Permission.WRITE_EXTacERNAL_STORAGE,
//                Permission.READ_EXTERNAL_STORAGE)) {
//        }
//        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//        if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
//            //WIFI和移动网络均未连接
//            netContentListener.netContent(false);
//        } else {
//            //WIFI连接或者移动网络连接
//            netContentListener.netContent(true);
//        }
            final boolean isOnline = NetworkUtils.isOnline(context);
            final NetworkStatus networkStatus = NetworkUtils.getNetWorkState(context);
            LogUtils.d(TAG, "onReceive#isOnline=" + isOnline + ", networdStatus=" + networkStatus);
            if (mBroadcastCallback != null) {
                mBroadcastCallback.onNetworkBroadcastCallback(isOnline, networkStatus);
            }
        }
    }

    public void setBroadcastCallback(NetworkBroadcastCallback broadcastCallback) {
        mBroadcastCallback = broadcastCallback;
    }

    public interface NetworkBroadcastCallback {
        /**
         * 根据监听的结果返回连接状态和网络状态;
         *
         * @param isConnected
         * @param networkStatus
         */
        void onNetworkBroadcastCallback(boolean isConnected, NetworkStatus networkStatus);
    }
}

调用:

package com.windfallsheng.networkstatusmonitor;

import android.app.Application;
import com.windfallsheng.by_lib.command.BaseApplicationHelper;
import com.windfallsheng.by_lib.utils.LogUtils;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:28
 * @description:
 */
public class ApplicationSupporter extends Application {

    private static ApplicationSupporter mApplicationSupporter;
    private final String TAG = "ApplicationSupporter";

    public static ApplicationSupporter getInstance() {
        return mApplicationSupporter;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApplicationSupporter = this;
        BaseApplicationHelper.getInstance()
                .initApplicationContext(mApplicationSupporter);
        // 日志开关;
        LogUtils.initDebug(true);
        // 注册网络状态监听;
        NetworkListenerHelper.init(mApplicationSupporter)
                .registerNetworkListener();
    }
}
package com.windfallsheng.networkstatusmonitor;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.windfallsheng.by_lib.command.NetworkStatus;
import com.windfallsheng.by_lib.utils.LogUtils;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:29
 * @description:
 */
public class MainActivity extends AppCompatActivity implements NetworkListenerHelper.NetworkConnectedListener {

    private final String TAG = "MainActivity";
    private TextView mTvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvResult = findViewById(R.id.tv_result);

        // 网络状态回调;
        NetworkListenerHelper.obtain()
                .addListener(MainActivity.this);
    }

    @Override
    public void onNetworkConnected(boolean isConnected, NetworkStatus networkStatus) {
        LogUtils.d(TAG, "onNetworkConnected#isConnected=" + isConnected);
        final String trim = mTvResult.getText().toString();
        final int status = networkStatus.getStatus();
        final String desc = networkStatus.getDesc();
        mTvResult.post(() -> mTvResult.setText("\n网络变化通知:status=" + status + ", desc=" + desc + "\n" + trim));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkListenerHelper.obtain()
                .removeListener(MainActivity.this);
    }
}

其它:

package com.windfallsheng.by_lib.command;

import android.text.TextUtils;

import com.windfallsheng.by_lib.utils.LogUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * @Author: lzsheng
 * @date: 2021/9/28 16:05
 * @description: 用于相关的一些业务对象的缓存,保证用户在登录及登录状态中的部分相关的实例对象唯一,
 * 用户退出账号可直接清除相关内存缓存;
 */
public class ObjectCachePool {

    private static volatile ConcurrentMap<String, Object> OBJECT_CACHE = null;
    private final String TAG = ObjectCachePool.class.getSimpleName();

    private ObjectCachePool() {
    }

    public static ObjectCachePool getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public synchronized void cache(Object obj) {
        if (OBJECT_CACHE == null) {
            OBJECT_CACHE = new ConcurrentHashMap<>();
        }
        String key = obj.getClass().getName();
        LogUtils.d(TAG, "method:cache#key=" + key + ", obj=" + obj);
        OBJECT_CACHE.put(key, obj);
    }

    public synchronized void cache(String key, Object obj) {
        if (OBJECT_CACHE == null) {
            OBJECT_CACHE = new ConcurrentHashMap<>();
        }
        LogUtils.d(TAG, "method:cache#key=" + key + ", obj=" + obj);
        OBJECT_CACHE.put(key, obj);
    }

    public synchronized boolean containsObj(String key) {
        if (OBJECT_CACHE == null) {
            return false;
        }
        Object obj = getObj(key);
        if (obj != null) {
            return true;
        }
        return false;
    }

    public Object getObj(Class<?> clazz) {
        LogUtils.d(TAG, "method:getObj#clazz=" + clazz);
        final String className = clazz.getName();
        LogUtils.d(TAG, "method:getObj#className=" + className);
        return getObj(className);
    }

    public Object getObj(String key) {
        LogUtils.d(TAG, "method:getObj#key=" + key);
        if (OBJECT_CACHE == null) {
            return null;
        }
        return OBJECT_CACHE.get(key);
    }

    public synchronized void remove(Class<?> clazz) {
        LogUtils.d(TAG, "method:getObj#clazz=" + clazz);
        final String className = clazz.getName();
        LogUtils.d(TAG, "method:getObj#className=" + className);
        remove(className);
    }

    public synchronized void remove(String key) {
        LogUtils.d(TAG, "method:remove#key=" + key);
        if (OBJECT_CACHE != null && !TextUtils.isEmpty(key)) {
            OBJECT_CACHE.remove(key);
        }
        LogUtils.d(TAG, "method:remove#OBJECT_CACHE=" + OBJECT_CACHE);
    }

    public synchronized void evictAll() {
        LogUtils.d(TAG, "method:evictAll");
        if (OBJECT_CACHE != null) {
            OBJECT_CACHE.clear();
            OBJECT_CACHE = null;
        }
        LogUtils.d(TAG, "method:evictAll#OBJECT_CACHE=" + OBJECT_CACHE);
    }

    public synchronized Object obtainInstance(Class<?> clazz) {
        LogUtils.d(TAG, "method:obtainInstance#in#arguments:clazz=" + clazz);
        final String className = clazz.getName();
        LogUtils.d(TAG, "method:obtainInstance#className=" + className);
        Object obj = getObj(className);
        LogUtils.d(TAG, "method:obtainInstance#obj=" + obj);
        if (obj == null) {
            synchronized (ObjectCachePool.class) {
                if (obj == null) {
                    try {
                        Constructor c0 = clazz.getDeclaredConstructor();
                        // 对于部分类可能的私有构造方法的处理;
                        c0.setAccessible(true);
                        obj = c0.newInstance();
                        LogUtils.d(TAG, "method:obtainInstance#newInstance#obj=" + obj +
                                ", hashCode=" + obj.hashCode());
                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
                        LogUtils.el(TAG, "method:obtainInstance#e=" + e.getMessage());
                    } catch (InstantiationException e) {
//                        e.printStackTrace();
                        LogUtils.el(TAG, "method:obtainInstance#e=" + e.getMessage());
                    } catch (NoSuchMethodException e) {
//                        e.printStackTrace();
                        LogUtils.el(TAG, "method:obtainInstance#e=" + e.getMessage());
                    } catch (InvocationTargetException e) {
//                        e.printStackTrace();
                        LogUtils.el(TAG, "method:obtainInstance#e=" + e.getMessage());
                    }
                }
            }
            if (obj != null) {
                LogUtils.d(TAG, "method:obtainInstance#cache#obj=" + obj);
                cache(className, obj);
            }
        }
        return obj;
    }

    private static class SingletonHolder {
        private static ObjectCachePool INSTANCE = new ObjectCachePool();
    }

}

package com.windfallsheng.by_lib.command;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:30
 * @description: 网络连接状态的枚举
 */
public enum NetworkStatus {

    /**
     * ;
     */
    NONE(-1, "无网络连接"),
    /**
     * 解析数据内容失败
     */
    MOBILE(0, "移动网络连接"),
    /**
     * 网络问题
     */
    WIFI(1, "WIFI连接");

    private int status;
    private String desc;

    NetworkStatus(int code, String msg) {
        this.status = code;
        this.desc = msg;
    }

    public int getStatus() {
        return status;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "NetwordStatus{" +
                "status=" + status +
                ", desc='" + desc + '\'' +
                "} " + super.toString();
    }
}

package com.windfallsheng.by_lib.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;

import com.windfallsheng.by_lib.command.NetworkStatus;

/**
 * @Author: lzsheng
 * @date: 2021/11/15 17:31
 * @description:
 */
public class NetworkUtils {

    @SuppressLint("MissingPermission")
    public static NetworkStatus getNetWorkState(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobileNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mobileNetInfo != null && mobileNetInfo.isAvailable()) {
                //WIFI和移动网络均未连接
                return NetworkStatus.MOBILE;
            } else if (wifiNetInfo != null && wifiNetInfo.isAvailable()) {
                //WIFI和移动网络均未连接
                return NetworkStatus.WIFI;
            } else {
                return NetworkStatus.NONE;
            }
        } else {
            if (isMobileConnected(context)) {
                return NetworkStatus.MOBILE;
            } else if (isWifiConnected(context)) {
                return NetworkStatus.WIFI;
            } else {
                return NetworkStatus.NONE;
            }
        }

//            //获取所有网络连接的信息
//            Network[] networks = connMgr.getAllNetworks();
//            //通过循环将网络信息逐个取出来
//            for (int i = 0; i < networks.length; i++) {
//                //获取ConnectivityManager对象对应的NetworkInfo对象
//                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
//                if (networkInfo.isConnected()) {
//                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//                        return NetwordStatus.WIFI;
//                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
//                        return NetwordStatus.MOBILE;
//                    }
//                }
//            }
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static boolean isOnline(Context context) {
        if (context == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ConnectivityManager connMgr = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            return (networkInfo != null && networkInfo.isAvailable());
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Network activeNetwork = connectivityManager.getActiveNetwork();
            if (activeNetwork == null) {
                return false;
            }
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
            if (networkCapabilities != null) {
                return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            }
        }
        return false;
    }

    @SuppressLint("MissingPermission")
    public static boolean isWifiConnected(Context context) {
        if (context == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Network activeNetwork = connectivityManager.getActiveNetwork();
            if (activeNetwork == null) {
                return false;
            }
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
            if (networkCapabilities != null) {
                return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
            }
        }
        return false;
    }

    @SuppressLint("MissingPermission")
    public static boolean isMobileConnected(Context context) {
        if (context == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Network activeNetwork = connectivityManager.getActiveNetwork();
            if (activeNetwork == null) {
                return false;
            }
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
            if (networkCapabilities != null) {
                return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
            }
        }
        return false;
    }

}

总结

??业务并不复杂,不再详细赘述,查看下载地址:https://download.csdn.net/download/Silence1515/42476740

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-11-16 18:57:11  更:2021-11-16 18:58:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 5:56:42-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码