你可以編寫自己的BroadcastReceiver。您的接收器將接收連接的變化,並告知您需要的情況下對變化(例如自己CommunicationManager):
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(getClass().getName(), "A change in network connectivity has occurred. Notifying communication manager for further action.");
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(info != null) {
Log.v(getClass().getName(), "Reported connectivity status is " + info.getState() + ".");
}
CommunicationManager.updateConnectivityState(); // Notify connection manager
}
}
例如這裏您CommunicationManager例如,將被通知連接的變化:
protected static void updateConnectivityState()
{
boolean isConnected = false;
if (_connec != null && (_connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(_connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)){
isConnected = true;
Log.i(CommunicationManager.class.getName(), "Device is connected to the network. Online mode is available.");
}else if (_connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || _connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
isConnected = false;
Log.w(CommunicationManager.class.getName(), "Device is NOT connected to the network. Offline mode.");
}
_isConnected = isConnected;
}
請查看NetworkInfo類以獲取有關連接可用性的更多詳細信息。
不要忘了在你的清單中註冊許可權在未經許可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
我希望這有助於。問候
爲什麼這是低調?有任何想法嗎? – cbrulak 2012-08-09 03:06:16
可能因爲ServiceState不是NetworkState。 ServiceState是電話無線電的狀態,而NetworkState會爲您提供數據連接的狀態(可能是wifi,wimax ...即不是電話網絡) – 2012-12-17 16:39:27