使用 Wi-Fi Direct 建立 P2P 連線

Wi-Fi Direct (也稱為點對點或 P2P) 可讓應用程式迅速找到鄰近裝置並與其互動,範圍超出藍牙功能的範圍。

Wi-Fi Direct (P2P) API 可讓應用程式連線至鄰近裝置,而不必連線至網路或無線基地台。如果您的應用程式適合剛接觸高範圍的安全網路,則 Wi-Fi Direct 比傳統的 Wi-Fi 臨時網路比較適合,原因如下:

  • Wi-Fi Direct 支援 WPA2 加密。(部分臨時網路僅支援 WEP 加密)。
  • 裝置可以播送自己提供的服務,協助其他裝置更輕鬆地發現合適的同類應用程式。
  • 在判斷哪部裝置應成為網路的群組擁有者時,Wi-Fi Direct 會檢查每部裝置的電源管理、UI 和服務功能,並根據這項資訊選擇最能有效處理伺服器責任的裝置。
  • Android 不支援 Wi-Fi 臨時模式。

本課程將說明如何使用 Wi-Fi P2P 尋找鄰近裝置並建立連線。

設定應用程式權限

如要使用 Wi-Fi Direct,請在資訊清單中新增 ACCESS_FINE_LOCATIONCHANGE_WIFI_STATEACCESS_WIFI_STATEINTERNET 權限。如果應用程式指定的是 Android 13 (API 級別 33) 以上版本,請一併在資訊清單中加入 NEARBY_WIFI_DEVICES 權限。Wi-Fi Direct 不需要網際網路連線,但會使用標準的 Java 通訊端,而這需要 INTERNET 權限。因此,您必須具備下列權限,才能使用 Wi-Fi Direct:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.nsdchat"
    ...
    <!-- If your app targets Android 13 (API level 33)
         or higher, you must declare the NEARBY_WIFI_DEVICES permission. -->
        <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
        <!-- If your app derives location information from Wi-Fi APIs,
             don't include the "usesPermissionFlags" attribute. -->
        android:usesPermissionFlags="neverForLocation" />
        
    <uses-permission
        android:required="true"
        android:name="android.permission.ACCESS_FINE_LOCATION"
        <!-- If any feature in your app relies on precise location information,
             don't include the "maxSdkVersion" attribute. -->
        android:maxSdkVersion="32" />
    <uses-permission
        android:required="true"
        android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission
        android:required="true"
        android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission
        android:required="true"
        android:name="android.permission.INTERNET"/>
    ...

除了上述權限以外,下列 API 也需要啟用位置模式:

設定廣播接收器和點對點管理員

如要使用 Wi-Fi Direct,您需要監聽廣播意圖,以便在特定事件發生時通知應用程式。在應用程式中,將 IntentFilter 例項化,並將其設為監聽以下項目:

WIFI_P2P_STATE_CHANGED_ACTION
指出是否已啟用 Wi-Fi Direct
WIFI_P2P_PEERS_CHANGED_ACTION
表示可用的同類群組清單已變更。
WIFI_P2P_CONNECTION_CHANGED_ACTION
表示 Wi-Fi Direct 連線狀態已變更。從 Android 10 開始,這不是固定式。如果應用程式因為固定式而依賴於註冊時接收這些廣播訊息,請在初始化時使用適當的 get 方法取得資訊。
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
表示這部裝置的設定詳細資料已變更。從 Android 10 開始,這不是固定式。如果應用程式因為固定式而依賴於註冊時接收這些廣播訊息,請在初始化時使用適當的 get 方法取得資訊。

Kotlin

private val intentFilter = IntentFilter()
...
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)

    // Indicates a change in the Wi-Fi Direct status.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)

    // Indicates a change in the list of available peers.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)

    // Indicates the state of Wi-Fi Direct connectivity has changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)

    // Indicates this device's details have changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
    ...
}

Java

private final IntentFilter intentFilter = new IntentFilter();
...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Indicates a change in the Wi-Fi Direct status.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);

    // Indicates a change in the list of available peers.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);

    // Indicates the state of Wi-Fi Direct connectivity has changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);

    // Indicates this device's details have changed.
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    ...
}

onCreate() 方法的結尾,取得 WifiP2pManager 的執行個體,並呼叫其 initialize() 方法。這個方法會傳回一個 WifiP2pManager.Channel 物件,您稍後會用這個物件將應用程式連線到 Wi-Fi Direct 架構。

Kotlin

private lateinit var channel: WifiP2pManager.Channel
private lateinit var manager: WifiP2pManager

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
    channel = manager.initialize(this, mainLooper, null)
}

Java

Channel channel;
WifiP2pManager manager;

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
}

現在建立新的 BroadcastReceiver 類別,用來監聽系統 Wi-Fi 狀態的變更。在 onReceive() 方法中,新增條件來處理上述各項狀態變更。

Kotlin

override fun onReceive(context: Context, intent: Intent) {
    when(intent.action) {
        WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
            // Determine if Wi-Fi Direct mode is enabled or not, alert
            // the Activity.
            val state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1)
            activity.isWifiP2pEnabled = state == WifiP2pManager.WIFI_P2P_STATE_ENABLED
        }
        WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {

            // The peer list has changed! We should probably do something about
            // that.

        }
        WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {

            // Connection state changed! We should probably do something about
            // that.

        }
        WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
            (activity.supportFragmentManager.findFragmentById(R.id.frag_list) as DeviceListFragment)
                    .apply {
                        updateThisDevice(
                                intent.getParcelableExtra(
                                        WifiP2pManager.EXTRA_WIFI_P2P_DEVICE) as WifiP2pDevice
                        )
                    }
        }
    }
}

Java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // Determine if Wi-Fi Direct 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));

    }
}

最後,請新增程式碼,以便在主要活動啟用時註冊意圖篩選器和廣播接收器,並在活動暫停時取消註冊。最好的做法是 onResume()onPause() 方法。

Kotlin

/** register the BroadcastReceiver with the intent values to be matched  */
public override fun onResume() {
    super.onResume()
    receiver = WiFiDirectBroadcastReceiver(manager, channel, this)
    registerReceiver(receiver, intentFilter)
}

public override fun onPause() {
    super.onPause()
    unregisterReceiver(receiver)
}

Java

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

啟動對等互連探索

如要透過 Wi-Fi P2P 搜尋鄰近裝置,請呼叫 discoverPeers()。這個方法採用下列引數:

Kotlin

manager.discoverPeers(channel, object : WifiP2pManager.ActionListener {

    override fun onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank. Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    override fun onFailure(reasonCode: Int) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
})

Java

manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

    @Override
    public void onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank. Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    @Override
    public void onFailure(int reasonCode) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
});

請注意,這麼做只能「啟動」同類應用程式探索作業。discoverPeers() 方法會啟動探索程序,然後立即傳回。系統會透過在提供的動作事件監聽器中呼叫方法,確認對等點探索程序是否成功啟動。此外,探索功能會保持有效狀態,直到連線啟動或 P2P 群組建立完成為止。

擷取同類應用程式清單

現在請編寫程式碼,用於擷取及處理同類應用程式清單。首先請實作 WifiP2pManager.PeerListListener 介面,提供 Wi-Fi Direct 偵測到的對等點相關資訊。應用程式也能利用這項資訊判斷對等點加入或離開網路。下列程式碼片段說明這些與對等互連相關的作業:

Kotlin

private val peers = mutableListOf<WifiP2pDevice>()
...

private val peerListListener = WifiP2pManager.PeerListListener { peerList ->
    val refreshedPeers = peerList.deviceList
    if (refreshedPeers != peers) {
        peers.clear()
        peers.addAll(refreshedPeers)

        // If an AdapterView is backed by this data, notify it
        // of the change. For instance, if you have a ListView of
        // available peers, trigger an update.
        (listAdapter as WiFiPeerListAdapter).notifyDataSetChanged()

        // Perform any other updates needed based on the new list of
        // peers connected to the Wi-Fi P2P network.
    }

    if (peers.isEmpty()) {
        Log.d(TAG, "No devices found")
        return@PeerListListener
    }
}

Java

private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
...

private PeerListListener peerListListener = new PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {

        List<WifiP2pDevice> refreshedPeers = peerList.getDeviceList();
        if (!refreshedPeers.equals(peers)) {
            peers.clear();
            peers.addAll(refreshedPeers);

            // If an AdapterView is backed by this data, notify it
            // of the change. For instance, if you have a ListView of
            // available peers, trigger an update.
            ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();

            // Perform any other updates needed based on the new list of
            // peers connected to the Wi-Fi P2P network.
        }

        if (peers.size() == 0) {
            Log.d(WiFiDirectActivity.TAG, "No devices found");
            return;
        }
    }
}

現在,請修改廣播接收器的 onReceive() 方法,在收到含有 WIFI_P2P_PEERS_CHANGED_ACTION 動作的意圖時呼叫 requestPeers()。您需要透過某種方式將這個事件監聽器傳遞至接收器。其中一種方法是將其做為引數傳送至廣播接收器的建構函式。

Kotlin

fun onReceive(context: Context, intent: Intent) {
    when (intent.action) {
        ...
        WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {

            // Request available peers from the wifi p2p manager. This is an
            // asynchronous call and the calling activity is notified with a
            // callback on PeerListListener.onPeersAvailable()
            mManager?.requestPeers(channel, peerListListener)
            Log.d(TAG, "P2P peers changed")


        }
        ...
    }
}

Java

public void onReceive(Context context, Intent intent) {
    ...
    else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

        // Request available peers from the wifi p2p manager. This is an
        // asynchronous call and the calling activity is notified with a
        // callback on PeerListListener.onPeersAvailable()
        if (mManager != null) {
            mManager.requestPeers(channel, peerListListener);
        }
        Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
    }...
}

現在,包含 WIFI_P2P_PEERS_CHANGED_ACTION 動作的意圖會觸發更新對等清單的要求。

與對等互連項目連線

如要連線至對等點,請建立新的 WifiP2pConfig 物件,並從代表您要連線裝置的 WifiP2pDevice 中將資料複製到該物件。接著,呼叫 connect() 方法。

Kotlin

override fun connect() {
    // Picking the first device found on the network.
    val device = peers[0]

    val config = WifiP2pConfig().apply {
        deviceAddress = device.deviceAddress
        wps.setup = WpsInfo.PBC
    }

    manager.connect(channel, config, object : WifiP2pManager.ActionListener {

        override fun onSuccess() {
            // WiFiDirectBroadcastReceiver notifies us. Ignore for now.
        }

        override fun onFailure(reason: Int) {
            Toast.makeText(
                    this@WiFiDirectActivity,
                    "Connect failed. Retry.",
                    Toast.LENGTH_SHORT
            ).show()
        }
    })
}

Java

@Override
public void connect() {
    // Picking the first device found on the network.
    WifiP2pDevice device = peers.get(0);

    WifiP2pConfig config = new WifiP2pConfig();
    config.deviceAddress = device.deviceAddress;
    config.wps.setup = WpsInfo.PBC;

    manager.connect(channel, config, new ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver notifies us. Ignore for now.
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

如果群組中的每個裝置都支援 Wi-Fi 直接功能,則在連線時,您不需要明確要求群組的密碼。不過,如要允許不支援 Wi-Fi Direct 的裝置加入群組,您必須呼叫 requestGroupInfo() 來擷取這組密碼,如以下程式碼片段所示:

Kotlin

manager.requestGroupInfo(channel) { group ->
    val groupPassword = group.passphrase
}

Java

manager.requestGroupInfo(channel, new GroupInfoListener() {
  @Override
  public void onGroupInfoAvailable(WifiP2pGroup group) {
      String groupPassword = group.getPassphrase();
  }
});

請注意,在 connect() 方法中實作的 WifiP2pManager.ActionListener 只會在啟動成功或失敗時通知您。如要監聽連線狀態的變更,請實作 WifiP2pManager.ConnectionInfoListener 介面。onConnectionInfoAvailable() 回呼會在連線狀態變更時通知您。如果將多部裝置連線至單一裝置 (例如有三位玩家以上的遊戲,或是即時通訊應用程式),系統會將一部裝置指定為「群組擁有者」。您可以按照建立群組一節中的步驟,將特定裝置指定為網路的群組擁有者。

Kotlin

private val connectionListener = WifiP2pManager.ConnectionInfoListener { info ->

    // String from WifiP2pInfo struct
    val groupOwnerAddress: String = info.groupOwnerAddress.hostAddress

    // After the group negotiation, we can determine the group owner
    // (server).
    if (info.groupFormed && info.isGroupOwner) {
        // Do whatever tasks are specific to the group owner.
        // One common case is creating a group owner thread and accepting
        // incoming connections.
    } else if (info.groupFormed) {
        // The other device acts as the peer (client). In this case,
        // you'll want to create a peer thread that connects
        // to the group owner.
    }
}

Java

@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {

    // String from WifiP2pInfo struct
    String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();

    // After the group negotiation, we can determine the group owner
    // (server).
    if (info.groupFormed && info.isGroupOwner) {
        // Do whatever tasks are specific to the group owner.
        // One common case is creating a group owner thread and accepting
        // incoming connections.
    } else if (info.groupFormed) {
        // The other device acts as the peer (client). In this case,
        // you'll want to create a peer thread that connects
        // to the group owner.
    }
}

現在返回廣播接收器的 onReceive() 方法,然後修改用於監聽 WIFI_P2P_CONNECTION_CHANGED_ACTION 意圖的部分。收到這項意圖時,請呼叫 requestConnectionInfo()。這是非同步呼叫,因此你提供做為參數的連線資訊事件監聽器會收到結果。

Kotlin

when (intent.action) {
    ...
    WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {

        // Connection state changed! We should probably do something about
        // that.

        mManager?.let { manager ->

            val networkInfo: NetworkInfo? = intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO) as NetworkInfo

            if (networkInfo?.isConnected == true) {

                // We are connected with the other device, request connection
                // info to find group owner IP

                manager.requestConnectionInfo(channel, connectionListener)
            }
        }
    }
    ...
}

Java

    ...
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

        if (manager == null) {
            return;
        }

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

        if (networkInfo.isConnected()) {

            // We are connected with the other device, request connection
            // info to find group owner IP

            manager.requestConnectionInfo(channel, connectionListener);
        }
        ...

建立群組

如果您希望執行應用程式的裝置做為含有舊版裝置的網路 (即不支援 Wi-Fi Direct 的裝置) 的群組擁有者,請遵循「連線至對等點」一節所述的步驟,除非您使用 createGroup() (而非 connect()) 建立新的 WifiP2pManager.ActionListenerWifiP2pManager.ActionListener 中的回呼處理方式相同,如以下程式碼片段所示:

Kotlin

manager.createGroup(channel, object : WifiP2pManager.ActionListener {
    override fun onSuccess() {
        // Device is ready to accept incoming connections from peers.
    }

    override fun onFailure(reason: Int) {
        Toast.makeText(
                this@WiFiDirectActivity,
                "P2P group creation failed. Retry.",
                Toast.LENGTH_SHORT
        ).show()
    }
})

Java

manager.createGroup(channel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
        // Device is ready to accept incoming connections from peers.
    }

    @Override
    public void onFailure(int reason) {
        Toast.makeText(WiFiDirectActivity.this, "P2P group creation failed. Retry.",
                Toast.LENGTH_SHORT).show();
    }
});

注意: 如果網路中的所有裝置都支援 Wi-Fi Direct,您可以在每部裝置上使用 connect() 方法,因為這樣方法便會自動建立群組並選取群組擁有者。

建立群組後,您可以呼叫 requestGroupInfo() 來擷取有關網路上同類群組的詳細資料,包括裝置名稱和連線狀態。