I making an app. The app needs internet for 5 activities, the 4 other activities don't need internet.
The Activity's that need to have internet need it because they have to do a CRUD and do httppost to the website to communicate with the DB. So at the moment on the onCreate I do a check for an internet connection like this
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false
if(isInternetPresent)
Log.e("Internet available","Internet available");
//Do httpPost logic here
else
Log.e("Internet not available","Internet not available");
//Tell the user that he needs internet
ConnectionDetector
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
But what after the onCreate? What if the user enters the Activity, the check passes in the onCreate, he fills in the form and then he got disconnected from the internet. How do I check this part? And how do I implement that with my current code? That's is why in the first requirement I wanted constant internet connection checking. But that'll drain battery like cbrulak pointed out