Home » Android » android – Detect if user interacts with phone?

android – Detect if user interacts with phone?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I need to detect when user interacts with the phone and restart my app after 60 seconds from last user’s touch on screen. Is is possible to do something like that?
It must work as the screenserver for PC.

How to&Answers:

Is is possible to do something like that?

Only if your activity is in the foreground, in which case you can keep track of touch events. You cannot find out about touch events happening elsewhere in the system.

Answer:

ACTION_USER_PRESENT is a broadcast action, so you should be able to write a broadcast receiver to respond to it and launch your application. Keep in mind that ACTION_USER_PRESENT is

sent when the user is present after device wakes up (e.g when the
keyguard is gone).

I also just came across an example where the BOOT_COMPLETED broadcast action is used by a broadcast receiver to start an application on boot.

Answer:

According to android lifecycle if user press home button or keypad locked onPause will get called.So do something like this.

@Override
public void onPause()
{
super.onPause();
Timer timer = new Timer();
TimerTask task = new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        finish();
    }
};
timer.schedule(task, 60000);
}

and if user comes before 60 seconds then in onRestart().

@Override
public void onRestart()
{
super.onRestart();
timer.cancel();
timer.purge();
}