如何根据背景通过连接状态更改Firebase数据



我尝试更改数据库onDisconnect方法。当连接可从后台使用时,我想更改数据库。例如,假设我目前处于主要目的的状态,状态是在线的,并且在Ondestroy中,它变得离线。对于我而言,不足以设置在线/离线状态。为此我想要

  1. 如果我有连接性(背景和前景(我的状态 在线
  2. 如果我在后台失去了连接,我的状态是离线的。每当可用连接性并且应用程序处于杀戮模式时,我的状态就在线。对于此解决方案,Stackoverflow建议我使用BroadcastreCeiver,但我不知道如何使用此类

我们可以同时使用服务和广播接收器轻松地完成它,以根据您的意愿获取输出。这将始终工作,即应用程序运行时,应用程序被最小化或从最小化的应用中删除应用程序时。

1. manifest代码:

    <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.您的活动代码

startService(new Intent(getBaseContext(), MyService.class));

使用此代码,您将能够在应用程序打开,暂停时,甚至应用程序被销毁

时可以检查连接性。

您可以使用此方法。它对我来说很好。

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

最新更新