如何检查Wi-Fi p2p是否已连接?
在我的应用程序中,我需要检查 p2p 是否已连接。以前我使用以下代码对其进行归档,但 NetworkInfo 已弃用,所以我想以另一种方式实现它。
mWifiP2pManager.requestNetworkInfo(mChannel, new NetworkInfoListener() {
@Override
public void onNetworkInfoAvailable(NetworkInfo networkInfo) {
mIsP2pConnected = networkInfo.isConnected();
}
});
我尝试使用以下代码来获取 p2p 的状态。但是当我通过 Wi-Fi Direct 连接其他设备时,我找不到此日志。 但是,如果我将addCapability
的参数设置为NetworkCapabilities.NET_CAPABILITY_INTERNET并打开wifi,我可以找到此日志。
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试添加 WIFI 传输类型以及添加 WIFI_P2P 功能:
Try to add WIFI transport type along with adding WIFI_P2P capability: