安卓:我能察觉已经离开该应用程序的用户?我能、应用程序、用户

2023-09-12 23:57:51 作者:心在旅途

我开发一个Android应用程序,并要检测,当用户退出通过单击后退按钮或home键的应用程序,无论是。

I am developing an android app and want to detect when the user exit the app either by clicking back button or home button.

也或者,如果有喜欢的OnInit事件也是我的方案是有用的, 我只是想送花儿给人MyInıt行动开始于第一次。

Or also if there is an event like onInit is also useful for my scenario, as I just want to alway MyInıt action starts at first.

的onDestroy不叫,直到其他应用程序需要更多的内存。

onDestroy is not called till other apps need more memory.

感谢。

推荐答案

如果你的活动是最后一个在堆栈中,然后检测一回按钮的onkeydown会解决这个1/2

If your activity is the last in the stack then detecting a back button with onKeyDown would solve 1/2 of this

的home键是有点麻烦,没有绝对的方法,但你可以做这样的事情这适合我的简单的需求。

The home key is a little trickier, there is no absolute method but you could do something like this which works for my simple needs.

该onUserLeaveHint是根据当用户点击主页按钮或当事情打断你的应用程序(如呼入电话),所以猜测哪些是你使用onUserInteraction方法,杜绝最后一个用户交互时间的文档调用。

The onUserLeaveHint is called according to the documentation when the user clicks the home button OR when something interrupts your application (like an incoming phone call) so to guess which it is you use the onUserInteraction method to stamp the last user interaction time.

现在如果precedes的onUserLeaveHint不够紧密,你可以假设(不能保证,但至今工作对我来说)的home键是你的应用被推到背景的原因(退出)

Now if that precedes the onUserLeaveHint closely enough you can assume (not guaranteed but has worked for me so far) that the home button was the reason your application is being pushed into the background (exiting)

不知道你的意图是在追赶home键什么的,反正这里是一个简单的方法来做到这一点,我用身边,我已经找到一直为我工作的两个事件100ms的围栏。注:我只测试了一把手机,像Android的所有的事情你里程将有所不同依赖于OS /硬件(赫克甚至多数民众赞成记录,并认为有时候上班的东东没有)

Not sure what your intent is in catching the home button, anyway here is a simplistic way to do that, I use a 100ms fence around the two events which I have found has always worked for me. NOTE: I have only tested on a handful of phones, like all things in Android your mileage will vary dependent on OS / Hardware (heck even the stuff that's documented and supposed to work sometimes doesn't)

long userInteractionTime = 0;

@Override
public void onUserInteraction() {
    userInteractionTime = System.currentTimeMillis();
    super.onUserInteraction();
    Log.i("appname","Interaction");
}

@Override
public void onUserLeaveHint() {
    long uiDelta = (System.currentTimeMillis() - userInteractionTime);

    super.onUserLeaveHint();
    Log.i("bThere","Last User Interaction = "+uiLag);
    if (uiDelta < 100)
        Log.i("appname","Home Key Pressed");    
    else
        Log.i("appname","We are leaving, but will probably be back shortly!");  
}