Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check internet connectivity continuously in background while android application running

Tags:

android

I want to check internet connectivity continuously in background while my android application running. I mean from starting of the application to the end of the application. How can i do it? What should be the approach?

like image 996
Manish Avatar asked Jan 21 '14 09:01

Manish


3 Answers

I know I am late to answer this Question. But here is a way to monitor the Network Connection Continuously in an Activity/Fragment.

We will use Network Callback to monitor our connection in an Activity/Fragment

first, declare two variable in class

// to check if we are connected to Network
boolean isConnected = true;

// to check if we are monitoring Network
private boolean monitoringConnectivity = false;

Next, We will write the Network Callback Method

private ConnectivityManager.NetworkCallback connectivityCallback
            = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            isConnected = true;
            LogUtility.LOGD(TAG, "INTERNET CONNECTED");
        }

        @Override
        public void onLost(Network network) {
            isConnected = false;
            LogUtility.LOGD(TAG, "INTERNET LOST");
        }
    };

Now Since we have written our Callback we will Now write a method which will monitor our Network Connection, and in this method, we will register our NetworkCallback.

// Method to check network connectivity in Main Activity
    private void checkConnectivity() {
        // here we are getting the connectivity service from connectivity manager
        final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);

        // Getting network Info
        // give Network Access Permission in Manifest
        final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        // isConnected is a boolean variable
        // here we check if network is connected or is getting connected
        isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

        if (!isConnected) {
            // SHOW ANY ACTION YOU WANT TO SHOW
            // WHEN WE ARE NOT CONNECTED TO INTERNET/NETWORK
            LogUtility.LOGD(TAG, " NO NETWORK!");
// if Network is not connected we will register a network callback to  monitor network
            connectivityManager.registerNetworkCallback(
                    new NetworkRequest.Builder()
                            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                            .build(), connectivityCallback);
            monitoringConnectivity = true;
        }

    }

All our work is almost finished we just need to call our checkConnectivity(), the method in onResume() of our Activity/Fragment

  @Override
    protected void onResume() {
        super.onResume();
        checkConnectivity();
    }

*unRegister the NetworkCallback in onPause() ,method of your Activity/Fragment *

   @Override
    protected void onPause() {
        // if network is being moniterd then we will unregister the network callback
        if (monitoringConnectivity) {
            final ConnectivityManager connectivityManager
                    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManager.unregisterNetworkCallback(connectivityCallback);
            monitoringConnectivity = false;
        }
        super.onPause();
    }

That's it, just add this code in which every class of your Activity/Fragment were you need to monitor the Network!.And don't forget to unregister it!!!

like image 128
hermes Avatar answered Oct 06 '22 18:10

hermes


Create class that extends BroadcastReceiver, use ConnectivityManager.EXTRA_NO_CONNECTIVITY to get connection info.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

public class CheckConnectivity extends BroadcastReceiver{

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

    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }

Add this permission in mainfest too

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
like image 37
Ajay Venugopal Avatar answered Oct 06 '22 19:10

Ajay Venugopal


In Activity or fragment

public static final String BROADCAST = "checkinternet";
IntentFilter intentFilter;

inside oncreate

   intentFilter = new IntentFilter();
   intentFilter.addAction(BROADCAST);
   Intent serviceIntent = new Intent(this,Networkservice.class);
   startService(serviceIntent);
   if (Networkservice.isOnline(getApplicationContext())){
       Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
   }else
       Toast.makeText(getApplicationContext(),"false",Toast.LENGTH_SHORT).show();

outside oncreate

 public BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BROADCAST)){
            if (intent.getStringExtra("online_status").equals("true")){
                Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
                Log.d("data","true");
            }else {
                Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
                Log.d("data", "false");
            }
        }
    }
};

@Override
protected void onRestart() {
    super.onRestart();
    registerReceiver(broadcastReceiver,intentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver,intentFilter);
}

//class

public class Networkservice extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler.post(perioud);
    return START_STICKY;
}
public static boolean isOnline(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cm.getActiveNetworkInfo();
    if (nf!=null&&nf.isConnectedOrConnecting())
        return true;
        else
            return false;
}
Handler handler=new Handler();
private Runnable perioud =new Runnable() {
    @Override
    public void run() {
        handler.postDelayed(perioud,1*1000- SystemClock.elapsedRealtime()%1000);

        Intent intent = new Intent();
        intent.setAction(MainActivity.BROADCAST);
        intent.putExtra("online_status",""+isOnline(Networkservice.this));
        sendBroadcast(intent);
    }
};
}
like image 39
Akhilesh Chaudhary Avatar answered Oct 06 '22 19:10

Akhilesh Chaudhary