How do you detect a network connection loss in Nougat, even if your application does not work?

In the API below Nougat, you can simply declare the recipient in a manifest that subscribes to CONNECTIVITY_CHANGES. This allowed me to listen to network connection changes, enable or disable the connection, and allow me to perform tasks even if my application was not running.

In Nougat, this is not possible. I know that Nougat's JobScheduler can be used to perform certain tasks in the background if there is a network connection, but there seems to be no way to listen for network connection loss.

In other words, I want to hear when my phone has lost all connectivity (Wi-Fi, LTE, etc.) and do something in the background when this happens. Is this possible for nougat?

+4
source share
1 answer

You can use NetworkChangeReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;
Context mContext;

@Override
public void onReceive(Context context, Intent intent) {
    Log.v(LOG_TAG, "Receieved notification about network status");
    isNetworkAvailable(context);
    mContext=context;

}

public boolean isNetworkAvailable(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) {
                    if (!isConnected) {
                        Log.v(LOG_TAG, "Now you are connected to Internet!");
                        Toast.makeText(context, R.string.internet_available, Toast.LENGTH_SHORT).show();

                        isConnected = true;


                    }
                    return true;
                }
            }
        }
    }
    Log.v(LOG_TAG, "You are not connected to Internet!");
    Toast.makeText(context, R.string.internet_not_available, Toast.LENGTH_SHORT).show();




    isConnected = false;
    return false;
}
0
source

Source: https://habr.com/ru/post/1660741/


All Articles