Android检查用户是否有网络工具类

时间:2023-02-17 08:06:05

Android检查用户是否有网络工具类

public class NetUtil
{

/**
* 检查用户的网络:是否有网络
*/

public static boolean checkNet(Context context)
{
//判断: WIFI连接
boolean isWIFI=isWIFIConnection(context);
//判断: Mobile连接
boolean isMOBILE=isMOBILEConnection(context);

//如果是Mobile连接,判断到底是哪个VPN被选中了
if(isMOBILE)
{
//APN被选中,代理信息是否有内容,如果有wap方式
readAPN(context);//判断到底是哪个VPN被选中了
}
if(!isWIFI && !isMOBILE)
{
return false;
}


return true;
}
/**
* APN被选中,代理信息是否有内容,如果有wap方式
* @param context
*/

private static void readAPN(Context context)
{
Uri uri = Uri.parse("content://telephony/carriers/preferapn");//4.0模擬器屏蔽掉該權限

//操作联系人类似
ContentResolver contentResolver = context.getContentResolver();
//判断是哪个APN被选中了
Cursor cursor = contentResolver.query(uri, null, null, null, null);

if(cursor != null && cursor.moveToNext())
{
GlobalParams.PROXY = cursor.getString(cursor.getColumnIndex("proxy"));
GlobalParams.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;
}

}