簡體   English   中英

如何通過連接狀態從后台更改Firebase數據庫?

[英]How to change firebase databse by connectivity status from background?

我試圖更改數據庫的onDisconnect方法。 我想在后台連接可用時更改數據庫。 例如,假設當前我處於MainActivity,狀態為Online,狀態為onPause和onDestroy,則它變為脫機。 對我而言,僅設置在線/離線狀態是不夠的。 為此我想要

  1. 如果我有連接(背景和前景),我的狀態為在線
  2. 如果我在后台失去連接,則我的狀態為離線。 而且只要有可用的連接並且應用程序處於終止模式,我的狀態就在線。 對於此解決方案,stackoverflow建議我使用BroadCastReceiver,但我不知道如何使用此類

我們可以通過同時使用服務和廣播接收器來輕松獲得所需的輸出,從而輕松地做到這一點。 這將始終有效,即當應用程序正在運行,應用程序最小化或什至從最小化應用程序中刪除應用程序時。

1.清單代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM