0

Possible Duplicate:
Android service to check internet connectivity?

I am designing an Android app to track the total data usage (download+upload). The app does the following tasks :-

  1. Continuously checks if the device is connected to the internet or not.
  2. If the device is connected to the internet then start counting the uploaded and downloaded data.
  3. The count is stored in database and displayed to the user for the current session.
  4. When the app is installed the service should be started.
  5. When the device is rebooted, the service should be started.

I have tried the following code but us this sufficient?

public final boolean isInternetOn()
{
    ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    // ARE WE CONNECTED TO THE NET
    if(     connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED  ||
            connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED   ) 
    {
        // MESSAGE TO SCREEN FOR TESTING (IF REQ)
        //Toast.makeText(this, connectionType + †connectedâ€, Toast.LENGTH_SHORT).show();
        return true;
    } 
    else
    {

        if(     connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  
                connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  )
        {
            //System.out.println(“Not Connectedâ€);
            return false;
        }
        return false;
    }
}

ANY HELP WOULD BE GREATLY APPRECIATED!

-Vaibhav.

Community
  • 1
  • 1
V Rohom
  • 9
  • 3
  • 2
    You might want to try [this](http://stackoverflow.com/questions/2789612/how-can-i-check-whether-an-android-device-is-connected-to-the-web) – Neo Oct 08 '11 at 04:00
  • 1
    Check this [link][1] u might need a broadcaster rather than service [1]: http://stackoverflow.com/questions/3141807/android-service-to-check-internet-connectivity – mayank_droid Oct 08 '11 at 04:59

1 Answers1

3

Continuously checks if the device is connected to the internet or not.

Please don't. This is not needed for your use case.

When the app is installed the service should be started.

This is not supported by Android. It is also not needed for your use case.

When the device is rebooted, the service should be started.

This is not needed for your use case.

The use of TrafficStats does not require an everlasting service. Please simply record values from TrafficStats periodically, perhaps using AlarmManager, so you do not need to keep stuff in memory all of the time.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491