NetworkConnectivityManager

import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;


public class NetworkConnectivityManager {
	private static NetworkConnectivityManager MANAGER = null;

	private Context context;
	private SortedMap<Integer, Handler> mHandlers = new TreeMap<Integer, Handler>();
	private State state;
    private boolean isListening;
    private String reason;
    private boolean isFailover;
    
    /** Network connectivity information */
    private NetworkInfo mNetworkInfo;
    /**
     * In case of a Disconnect, the connectivity manager may have
     * already established, or may be attempting to establish, connectivity
     * with another network. If so, {@code mOtherNetworkInfo} will be non-null.
     */
    private NetworkInfo mOtherNetworkInfo;
    private ConnectivityBroadcastReceiver mReceiver;

    public enum State {
        UNKNOWN, 
        CONNECTED,		// This state is returned if there is connectivity to any network
        NOT_CONNECTED	/*
				         * This state is returned if there is no connectivity to any network. This is set
				         * to true under two circumstances:
				         * 
				         * When connectivity is lost to one network, and there is no other available
				         * network to attempt to switch to.
				         * When connectivity is lost to one network, and the attempt to switch to
				         * another network fails.
				         */
    }
    
    public enum Signal {
    	MOBILE,
    	WIFI,
    	UNKNOWN;
    }
    
    
    /**
     * Create a new NetworkConnectivityListener.
     */
    public NetworkConnectivityManager() {
        state = State.UNKNOWN;
        mReceiver = new ConnectivityBroadcastReceiver();        
    }

    
    public static NetworkConnectivityManager getInstance(){
    	if(MANAGER == null){
    		MANAGER = new NetworkConnectivityManager();
    	}
    	return MANAGER;
    }
    
    
    /**
     * This method starts listening for network connectivity state changes.
     * @param context
     */
    public synchronized void startListening(Context context) {
        if (!isListening) {
            this.context = context;

            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);            
            context.registerReceiver(mReceiver, filter);
            isListening = true;
        }
    }

    /**
     * This method stops this class from listening for network changes.
     */
    public synchronized void stopListening() {
        if (isListening) {
            context.unregisterReceiver(mReceiver);
            context = null;
            mNetworkInfo = null;
            mOtherNetworkInfo = null;
            isFailover = false;
            reason = null;
            isListening = false;
        }
    }

    /**
     * This methods registers a Handler to be called back onto with the specified what code when
     * the network connectivity state changes.
     *
     * @param what The what code to be used when posting a message to the handler and sorting.
     * @param target The target handler.
     */
    public void registerHandler(int what, Handler target) {
        mHandlers.put(what, target);
    }
    
    /**
     * This methods unregisters the specified Handler.
     * @param The what code to be used when posting a message to the handler and sorting.
     */
    public void unregisterHandler(int what) {
        mHandlers.remove(what);
    }
    
    public State getState() {    	
    	// FIXME Quick fix for checking correct state when launch applicaiton.
    	ConnectivityManager manager =  (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    	if (networkInfo != null && networkInfo.isConnected()) {
    	    state = State.CONNECTED;
    	} else {
    		state = State.NOT_CONNECTED;
    	} 
        return state;
    }

    /**
     * Return the NetworkInfo associated with the most recent connectivity event.
     * @return {@code NetworkInfo} for the network that had the most recent connectivity event.
     */
    public NetworkInfo getNetworkInfo() {
        return mNetworkInfo;
    }

    /**
     * If the most recent connectivity event was a DISCONNECT, return
     * any information supplied in the broadcast about an alternate
     * network that might be available. If this returns a non-null
     * value, then another broadcast should follow shortly indicating
     * whether connection to the other network succeeded.
     *
     * @return NetworkInfo
     */
    public NetworkInfo getOtherNetworkInfo() {
        return mOtherNetworkInfo;
    }

    /**
     * Returns true if the most recent event was for an attempt to switch over to
     * a new network following loss of connectivity on another network.
     * @return {@code true} if this was a failover attempt, {@code false} otherwise.
     */
    public boolean isFailover() {
        return isFailover;
    }

    /**
     * An optional reason for the connectivity state change may have been supplied.
     * This returns it.
     * @return the reason for the state change, if available, or {@code null}
     * otherwise.
     */
    public String getReason() {
        return reason;
    }
    
    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
        	//System.err.println(this.getClass().getSimpleName() + ".onReceive()");
        	
            String action = intent.getAction();

            if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || isListening == false) {
                return;
            }

            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

            if (noConnectivity) {
                state = State.NOT_CONNECTED;
            } else {
                state = State.CONNECTED;
            }


            mNetworkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            mOtherNetworkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            // Notifiy any handlers.
            Iterator<Integer> it = mHandlers.keySet().iterator();
            while (it.hasNext()) {
                Integer key = it.next();
                Handler handler = mHandlers.get(key);
                LogUtil.e("key", key.toString());
                Message message = Message.obtain(mHandlers.get(key), key);
                message.obj = state;
                handler.sendMessage(message);
            }
        }
    };
    
    
	public Signal getConnectionSignal(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		
		// For 3G check
		NetworkInfo mobileNetworkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean is3g = false; 
		if(mobileNetworkInfo != null){
			is3g = mobileNetworkInfo.isConnectedOrConnecting();
		}
		
		// For WiFi Check		
		NetworkInfo wifiNetworkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		boolean isWifi = false;
		if(wifiNetworkInfo != null){
			isWifi = wifiNetworkInfo.isConnectedOrConnecting();
		}

		if (is3g) {
			LogUtil.d(this.getClass().getName(), "Mobile");
			return Signal.MOBILE;
		} else if (isWifi) {
			LogUtil.d(this.getClass().getName(), "WIFI");
			return Signal.WIFI;
		} else {
			LogUtil.d(this.getClass().getName(), "UNKNOWN");
			return Signal.UNKNOWN;
		}
	}    


}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值