Android 知识要点整理(13)----网络连接

网络连接是应用要具备的基本功能。下面就来讲讲网络连接的基本知识,包括如何连接网络,监控网络状态以及控制网络的使用。

连接到网络

在Android平台,首先要声明使用网络的权限。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

大多数网络连接都是基于HTTP协议。Android平台提供了HttpUrlConnection的网络客户端,该客户端支持HTTPS、上传下载、IPV6、超时策略和连接池等。
在连接网络之前,我们需要检查当前设备所处的网络状态。下面是一个network 工具类,用来检测网络的连通性:

package com.example.android.animationsdemo;

/**
 * Created by Stephan on 2016/6/4.
 */

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;       

/**
 * Created by StephanZeng on 2015/6/24.
 */
public class NetworkUtils {


    private static final String TAG = "NetworkUtils";

    /**
     * 判断当前网络连接是否可用
     * @param context 上下文
     * @return true 如果网络可用,否则返回false
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo info = cm.getActiveNetworkInfo();
            return  info != null && info.isConnected();
        }
        return false;
    }


    /**
     * 判断当前wifi是否可用
     * @param context 上下文
     * @return true 如果网络可用,否则返回false
     */
    public static boolean isWifiAvailable(Context context) {
        ConnectivityManager mgrConn = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = mgrConn.getActiveNetworkInfo();

        return activeNetworkInfo != null&&activeNetworkInfo.isConnected()
                && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 判断当前Mobile网络是否可用
     * @param context 上下文
     * @return true 如果网络可用,否则返回false
     */
    public static boolean isMobileAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        return  networkINfo != null && networkINfo.isConnected()
                && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 判断是否是WIFI网络
     * @param context 上下文
     * @return true 如果是wifi网络,否则返回false.
     */
    public static boolean isWifiType(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null
                && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * ping 某个网络,确保网络能够连接到Internet
     * @return 连通返回true,否则返回false
     */
    public static final boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容,可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d(TAG, "ping result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }
}

监测网络变化

网络可能发生变化,在网络变化我我们需要处理一些场景,所以我们需要知道网络什么时候发生了变化。当网络改变时,系统会发送一个action为CONNECTIVITY_ACTION的广播,我们通过实现NetworkReceiver广播监听器来监听网络的变化。

public class NetworkChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction() == ConnectivityManager.CONNECTIVITY_ACTION){
                //网络变化的广播

                //当前活动网络
                NetworkInfo info = ((ConnectivityManager)
                        context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

                //获取网络发生变化后的网络类型
                int networkType = intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,-1);
                //指示该事件是否是从一个网络连接切换到了另一个网络连接
                boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,false);

                //指示当前是否完全没有了网络连接
                boolean hasNoConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);

                //当前网络连接失败的原因,是一个字符串,可以呈现给用户看
                String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);

                //指示当前连接到INTERNET的强度
                //0 表示没有连接,100 表示连接良好
                //这个 EXTRA_INET_CONDITION 数以(@hide)级别,
                //所以没法引用,直接用字符串,不过不建议。
                int inetCondition = intent.getIntExtra("inetCondition",-1);

                //....
                //TODO:处理网络变化的事
            }
        }
    }

下面是网络发生变化时打印出的日志。我们发现有些参数的值并不是我们预期的那样,比如 inetCondition有时候会一直是0,所以在使用这些值做逻辑判断时需要谨慎。还有一点,当网络从3G切换到wifi时,应用会收到2条广播,一条指示3G网络(networkType=0)已经断开连接(hasNoConnection=true),另外一条指示WIFI网络(networkType=1)已经连接(hasNoConnection=false)。

06-05 13:15:32.186 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>1
isFailover=>false
hasNoConnection=>true
reason=>null
inetCondition=>0
06-05 13:15:33.613 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>0
isFailover=>false
hasNoConnection=>false
reason=>null
inetCondition=>0
06-05 13:16:43.446 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>0
isFailover=>false
hasNoConnection=>true
reason=>specificDisabled
inetCondition=>0
06-05 13:17:08.078 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>1
isFailover=>false
hasNoConnection=>false
reason=>null
inetCondition=>0
06-05 13:17:37.298 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>1
isFailover=>false
hasNoConnection=>true
reason=>null
inetCondition=>0
06-05 13:17:42.562 9496-9496/com.example.android.animationsdemo D/NetworkUtils: networkType=>1
isFailover=>false
hasNoConnection=>false
reason=>null
inetCondition=>0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值