'How to check whether Wi-Fi p2p is connected?

In my app, I need to check if p2p is connected. Previously I use following code to archive it, but NetworkInfo is deprecated, so I want to implement it in another way.

mWifiP2pManager.requestNetworkInfo(mChannel, new NetworkInfoListener() {
        @Override
        public void onNetworkInfoAvailable(NetworkInfo networkInfo) {
            mIsP2pConnected = networkInfo.isConnected();
        }
    });

I tried to use following code to get the status of p2p. But when I connect other device via Wi-Fi Direct, I can't find this log. However, if I set the parameter of addCapability is NetworkCapabilities.NET_CAPABILITY_INTERNET and turn on wifi, I can find this log.

        mCM = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest networkRequest =
                new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P).build();
        mCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                Log.d("MainActivity", "onAvailable: Detect network");

            }
        };
       mCM.registerNetworkCallback(networkRequest, mCallback);


Solution 1:[1]

wifiP2pManger.requestConnectionInfo

Solution 2:[2]

Try to add WIFI transport type along with adding WIFI_P2P capability:

...
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
NetworkRequest networkRequest = builder.build();
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hydrolysis Zhao
Solution 2 Bedgo