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
    ...
<service android: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;

    public class MyService extends Service {

    static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    NotificationManager manager ;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
            //check internet connection
            if (!ConnectionHelper.isConnectedOrConnecting(context)) {
                if (context != null) {
                    boolean show = 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;
    }

    @Override
    public void onDestroy() {
        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;

 public class ConnectionHelper {

 public static long lastNoConnectionTs = -1;
 public static boolean isOnline = true;

 public static boolean isConnected(Context context) {
 ConnectivityManager cm =(ConnectivityManager)                      context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

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

public static boolean isConnectedOrConnecting(Context context) {
ConnectivityManager cm =(ConnectivityManager)             context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

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

}

4.Your Activity Code

startService(new Intent(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(new ValueEventListener() {
  @Override
  public void onDataChange(@NonNull DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
      Log.d("FirasChebbah", "connected");
    } else {
      Log.d("FirasChebbah", "not connected");
    }
  }

  @Override
  public void onCancelled(@NonNull DatabaseError error) {
    Log.w("FirasChebbah", "Listener was cancelled");
  }
});

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