How can i have screen idle listener?
Asked Answered
M

1

6

I need to use idle listener to listen the user is using the application or idle when the activity is alive. I need to do something when the user is not using the application more than ten seconds. How can i make it possible?

Merited answered 2/12, 2011 at 7:2 Comment(0)
A
7

Here is the idea how you can achieve this task:

Firstly you need a Runnable(), which will be Run when your timeout(e.g. 10 sec) occurs. Below is the Runnable():

private Runnable DoOnTimeOut = new Runnable() 
{
    public void run() 
    {
        // Do something Here
    }
}

Now, in your activity, you can call postDelayed for the DoOnTimeOut:

Handler hl_timeout = new Handler();

@Override
public void onCreate(Bundle b)
{
   hl_timeout.postDelayed(DoOnTimeOut, 10000); // The DoOnTimOut will be triggered after 10sec
}

Now, most important part is that when you see user interaction, you want to cancel the call to DoOnTimeOut and then again set the call for next 10 sec. Here is the Override method of your Activity for User Interaction:

@Override
public void onUserInteraction()
{
    super.onUserInteraction();
    //Remove any previous callback
    hl_timeout.removeCallbacks(DoOnTimeOut);
    hl_timeout.postDelayed(DoOnTimeOut, 10000);
}

I hope it will be helpful for you.

Autoerotism answered 2/12, 2011 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.