在Android上使用Wi-Fi创建P2P连接:创建BroadcastReceiver类

我正尝试在Android上创建Wi-Fi P2P连接。 我指的是API https://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html,但我坚持创建BroadcastReceiver类。

它说:“现在创建一个新的BroadcastReceiver类,用来监听系统的Wi-Fi P2P状态的变化。在onReceive()方法中,添加一个条件来处理上面列出的每个P2P状态变化。

@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // Determine if Wifi P2P mode is enabled or not, alert // the Activity. int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { activity.setIsWifiP2pEnabled(true); } else { activity.setIsWifiP2pEnabled(false); } } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { // The peer list has changed! We should probably do something about // that. } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { // Connection state changed! We should probably do something about // that. } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager() .findFragmentById(R.id.frag_list); fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra( WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)); } } 

现在我有关于这个API代码片段的以下问题: –

1)在上面的代码中使用了什么activity 。在使用API​​片段之前, mManagermChannel都已被定义,但我无法findactivity已定义的位置。

2)为了解决上述问题,我有一个类的描述如下

 class MyBroadcastReceiver( val manager: WifiP2pManager, val channel: WifiP2pManager.Channel, val activity: PlayOverNetworkActivity ): BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action when(action) { WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> { // Determine if Wifi P2P mode is enabled or not, alert the activity val state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1) if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { activity.setIsWifiP2pEnabled(true) } else { activity.setIsWifiP2pEnabled(false) } } } } } 

在上面的代码中,我没有find任何方法setIsWifiP2pEnabled() 。 所以,我是否需要定义这个方法,或者我是否首先通过传递活动PlayOverNetworkActivity来做这个错误,这个活动实际上是在onCreate()方法中初始化mManagermChannel对象的活动。

注意:虽然我正在Kotlin编写代码,但Kotlin和Android对我来说都是非常新的。 所以,如果你使用Kotlin作为答案,那么我可以很容易的跟进。