Tips for creating an Android service that checks a web service for a bad connection

I am developing an Android application that should periodically test a specific web page. I got this to such an extent that it really polls the page at a certain interval, and this interval is specified in the SharedPreference, which can be changed by the user on the application settings page. But complications arise when the network connection is flaky.

For example, how can I guarantee that the service "wakes up" to the network adapter and gives it enough time to connect before polling the page, in case the phone was asleep in order to save electricity? This polling action can occur only every 24 hours, so I don’t want to skip one action only because the network is disconnected (but it turns on after a few seconds, minutes or even hours).

Or there are times when the web service is not responding, or the DNS is not responding, or what you have, and for some reason it does not receive a response, even if the phone is technically connected. What rule do I create to retry this attempt later, so that I don’t repeat it again when the user specifically disconnected their Internet, but I will rather soon repeat that if it was just a hiccup, the data can be received shortly after the first attempt?

Are there any examples for this type of situation? What is the logic to better deal with this?

+4
source share
2 answers

Listen to CONNECTIVITY_ACTION

This looks like a good example code . Here is a snippet:

IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(mReceiver, filter); 

See another question about How can we get a notification if the phone has Internet access?

+4
source

Refer to the BuzzBox SDK to handle a periodic task.

http://hub.buzzbox.com/android-sdk/

If you declare your task as a network task, the library will repeat the errors as soon as the phone is connected again. It uses the BroadcastReceiver, which you need to declare in your manifest:

  <receiver android:name=".NetworkChangeReceiver" android:label="NetworkChangeReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> 
+1
source

Source: https://habr.com/ru/post/1315972/


All Articles