如何检测用户是否离开了我的应用程序? [英] How do I detect if the user has left my app?

查看:126
本文介绍了如何检测用户是否离开了我的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,我想通过单击后退"按钮或主页"按钮来检测用户何时退出我的应用程序.

I am developing an Android app and I want to detect when the user exits my app either by clicking the Back button or the Home button.

另外,在我的场景中,像onInit()这样的事件将很有用,因为我只是想首先开始执行MyInıt动作.

Also, an event like onInit() would be useful in my scenario, as I just want to have the MyInıt action start at first.

onDestroy().

推荐答案

如果您的活动是堆栈中的最后一个活动,则使用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.

现在,如果该距离足够接近onUserLeaveHint,您可以假设(不能保证,但到目前为止对我有用)主页按钮是您的应用程序被推入后台(退出)的原因

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)

不确定要按下主页按钮的意图是什么,无论如何,这是一种简单的方法,我在发现的两个事件周围始终使用了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!");  
}

这篇关于如何检测用户是否离开了我的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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