I am having 10 different buttons in my application for different task to perform. I want to develop one service which continuously check (listens) and if user is not clicking any button for particular time let say for 5sec than i wish to perform some other task. How can I check that user has not clicked any button? If anyone having any idea please kindly let me know.
Click Listener in Android, How to check if no Button is clicked for particular time period?
3.5k views Asked by Scorpion At
3
There are 3 answers
1
On
On each button click, update some Calendar object to a new Calendar instance and then you can check what the time is of that Calendar and see if it's more than 5 minutes ago.
//this is a field
Calendar calendar;
public void onClick(View v) {
calendar = Calendar.getInstance();
//etc
switch(v.getId()) {
}
}
1
On
You could simply set a Timer to the desired length. When a button is clicked, just reset the timer. Start the timer in onResume so it starts even if the user is coming back from a phone call or other activity. You should probably stop the timer in onPause of the activity too.
In each of your click listeners save off the time the last button was clicked:
Now the smarter developer would create a reusable base class that handled setting the timestamp once, then reuse that base class in each of the 10 buttons. But, that's left up to you. Then the background job would look like:
If you have to use a service you can send a notification to the service saying a button was clicked, then the service can keep track of the time when that occurred. I wouldn't use a service for this because playing an animation or sound doesn't need to survive if the app is put into the background or killed. Services are meant for things like playing music when someone is doing something else, chat applications, or things that need to run in the background when the user isn't interacting with the application. What you're describing could be done as I've shown because when the user gets a phone call or text message they'll leave your application, and the animation or sound you're playing probably should stop too. Pretty easy to do with the Handler option I showed. More difficult, but doable, with a service.