Android系统服务:ConnectionManager

裴凯定
2023-12-01

ConnectionManager基本介绍和使用

ConnectionManager是负责网路管理的类。
获取ConnectivityManager

ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

获取可用的NetworkInfo()

NetworkInfo info = manager.getActiveNetworkInfo();

获取wifi和移动网络的信息

NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

判断网路是否连接

wifiInfo.isConnected();

利用广播监听网络变化

ConnectChangeReceiver

public class ConnectChangeReceiver extends BroadcastReceiver {

    private static final String TAG = "ConnectChangeReceiver";

    /**
     * 获取ConnectivityManager
     * 获取ConnectionInfo
     * 判断网络是否可用
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (wifiInfo.isConnected() || mobileInfo.isConnected()) {
                Log.d(TAG, "联网正常");
            } else {
                Log.d(TAG, "联网失败");
            }
        }
    }
}

在合适的地方注册广播和取消广播

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
ConnectChangeReceiver receiver = new ConnectChangeReceiver();

registerReceiver(receiver, filter);
unregisterReceiver(receiver);

其它

Demo:http://git.oschina.net/httpmethod/networkmanager01

 类似资料: