I need to check for internet connection in background.... i am saving some data in my database and whenever i get internet connection, it should upload the data on my server... i need a background service which will check for internet connection continuously even if i close my App, i tried few methods but they all work only if i open my app... Currently i am checking the internet connection like this
/checking internet connection
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
//not connected to internet
connected = false;
if(connected) {
//getting teacher data if INTERNET_STATE is true(if will be still true if connected to a wifi or network without internet)
getOfflineSubjectData();
getTeacherData();
}
else{
getOfflineSubjectData();
Toast.makeText(teacher_homePage.this,"no internet",Toast.LENGTH_SHORT).show();
}
NOTE I don't want a method which will not work after i close my app... Just like whatsapp when we close the app,We still get text messages
Code check internet access by using timer, I have made a service for that First time I have posted on stack.... so sorry in advance because i am not able to post it in good format
I know it's too late to answer your question but still, this is a perfectly working solution.
We can easily do it by using a Service and a Broadcast Receiver simultaneously to get the output as you wish. This will work always i.e when app is running, app is minimized or when app is even removed from minimized apps.
Manifest Code :
MyService.java
ConnectionHelper.java
Your Activity Code
If you need to check Internet in Background even App is killed then must implement sticky service. Which will stick in background and will do uploading work for you. Create a DB or any other persistence storage in which you can save your data and maintian their status.
For E.g.- If data is uploaded then mark its status as
true
or remove it from DB and on next time get data whose status is nottrue
or not sent to server yet.use this method anywhere
Android manifest
Create a BroadcastReceiver to listen internet connectivity
Then configure receiver in Android Manifest
Then check internet connection in your Activity