Skip to content Skip to sidebar Skip to footer

How To Change Firebase Databse By Connectivity Status From Background?

I tried to change database onDisconnect method. I want to change the database when connectivity available from background. For example, Suppose currently i am in MainActivity and s

Solution 1:

We can easily do it by using a Service and a Broadcast Receiver simultaneously to get the output as you wish. This will work always i.e when app is running, app is minimized or when app is even removed from minimized apps.

1.Manifest Code :

<application...
<serviceandroid:name=".MyService" /></application>

2.MyService.java

import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import android.widget.Toast;

    publicclassMyServiceextendsService {

    staticfinalStringCONNECTIVITY_CHANGE_ACTION="android.net.conn.CONNECTIVITY_CHANGE";
    NotificationManager manager ;

    @Nullable@Overridepublic IBinder onBind(Intent intent) {
        returnnull;
    }

    @OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        IntentFilterfilter=newIntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        BroadcastReceiverreceiver=newBroadcastReceiver() {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        Stringaction= intent.getAction();
        if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
            //check internet connectionif (!ConnectionHelper.isConnectedOrConnecting(context)) {
                if (context != null) {
                    booleanshow=false;
                    if (ConnectionHelper.lastNoConnectionTs == -1) {//first time
                        show = true;
                        ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                    } else {
                        if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
                            show = true;
                            ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                        }
                    }

                    if (show && ConnectionHelper.isOnline) {
                        ConnectionHelper.isOnline = false;
                        Log.i("NETWORK123","Connection lost");
                        //manager.cancelAll();
                    }
                }
            } else {
                Log.i("NETWORK123","Connected");
                showNotifications("APP" , "It is working");
                // Perform your actions here
                ConnectionHelper.isOnline = true;
            }
        }
    }
};
registerReceiver(receiver,filter);
return START_STICKY;
    }

    @OverridepublicvoidonDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
   }

3.ConnectionHelper.java

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

 publicclassConnectionHelper {

 publicstaticlonglastNoConnectionTs= -1;
 publicstaticbooleanisOnline=true;

 publicstaticbooleanisConnected(Context context) {
 ConnectivityManagercm=(ConnectivityManager)                      context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoactiveNetwork= cm.getActiveNetworkInfo();

return activeNetwork != null && activeNetwork.isConnected();
}

publicstaticbooleanisConnectedOrConnecting(Context context) {
ConnectivityManagercm=(ConnectivityManager)             context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoactiveNetwork= cm.getActiveNetworkInfo();

return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}

}

4.Your Activity Code

startService(newIntent(getBaseContext(), MyService.class));

With this code, you will be able to check the connectivity when the app is onStart, On pause and even when the app is destroyed

Solution 2:

You can use this method. It works fine for me.

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(newValueEventListener() {
  @OverridepublicvoidonDataChange(@NonNull DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
      Log.d("FirasChebbah", "connected");
    } else {
      Log.d("FirasChebbah", "not connected");
    }
  }

  @OverridepublicvoidonCancelled(@NonNull DatabaseError error) {
    Log.w("FirasChebbah", "Listener was cancelled");
  }
});

Post a Comment for "How To Change Firebase Databse By Connectivity Status From Background?"