广播接收检测是否连接网络

已不推荐。
推荐:使用Service和BroadcastReceiver实时监听网络状态


public class ConnectivityReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
    {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        MainMap.setWifiState(wm.getWifiState());
        Log.e("Debug", "Setting wifistate: " + wm.getWifiState());
    } else if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
    {
        NetworkInfo ni = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        MainMap.setConnected(ni.isConnected());
        Log.e("Debug", "Setting isConnected: " + ni.isConnected());
        if(ni.isConnected()) Toast.makeText(context, "Connected!", Toast.LENGTH_LONG).show();
    }
}

你可能感兴趣的:(连接)