如何检查用户是否在线

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

我是android新手我正在开发需要更新用户在线状态的应用]

每当用户关闭时最小化应用程序

我尝试过onPause()方法,它在最小化的情况下效果很好,但是在使用意图更改活动时有效onPause()称为

所以没有用

我也尝试过LifeCycle观察器,但不知道在哪里应用,所以我通过实现lifeCYcle观察器将其应用到我的主要活动中。>

    public class MainActivity extends AppCompatActivity implements LifecycleObserver {

以及我使用的onCreate中

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

以及创建后我用过

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {   //shows method never used
    // app moved to foreground
    Status("online")
 }

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {  //shows method never used
    // app moved to background
    Status("offline")
}

     public void UserState(String state)
{

    String saveCurrentDate, saveCurrentTime;

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat currentDateFormat = new SimpleDateFormat("MMM dd,YYYY");
    saveCurrentDate = currentDateFormat.format(calendar.getTime());

    SimpleDateFormat currentTimeFormat = new SimpleDateFormat("hh:mm a");
    saveCurrentTime = currentTimeFormat.format(calendar.getTime());

    HashMap<String, Object> userOnlineStatus = new HashMap<>();
    userOnlineStatus.put("time", saveCurrentTime);
    userOnlineStatus.put("date", saveCurrentDate);
    userOnlineStatus.put("state", state);

    rootreference.child(currentUserId)
            .child("user_state")
            .updateChildren(userOnlineStatus);
}

它显示从未使用过的方法我尝试以工作正常的方法使用吐司但是当我尝试从中调用方法

仅在涉及前景时才调用当它进入后台时,不要调用方法

什么是最简单的方法请回复,将对您有帮助

<<

尝试使用此代码使用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

android background lifecycle
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.