Android 技巧 - 网络可用性侦测

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <receiver android:name=".NetworkConnectionChangeReceiver"
             android:enabled="true" 
             android:exported="false">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>




import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

public class NetworkConnectionChangeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Intent myIntent = new Intent(context, WAMPClient.class);
    
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    
    if (null != info) {
      State state = info.getState();
      if (State.CONNECTED == state) {
        // connected to network
        context.startService(myIntent);
      }
    }
    else {
      // network connection lost
      context.stopService(myIntent);
    }
  }
}

   

你可能感兴趣的:(android,网络,监听,可用性)