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
Probably there is some better way, but I've implemented this as a STICK_SERVICE as @Rahul suggested, and for avoiding killing the service I forced a fixed notification in status bar. I know this probably is not a good practice, however the client has asked to show "App is running..." in the status bar, so it's ok.
SyncService.class
And then in my first activity onCreate I call this: