Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package emobility.ae.e_mobilityuae.data.network;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.util.Log;
- import java.util.LinkedList;
- import java.util.List;
- import io.reactivex.Observable;
- import io.reactivex.ObservableEmitter;
- public class ConnectionManager extends BroadcastReceiver {
- private enum ConnectionStatus { NOT_CONNECTED, MOBILE, WIFE }
- private Boolean isInternetOn;
- private List<ObservableEmitter<Boolean>> emitters;
- public ConnectionManager(Context context) {
- emitters = new LinkedList<>();
- context.registerReceiver(this,
- new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
- }
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction() != null
- && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
- Log.d("test", "onReceive");
- Boolean oldConnection = currentInternetConnection();
- updateInternetConnection(context);
- if (currentInternetConnection() != oldConnection) {
- notifyAllEmitters(currentInternetConnection());
- }
- }
- }
- public Observable<Boolean> isInternetOn() {
- return Observable.create(emitter -> {
- emitters.add(emitter);
- Boolean currentInternetConnection = currentInternetConnection();
- if (currentInternetConnection != null) {
- emitter.onNext(currentInternetConnection);
- }
- });
- }
- private void notifyAllEmitters(Boolean value) {
- for (ObservableEmitter<Boolean> emitter : emitters) {
- if (!emitter.isDisposed()) {
- emitter.onNext(value);
- }
- }
- }
- private Boolean currentInternetConnection() {
- return isInternetOn;
- }
- private void updateInternetConnection(Context context) {
- isInternetOn = getConnectionStatus(context) != ConnectionStatus.NOT_CONNECTED;
- }
- private ConnectionStatus getConnectionStatus(Context context) {
- ConnectivityManager connectivityManager = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivityManager != null ) {
- NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
- if (networkInfo != null && networkInfo.isConnected()) {
- if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
- return ConnectionStatus.MOBILE;
- } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
- return ConnectionStatus.WIFE;
- } else {
- // for default is WIFI
- return ConnectionStatus.WIFE;
- }
- } else {
- return ConnectionStatus.NOT_CONNECTED;
- }
- } else {
- return ConnectionStatus.NOT_CONNECTED;
- }
- }
- }
Add Comment
Please, Sign In to add comment