问题
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.
回答1:
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.
回答2:
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.
回答3:
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();
}
来源:https://stackoverflow.com/questions/8816732/detect-if-user-interacts-with-phone