NetUtils网络连接工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetUtils { /** * 获得网络连接是否可用 * @param context * @return */ public static boolean hasNetwork(Context context) { ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo workinfo = con.getActiveNetworkInfo(); if (workinfo == null || !workinfo.isAvailable()) { return false ; } return true ; } /** * 判断是否是wifi连接 */ public static boolean checkWifiState(Context context) { boolean isWifiConnect = true ; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] networkInfos = cm.getAllNetworkInfo(); for ( int i = 0 ; i < networkInfos.length; i++) { if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) { if (networkInfos[i].getType() == cm.TYPE_MOBILE) { isWifiConnect = false ; } if (networkInfos[i].getType() == cm.TYPE_WIFI) { isWifiConnect = true ; } } } return isWifiConnect; } /** * 打开网络设置界面 */ public static void openNet(Activity activity) { Intent intent = new Intent( "/" ); ComponentName cm = new ComponentName( "com.android.settings" , "com.android.settings.WirelessSettings" ); intent.setComponent(cm); intent.setAction( "android.intent.action.VIEW" ); activity.startActivityForResult(intent, 0 ); } } |
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步