Question

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

Was it helpful?

Solution

See this answer: How to check internet access on Android? InetAddress never times out

However I would like to point out something that you may have overlooked: checking for constant internet connectivity will consume power. A lot of power. So, what you may end up doing is draining your user's batteries (which would have a lot of negative consequences, not just poor reviews).

So, maybe we could talk about why you need to check for internet connectivity constantly? You might want to look into how you can buffer up your network requests or caching ,etc. Feel free to edit this question or even create a new one, just link to it :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top