简体   繁体   English

继续检查设备是否可以连接互联网

[英]Keep checking if Device has internet connection

As title states I wanted to ask, how can I keep checking if the device has internet connection? 作为标题,我想问一下,如何继续检查设备是否可以连接互联网? I use the following class: 我使用以下类:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class checkConnection {

    private static checkConnection instance = new checkConnection();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static checkConnection getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();

        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

But this only checks once the activity starts if the device has or not internet connection, if I wanted to keep checking how can I create a loop throughout the activity? 但这只会在活动开始后检查设备是否已连接互联网,是否一直保持检查状态,以便在整个活动期间如何创建循环?

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

 if(checkInternet(context))
 {
   Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
 }

}


boolean checkInternet(Context context) {
        ServiceManager serviceManager = new ServiceManager(context);
        if (serviceManager.isNetworkAvailable()) {
            return true;
        } else {
            return false;
        }
    }

}

ServiceManager.java ServiceManager.java

public class ServiceManager extends ContextWrapper {

public ServiceManager(Context base) {
    super(base);
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

}

permissions : 权限:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.INTERNET" />

And don't forget to register the receiver like this in main activity - 并且不要忘记在主要活动中像这样注册接收者-

registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
   }
}

ref. REF。 here 这里

You have to use Brodcast Receiver to register a listner whenever connectivity change and then check internet connection like this. 每当连接更改时,您必须使用Brodcast Receiver注册一个列表器,然后像这样检查Internet连接。


  
 
  
  
  
    public class NetworkConnectivityListener {
    	private static final String TAG = "NetworkConnectivityListener";
    	private static final boolean DBG = true;

    	private Context mContext;
    	private State mState;
    	private boolean mListening;
    	private String mReason;
    	private boolean mIsFailover;
    	boolean isWifiConnected = false;
    	boolean isMobileConnected = false;
    	private static NetworkConnectivityListener Networkobject;
    	private MainThreadBus mThreadBus;
    	public static NetworkConnectivityListener newInstance() {
    		if (Networkobject == null) {
    			Networkobject = new NetworkConnectivityListener();
    		}
    		return Networkobject;
    	}

    	/** 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;

    	private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
    		@SuppressWarnings("deprecation")
    		@Override
    		public void onReceive(Context context, Intent intent) {
    			String action = intent.getAction();

    			if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
    					|| mListening == false) {
    				Log.d(TAG, "onReceived() called with " + mState.toString()
    						+ " and " + intent);
    				return;
    			}

    			ConnectivityManager connMgr = (ConnectivityManager) context
    					.getSystemService(Context.CONNECTIVITY_SERVICE);

    			NetworkInfo networkInfo = connMgr
    					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    			if (networkInfo != null)
    				isWifiConnected = networkInfo.isConnected();

    			networkInfo = connMgr
    					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    			if (networkInfo != null)
    				isMobileConnected = networkInfo.isConnected();

    			Log.d("network status", "wifi == " + isWifiConnected
    					+ " and mobile == " + isMobileConnected);

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

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

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

    			mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
    			mIsFailover = intent.getBooleanExtra(
    					ConnectivityManager.EXTRA_IS_FAILOVER, false);
    			System.out.println("Printing the MYTest" + mNetworkInfo);
    			if (DBG) {
    				Log.d(TAG,
    						"onReceive(): mNetworkInfo="
    								+ mNetworkInfo
    								+ " mOtherNetworkInfo = "
    								+ (mOtherNetworkInfo == null ? "[none]"
    										: mOtherNetworkInfo + " noConn="
    												+ noConnectivity) + " mState="
    								+ mState.toString());
    			}

    			mThreadBus.post(getState());
    		}
    	};

    	public enum State {
    		UNKNOWN,

    		/** This state is returned if there is connectivity to any network **/
    		CONNECTED,
    		/**
    		 * This state is returned if there is no connectivity to any network.
    		 * This is set to true under two circumstances:
    		 * <ul>
    		 * <li>When connectivity is lost to one network, and there is no other
    		 * available network to attempt to switch to.</li>
    		 * <li>When connectivity is lost to one network, and the attempt to
    		 * switch to another network fails.</li>
    		 */
    		NOT_CONNECTED
    	}

    	/**
    	 * Create a new NetworkConnectivityListener.
    	 */
    	public NetworkConnectivityListener() {
    		mState = State.UNKNOWN;
    		mReceiver = new ConnectivityBroadcastReceiver();
    	}

    	/**
    	 * This method starts listening for network connectivity state changes.
    	 * 
    	 * @param context
    	 */
    	public synchronized void startListening(Context context,Bus bus) {
    		if (!mListening) {
    			mContext = context;
    			mThreadBus=new MainThreadBus(bus);
    			IntentFilter filter = new IntentFilter();
    			filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    			context.registerReceiver(mReceiver, filter);
    			mListening = true;

    		}
    	}

    	/**
    	 * This method stops this class from listening for network changes.
    	 */
    	public synchronized void stopListening() {
    		if (mListening) {
    			mContext.unregisterReceiver(mReceiver);
    			mContext = null;
    			mNetworkInfo = null;
    			mOtherNetworkInfo = null;
    			mIsFailover = false;
    			mReason = null;
    			mThreadBus=null;
    			mListening = false;
    		}
    	}

    	public State getState() {
    		return mState;
    	}

    	/**
    	 * 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 mIsFailover;
    	}

    	/**
    	 * 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 mReason;
    	}

    	public boolean iswifiConnected() {
    		return isWifiConnected;
    	}

    	public boolean ismobileConnected() {
    		return isMobileConnected;
    	}

    	public class MainThreadBus extends Bus {
    		private final Bus mBus;
    		private final Handler mHandler = new Handler(Looper.getMainLooper());

    		public MainThreadBus(final Bus bus) {
    			if (bus == null) {
    				throw new NullPointerException("bus must not be null");
    			}
    			mBus = bus;
    		}

    		@Override
    		public void post(final Object event) {
    			System.out.println("Printing the Value of Send" + event);
    			if (Looper.myLooper() == Looper.getMainLooper()) {
    				mBus.post(event);
    			} else {
    				mHandler.post(new Runnable() {
    					@Override
    					public void run() {
    						mBus.post(event);
    					}
    				});
    			}
    		}
    	}
    }

I have use otto here but you can use listener. 我在这里使用了otto,但是您可以使用侦听器。

Alternatively you can use TinyBus open source project, which makes you code as simple as this. 另外,您可以使用TinyBus开源项目,这使您的代码如此简单。

public class MyActivity extends Activity {

    private Bus mBus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBus = TinyBus.from(this).wire(new ConnectivityEvents());
        ...
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBus.register(this);
    }

    @Override
    protected void onStop() {
        mBus.unregister(this);
        super.onStop();
    }

    @Subscribe
    public void onConnectivityEvent(ConnectionChangedEvent event) {
        if (event.isConnected()) {
            // connected

        } else {
            // disconnected

        }
    }

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM