Android Q网络状态判断,亲测可用
程序员文章站
2024-01-02 17:36:52
package com.example.androidinterviewjxd.utils;import android.content.Context;import android.net.ConnectivityManager;import android.net.Network;import android.net.NetworkCapabilities;public class NetworkUtils { /** * 判断当前网络是否连接 * @para....
package com.example.androidinterviewjxd.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
public class NetworkUtils {
/**
* 判断当前网络是否连接
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
return networkCapabilities!=null;
}
/**
* 判断当前的网络类型是wifi,流量还是有线网络
* @param context
* @return
*/
public static String getCurrentNetworkType(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities==null){
return "no network";
}else if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
return "Wifi";
}else if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
return "Mobile";
}
// else if(networkCapabilities.hasCapability(NetworkCapabilities.TRANSPORT_ETHERNET)){
// return "Ethernet";
// }
return "other";
}
}
本文地址:https://blog.csdn.net/u012539700/article/details/108692198