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;
}
}
}
NetworkConnectivityManager
最新推荐文章于 2023-05-11 19:07:19 发布