-->

Android notification in realtime

2019-09-19 06:32发布

问题:

I have a website that sends and receives documents. I was thinking of building an Android app that notifies the user if a new document has been received, and displays document details if the notification is clicked. It doesn't have to be in real time, it could update in interval of five minutes or something.

What is the best way to update the Android app of changes in the website? I'm new to Android and I'm not quite sure where to start. I've heard of Services, BroadcastReceivers and Alarms, but I don't know if those are the right ideas.

Update: How do I update my Android db from my web db within an AsyncTask in my BroadcastReceiver? I'm worried I might have a "leak error" which sometimes comes up with my AsyncTask.

回答1:

You can try to implement GCM or as the above-mentioned, work with an AlarmManager or the more efficient JobScheduler (requires API level 21!). Avoid doing heavy work on a BroadcastReceiver. Instead use the Broadcastreceiver to receive Alarms and start a Service in background. You may also have a look to WakefulBroadcastReceiver which holds a WakeLock for you. The Service could GET data from your webservice by using a REST architecture and update it's local database. Retrofit is a powerful open source library for a REST architecture. If there are new database records, you can inform the user by a Notification. Don't forget to check basic things like not starting the Service if the device hasn't got a network connection or to stop the Service after the work has been finished. I personally recommend to learn the basics first and then go to advanced topics. Good luck and pleasure.