如何检查用户是否在android studio中在线

问题描述 投票:0回答:1

我使用了以下代码

public class AppControllerClass extends Application implements LifecycleObserver {


private FirebaseAuth mAuth;
private DatabaseReference stateRef;

@Override
public void onCreate() {
    super.onCreate();

    try {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }catch (Exception e){
        e.printStackTrace();
    }

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

    mAuth = FirebaseAuth.getInstance();
    stateRef= FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("user_state");

}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {

    stateRef.child("state").setValue("online");

    Log.i("AppActivity","foreground");
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {

    stateRef.child("state").setValue("offline");

    Log.i("AppActivity","background");
}
}

我已更新代码,

    onMoveToBackground()

到达背景时被称为,我可以看到日志AppActivity背景但是一旦我返回到应用程序,状态就会更新为离线,然后

    onMoveToForeground()

被调用,状态迅速更新为在线。

我不知道怎么了为什么不在后台更新状态请某人,尝试给我有效的解决方案。

android background lifecycle
1个回答
0
投票

尝试使用此代码使用LifecycleObserver检查应用程序状态

gradle

  implementation "android.arch.lifecycle:common-java8:1.1.1"
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'

AppControllerClass

公共类AppController扩展应用程序实现LifecycleObserver {

@Override
public void onCreate() {
    super.onCreate();
 try {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }catch (Exception e){
        e.printStackTrace();
    }
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {
    // app moved to foreground
    Log.i("Check_App_Status","onMoveToForeground");
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {
    // app moved to background
    Log.i("Check_App_Status","onMoveToBackground");

 }
}

清单

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".AppController"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

添加清单

android:name=".AppController" 

并确保您的minSdkVersion = 24

© www.soinside.com 2019 - 2024. All rights reserved.