Продолжайте проверять, подключено ли устройство к Интернету

Как говорится в заголовке, я хотел спросить, как я могу проверить, подключено ли устройство к Интернету? Я использую следующий класс:

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

Но это проверяется только после начала действия, если устройство подключено к Интернету или нет, если я хочу продолжать проверять, как я могу создать цикл на протяжении всего действия?


person LS_    schedule 04.11.2014    source источник


Ответы (3)


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

}

разрешения:

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

И не забудьте зарегистрировать приемник вот так в основной активности -

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

исх. здесь

person Darpan    schedule 04.11.2014

Вы должны использовать Broadcast Receiver для регистрации листнера при каждом изменении подключения, а затем проверять подключение к Интернету, как это.

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

Здесь я использую otto, но вы можете использовать listener.

person amit kumar    schedule 04.11.2014

В качестве альтернативы вы можете использовать проект с открытым исходным кодом 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

        }
    }

    ...
}
person sergej shafarenka    schedule 13.11.2014