7

I know how to check for internet connectivity when my app is open using activity. But how to check for connectivity in service when my app is not running?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • 1
    why use a Socket when [the system provides a means to see if the network is connected or not](http://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app) – panini Mar 10 '14 at 20:35
  • 1
    Use broadcast receiver, register it in manifest and pass data to your service on network status changed in onReceive method of this broadcast receiver. – Adnan Mar 10 '14 at 20:40

3 Answers3

13

You might need to use broadcast receiver. You will continuously receive updates in connectivity.(Connected/Disconnected)

Example:

Manifest:

Permissions:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Register broadcast receiver:

<receiver android:name=".ConnectivityChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

Create receiver class:

public class ConnectivityChangeReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        // Explicitly specify that which service class will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                YourService.class.getName());
        intent.putExtra("isNetworkConnected",isConnected(context));
        startService(context, (intent.setComponent(comp)));
    }

 public  boolean isConnected(Context context) {
           ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
           NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
           return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
   }

}

Your service class:

class YourService extends IntentService{

    @Override
    protected void onHandleIntent(Intent intent) {
      Bundle extras = intent.getExtras();
      boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
      // your code

   }

}
Adnan
  • 5,025
  • 5
  • 25
  • 44
3

The system provides a Broadcast when the network connectivity changes, which you can read using a BroadcastReceiver. This will be called whether your app is open or closed.

panini
  • 2,026
  • 19
  • 21
  • Tnx,so, if I want to do something(checking for updates),how can I do ? – S.M_Emamian Mar 10 '14 at 20:48
  • 1
    in the onReceive method of the BroadcastReceiver, you can run arbitrary code, so if you wanted to do some processing in the background you could start a [Service](http://developer.android.com/reference/android/app/Service.html) or something to do that – panini Mar 10 '14 at 21:27
0

Using below code you can test whether device is connected with internet or not. You can use this function anytime when you try to call any webservice or any task related to internet. You can use this function in android service which runs in background.

public boolean isConnectingToInternet(Context _context){
        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;
    }
Sanket Patel
  • 1,130
  • 14
  • 25
  • 2
    This does not answer the question. The OP said he knows how just not when the app isn't open – codeMagic Mar 10 '14 at 20:37
  • 1
    this does not my answer !!! "I know when my app is open how to checking if internet is available or not in the activity" – S.M_Emamian Mar 10 '14 at 20:38
  • I updated answer. You can use this function in android services, You need to create service and start it. You may need to handle broadcast receivers to handle service auto start after device restart etc.. – Sanket Patel Mar 10 '14 at 20:40