Keep checking if Device has internet connection

被刻印的时光 ゝ 提交于 2019-12-08 10:10:42

问题


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?


回答1:


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

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. here




回答2:


You have to use Brodcast Receiver to register a listner whenever connectivity change and then check internet connection like this.

    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);
    					}
    				});
    			}
    		}
    	}
    }


来源:https://stackoverflow.com/questions/26730683/keep-checking-if-device-has-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!