Search code examples
androidservicebroadcastreceiverintentserviceandroid-networking

Check network connectivity android


I am new using Service in Android and I am quite confused. I have and Activity and I want to check for all the time that the network connection is up (wifi or 3g). I implemented a simple Service and a BroadcastReveiver.

here the code of the Service

public class NetworkCheck extends IntentService {

private final String CONNECTION = "connection";

public NetworkCheck(String name) {
    super(name);
}

@Override
protected void onHandleIntent(Intent workIntent) {

    ConnectivityManager conMgr = (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);


    String dataString = workIntent.getDataString();

    if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
            || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

        // notify user you are not online
        Intent localIntent = new Intent().putExtra(CONNECTION, 0);

        LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);

    }
}

here the code of the BroadcastReceiver

public class NetworkReceiver extends BroadcastReceiver{

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

     int value = intent.getIntExtra("connection", 0);
     if(value == 0){
         //now I print, then I will show up a dialog
         System.out.println("NO CONNECTION!!!!!!!!");

     }

    }
}

this is the user permission in the Manifest

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

and here there is the code that I put in the onCreate method of my Activity

this.intent = new Intent(this, NetworkCheck.class);
        this.startService(this.intent);

        LocalBroadcastManager.getInstance(this).registerReceiver(new NetworkReceiver(), new IntentFilter());

This does not work and I cannot figure out why.


Solution

  • Isn´t recommended to check all the time connectivity, call it only when you need it:

    WiFi:

    public boolean isConnectedWifi(Context context) {
             ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
             return networkInfo.isConnected();
    }
    

    3G:

    public boolean isConnected3G(Context context) {
             ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);     
             return networkInfo.isConnected();
    }