Android判断网络连接状态代码

来源:互联网 发布:java web网站mvc模板 编辑:程序博客网 时间:2024/05/29 12:30
        很多时候对于手机或者平板电脑这样的手持设备,我们是不知道它们的网络连接状态的,在联网的时候我们必须得保证设备的网路是否正常,是否可以连接上互联网,或者我们在进行大量数据上传或者下载,例如下载网路视频,看网路电视等等,我们必须得为用户省钱,这样大数据的传输显然是不能使用用户昂贵的数据流量的,而是判断当前网络是不是在wifi下,使用WiFi来进行大数据的传输,会给用户更好的体验,那么下面这个工具类就是用来判断设备网络连接状态的,不仅判断了当前设置手机网络下还是WiFi环境下,而且如果手机网络下还需要设置运营商的代理IP和端口。
</pre><pre name="code" class="java">/** * 判断网络状态的工具类 *  */public class NetworkUtil {     /* 代码IP */    private static String PROXY_IP = null;    /* 代理端口 */    private static int PROXY_PORT = 0;    /**     * 判断当前是否有网络连接     *      * @param context     * @return     */    public static boolean isNetwork(Context context) {        boolean network = isWifi(context);        boolean mobilework = isMobile(context);        if (!network && !mobilework) { // 无网络连接            Log.i(NetworkUtil, 无网路链接!);            return false;        } else if (network == true && mobilework == false) { // wifi连接            Log.i(NetworkUtil, wifi连接!);        } else { // 网络连接            Log.i(NetworkUtil, 手机网路连接,读取代理信息!);            readProxy(context); // 读取代理信息            return true;        }        return true;    }     /**     * 读取网络代理     *      * @param context     */    private static void readProxy(Context context) {        Uri uri = Uri.parse(content://telephony/carriers/preferapn);        ContentResolver resolver = context.getContentResolver();        Cursor cursor = resolver.query(uri, null, null, null, null);        if (cursor != null && cursor.moveToFirst()) {            PROXY_IP = cursor.getString(cursor.getColumnIndex(proxy));            PROXY_PORT = cursor.getInt(cursor.getColumnIndex(port));        }        cursor.close();    }     /**     * 判断当前网络是否是wifi局域网     *      * @param context     * @return     */    public static boolean isWifi(Context context) {        ConnectivityManager manager = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo info = manager                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);        if (info != null) {            return info.isConnected(); // 返回网络连接状态        }        return false;    }     /**     * 判断当前网络是否是手机网络     *      * @param context     * @return     */    public static boolean isMobile(Context context) {        ConnectivityManager manager = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo info = manager                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);        if (info != null) {            return info.isConnected(); // 返回网络连接状态        }        return false;    }}

0 0
原创粉丝点击