Android_ConnectivityManager连接管理

ConnectivityManager

ConnectivityManager作为安卓网络连接管理类,主要功能如下:
1. 通知应用网络状态的改变,发送广播 ACTION:CONNECTIVITY_ACTION
2. WiFi,GPRS等网络的连接管理(是否可用,连接状态等)
3. 提供了一种api来让应用去请求或是选择网络来进行数据的传输

需要的权限:

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

NetWorkActivity

public class NetWorkActivity extends ActionBarActivity {

    private final static String TAG = "RAISE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_work);
        check_network();

        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(NetworkReceiver, filter);
    }

    private void check_network() {
        //获取网络管理类
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //得到当前可以使用的网络
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        //判断当前网络类型
        if (activeNetworkInfo != null) {
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                Log.d(TAG, "当前网络:" + activeNetworkInfo.getTypeName());
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                Log.d(TAG, "当前网络:" + activeNetworkInfo.getTypeName());
            }
            NetworkInfo.State state = activeNetworkInfo.getState();
            if (state.ordinal() ==NetworkInfo.State.CONNECTED.ordinal()) {
                Log.d(TAG, activeNetworkInfo.getTypeName() + "网络可用");
            }
        } else {
            Log.d(TAG, "无网络可用");
        }
    }

    BroadcastReceiver NetworkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                Log.d(TAG, "广播接受");
                check_network();
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(NetworkReceiver);
        super.onDestroy();
    }
}

经测试发现,这个广播会在注册之后有一次调用
这个广播只会在当前网络切换为另一种网络(必须可上网)或是无网络时,才会调用
上图:
Android_ConnectivityManager连接管理_第1张图片
当然也可以分别获得mobile和wifi的NetworkInfo来分别处理

        NetworkInfo mobile_networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifi_networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mobile_networkInfo.isConnected()){
            //...
        }

你可能感兴趣的:(Android)