Search code examples
androidandroid-activityrunnableandroid-handler

Take action for every two minutes of inactivity (no user interaction)


I am trying to write to a file whenever the user has not interacted with the application for 2 minutes. Currently am having base activity in which I have overriden the onUserInteraction method. In this method the float time variable is reset and onResume I subtract the time with the current time to check if two minutes have passed. This works fine but sometimes acts crazy. Second approach was using the postDelayed method of the Handler and start a thread. This works perfectly but does not include the case when the app goes to background or the device goes to sleep.Is there a way to cover all these cases. ahve researched a lot. Also came across Wakeful Intent service but read that it is expensive.


Solution

  • Is there a way to cover all these cases.

    Yes. ... and it is expensive. Waking the phone up, every 2 minutes is going to drain the battery like crazy.

    That said, the answer to your question is that you need to use the AlarmManager, probably in concert with either the WakefulIntentService or the WakefulBroadcastReceiver. Create a PendingIntent and schedule it for delivery every 2 minutes.