android用户网络检测工具

本文介绍了一个Java类NetUtil,用于检查设备的网络状态,包括Wi-Fi和移动数据连接,并提供了读取当前活动APN设置的方法以确定是否使用代理。
public class NetUtil{
	
	private static String PROXY = "";      // 移动运营商代理: 中国移动:10.0.0.172 其它的忘了
	private static int PORT = 0;           // 端口:80
	/**
	 * 检查用户网络
	 */
	public static boolean checkNet(Context context){
		// 判断WIFI连接
		boolean isWifi = isWifiConnection(context);
		// 判断Mobile连接
		boolean isMobile = isMobileConnection(context);
		// 如果Mobile连接,判断是哪个APN被选中了
		if(isMobile){
			// APN被选中,代理信息是否有内容,如果wap方式
			readAPN(context); // 判断是哪个APN被选中

			// TODO
		}
		
		if(!isWifi && !isMobile){
			return false;
		}
		
		return true;
	}

	/**
	 * 读取被选中的APN
	 * @param context
	 */
	private static void readAPN(Context context) {
		// 操作联系人
		ContentResolver resolver = context.getContentResolver();
		Uri uri = Uri.parse("content://telephony/carriers/preferapn");
		
		Cursor cursor = resolver.query(uri, null, null, null, null);
		if(cursor!=null && cursor.moveToNext()){
			PROXY = cursor.getString(cursor.getColumnIndex("proxy"));
			PORT = cursor.getInt(cursor.getColumnIndex("port"));
		}
	}

	/**
	 * 判断: Mobile连接
	 * @param context
	 * @return
	 */
	private static boolean isMobileConnection(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;
	}
	
	/**
	 * 判断: Wifi连接
	 * @param context
	 * @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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值