分享

Android网络连接工具类

 不老松 2020-02-21
/** * 检查当前的网络 */ public static boolean checkNet(Context context) { // 判断当前用户手机是否使用WIFI通信 boolean isWIFI = isWIFIConnection(context); // 判断当前用户手机是否使用APN通信 boolean isAPN = isAPNConnection(context); // 否——提示用户——界面跳转到网络设置 if (isAPN == false && isWIFI == false) { return false; } if (isAPN) { // 是接入点 // IP是10.0.0.172 端口是80 从手机的配置信息中读取 // 有一部分手机:010.000.000.172 setAPN(context); } return true; } /** * 从手机的配置信息中读取 */ private static void setAPN(Context context) { Uri PREFERRED_APN_URI = Uri.parse('content://telephony/carriers/preferapn'); ContentResolver contentResolver = context.getContentResolver(); Cursor query = contentResolver.query(PREFERRED_APN_URI, null, null, null, null);//获取到当前正在连接的APN信息 if(query!=null&&query.moveToNext()) { //设置ip和端口的信息 GlobalParams.IP=query.getString(query.getColumnIndex('proxy')); GlobalParams.PORT=query.getInt(query.getColumnIndex('port')); } } /** * 判断WIFI是否连接 * * @return */ private static boolean isWIFIConnection(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo != null) return networkInfo.isConnected(); return false; } /** * 判断APN是否连接 * * @return */ private static boolean isAPNConnection(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (networkInfo != null) return networkInfo.isConnected(); return false; } } </pre>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多