user2990506 user2990506 - 2 months ago 23
Android Question

What is the solution to Check internet connectivity

getnetworkInfo' is deprecated , what is the solution? I am using compilesdkversion 24.

Answer

Use ConnectivityManager to get network access. you can use BroadcastReceiver to get constant updates of your network status.

package your_package_name;

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
    super(base);
}

public static boolean isConnected(Context context){

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo connection = manager.getActiveNetworkInfo();
    if (connection != null && connection.isConnectedOrConnecting()){
        return true;
    }
    return false;
 }
}

Receive updates from your network class, use this in your main class where to update status. Register Receiver on class getContext().registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            //not connected
        }else {
            //connected
        }
    }
};