如何通过连接状态从后台更改Firebase数据库? [英] How to change firebase databse by connectivity status from background?

查看:33
本文介绍了如何通过连接状态从后台更改Firebase数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更改数据库的onDisconnect方法.我想在后台连接可用时更改数据库.例如,假设当前我处于MainActivity,状态为Online,状态为onPause和onDestroy,则它变为脱机.对我而言,仅设置在线/离线状态是不够的.为此我想要

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 status is Online and in onPause and onDestroy it becomes offline. For my side it is not enough to set online/offline status. For this i want

  1. 如果我具有连通性(背景和前景),则我的状态在线
  2. 如果我在后台断开了连接,则我的状态为离线.而且只要有可用的连接并且应用程序处于终止模式,我的状态就在线.对于此解决方案,stackoverflow建议我使用BroadCastReceiver,但我不知道如何使用此类

推荐答案

我们可以通过同时使用服务和广播接收器来轻松获得所需的输出,来轻松地做到这一点.这将始终有效,即在应用程序运行,最小化应用程序或什至从最小化应用程序中删除应用程序时.

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.清单代码:

    <application
    ...
<service android:name=".MyService" />
</application>

2.MyService.java

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

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

使用此代码,您可以在应用程序启动时,暂停时甚至在应用程序被销毁时检查连接性

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

这篇关于如何通过连接状态从后台更改Firebase数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆