Android检查用户是否有网络工具类
public class NetUtil
{
/**
* 检查用户的网络:是否有网络
*/
public static boolean checkNet(Context context)
{
boolean isWIFI=isWIFIConnection(context);
boolean isMOBILE=isMOBILEConnection(context);
if(isMOBILE)
{
readAPN(context);
}
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");
ContentResolver contentResolver = context.getContentResolver();
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;
}
}