Issue
So, I have a service that is supposed to send data to my server via MQTT. This process of sending of data is supposed to happen every 10 minutes and must be done regardless of the state of my application (Paused/Stopped/Destroyed). So, the conclusion here is my service needs internet connection even when the phone is in idle state in order to function properly.
The approach that I have taken is: Using AlarmManager and a WakefulBroadcastReceiver to run Service described in the first paragraph.
The steps can be described as follows:
- Attempt to connect to MQTT broker
- Upon successful connection, do some logic and publish message to server
- Upon successful message publish, disconnect from broker and clean up resources
The above sub-routine is supposed to be executed every 10 minutes.
The problem now is, after 3-4 minutes of idle state, my service is unable to connect to the MQTT broker because there seems to be no internet connection. I checked the internet connection via:
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
Log.wtf(TAG, "internet: " + (activeNetworkInfo != null && activeNetworkInfo.isConnected());
How do I acquire internet access for my service? The only thing that I haven't tried is using evernote/android-job. But before that, I would like to gain some information because I suspect the only way that I can solve this is by somehow acquiring internet access every time my service run.
I have browsed quite a bit on this topic, but all I came across is answers pertaining to 'How to check internet connection in background service' which is not what I need. What I need is 'how to acquire internet connection when phone is idle for every time my service runs?'
Please ask me if you need code snippets, or other information that I failed to include above. Thanks in advance.
Solution
Use a Sync Adapter. It will sync your data in the background at opportune moments to prevent unnecessary battery drain and service charges.
Answered By - DKIT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.