Programming from 51 years old Note: Checking Android network connection

NetworkInfo has been deprecated since API29 </ font>. The text uses NetworkInfo, so I searched for an alternative. It took a long time and I forgot who Android, PHP, Laravel, etc.


By the way, in the reference, read ** ConnectivityManager.NetworkCallback API ** carefully and consider ** ConnectivityManager # getNetworkCapabilities </ font> ** or ConnectivityManager # getLinkProperties! It seems that ** getNetworkCapabilities </ font> ** is fine?

ConnectivityManager.getNetworkCapabilities

python


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get the class object manager that tells you the network connection status!
        //Get the network object you are currently connected to by default with getActiveNetwork!
        //capabilities You can check various connection information such as wireless connection points, carrier services related to connections, and communication connection types!
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        Network network = manager.getActiveNetwork();
        NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);

        //If it is wifi
        if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
            Log.d("TRANSPORT","WIFI");
        }
        //If it is mobile communication
        if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
            Log.d("TRANSPORT","CELLULAER");
        }
        Log.d("TRANSPORT", String.valueOf(capabilities));
    }
}

The state constants you want to check on the net connection (such as NetworkCapabilities.TRANSORT_CELLULAR) are

https://developer.android.com/reference/android/net/NetworkCapabilities.html#TRANSPORT_WIFI

Recommended Posts