Android Mobile App – How to Execute a Get Request Periodically While Inactive

androidappmobile

I have a website that has full support for mobile devices but since opening a browser window seems too much and some people are obsessed with installing apps, I'm now creating an android app which is essentially just a browser inside of an activity.

I thought, I'm creating it anyway, so I might just go one step further and enable the app to notify the user when there are new events that may concern them such as new notifications in the site itself.

I've never developed an android application nor have I ever worked with java, I'm basically just googling and copy/pasting with little tweaks (I know my ways around programming, just not java), which made me think twice about how I should do this.

Basically my idea is when the activity is closed (onStop) I will start a service that then is going to send an HTTP GET request to my API site.com/notifications/countUnseen which simply returns an integer, and if there are any I'll create a new android notification for the user. When the activity is resumed (onStart) I will terminate the service. I am concerned mainly about the fact that I have to send an HTTP request every, say, 5 minutes and I'm not really sure how to do that. What I found is that I could use ScheduledThreadPoolExecutor suggested in this answer from within the service.

Do you think that what I have planned is a good idea at all? I just need a word of comfort about this, or better yet another suggestion if what I have is garbage, from someone more experienced than me.

Best Answer

There is no need to leave as service running to perform regular polling, and doing so may annoy your users, as it will consume memory for no good reason.

You should look at the AlarmManager API. This has three potential advantages:

  • it can be configured to send an Intent that will start your app in the background even if it is not running, meaning you don't need to waste memory
  • it can be configured to wait until the device is next awake after your selected time, which will save power
  • it is able to batch notifications with similar frequency together, meaning that if any of your users have another process that polls periodically the two will happen simultaneously, thus saving power.
Related Topic