问题
I would like to notify (create a notification) user whenever he receives an in-app request.
I'm using a MySQL Database with PHP - regular stuff.
Whenever the value of the user_id_req field changes from 0 to 1, the app should create a notification. I was able to do it on App Start with NotificationManager
and checking the DB but I would like to do it in real-time, meaning as soon as the value changes.
Should I use GCM to handle those requests or a Service that runs in the background and checks the Database every minute?
回答1:
You should absolutely use GCM for this, rather than a polling model.
It is very bad practice to make a network request every minute - this will lead to significant battery usage. Moreover, unless you have your Service hold a wake-lock (which will really kill the battery), the device will go to sleep eventually and your requests will stop until the user wakes up the device again. Another issue is that unless you register your app to wake up and trigger the service on boot, your polling will stop whenever the user restarts their device.
It just so happens that most GCM tutorials will also have you create a Service
. Don't let that confuse you. If you're only showing a notification to the user, you don't need the Service
and just a simple BroadcastReceiver
will work fine.
来源:https://stackoverflow.com/questions/27238870/android-notification-gcm-or-service