Tạo kết nối ngang hàng (P2P) bằng Wi-Fi Direct

Wi-Fi Direct (còn gọi là ngang hàng hoặc P2P) cho phép ứng dụng của bạn nhanh chóng tìm và tương tác với các thiết bị ở gần, ở phạm vi vượt quá khả năng của Bluetooth.

Wi-Fi Direct (P2P) API cho phép các ứng dụng kết nối với các thiết bị ở gần mà không cần kết nối với mạng hoặc điểm phát sóng. Nếu ứng dụng của bạn được thiết kế để trở thành một phần của hệ thống mạng an toàn và ở gần phạm vi gần, thì Wi-Fi Direct là một lựa chọn phù hợp hơn so với mạng Wi-Fi truyền thống đặc biệt vì những lý do sau:

  • Wi-Fi Direct hỗ trợ mã hóa WPA2. (Một số mạng đặc biệt chỉ hỗ trợ loại mã hoá WEP.)
  • Các thiết bị có thể truyền phát những dịch vụ mà mình cung cấp, giúp các thiết bị khác tìm thấy các thiết bị ngang hàng dễ dàng hơn.
  • Khi xác định thiết bị nào sẽ là chủ sở hữu nhóm cho mạng đó, Wi-Fi Direct sẽ kiểm tra khả năng quản lý nguồn điện, giao diện người dùng và khả năng dịch vụ của từng thiết bị rồi sử dụng thông tin này để chọn thiết bị có thể xử lý trách nhiệm của máy chủ một cách hiệu quả nhất.
  • Android không hỗ trợ chế độ Wi-Fi đặc biệt.

Bài học này sẽ hướng dẫn bạn cách tìm và kết nối với các thiết bị ở gần bằng Wi-Fi P2P.

Thiết lập quyền cho ứng dụng

Để sử dụng Wi-Fi Direct, hãy thêm các quyền ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATEINTERNET vào tệp kê khai. Nếu ứng dụng của bạn nhắm đến Android 13 (API cấp 33) trở lên, hãy thêm quyền NEARBY_WIFI_DEVICES vào tệp kê khai. Wi-Fi Direct không yêu cầu kết nối Internet, nhưng sử dụng các ổ cắm Java tiêu chuẩn, yêu cầu quyền INTERNET. Vì vậy, bạn cần có các quyền sau để sử dụng 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"/>
    ...

Ngoài các quyền trước đó, các API sau cũng yêu cầu bật Chế độ vị trí:

Thiết lập broadcast receiver và trình quản lý ngang hàng

Để sử dụng Wi-Fi Direct, bạn cần theo dõi ý định truyền tin để cho ứng dụng của bạn biết khi nào một số sự kiện nhất định đã xảy ra. Trong ứng dụng của bạn, hãy tạo thực thể cho IntentFilter và thiết lập để theo dõi những thông tin sau:

WIFI_P2P_STATE_CHANGED_ACTION
Cho biết liệu Wi-Fi Direct có đang bật không
WIFI_P2P_PEERS_CHANGED_ACTION
Cho biết danh sách ứng dụng ngang hàng có sẵn đã thay đổi.
WIFI_P2P_CONNECTION_CHANGED_ACTION
Cho biết trạng thái kết nối Wi-Fi Direct đã thay đổi. Kể từ Android 10, đây là thuộc tính cố định. Nếu ứng dụng của bạn dựa vào việc nhận những thông báo này khi đăng ký vì các thông báo đó cố định, hãy sử dụng phương thức get thích hợp khi khởi động để lấy thông tin.
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
Cho biết thông tin chi tiết về cấu hình của thiết bị này đã thay đổi. Kể từ Android 10, đây là thuộc tính cố định. Nếu ứng dụng của bạn dựa vào việc nhận những thông báo này khi đăng ký vì các thông báo đó cố định, hãy sử dụng phương thức get thích hợp khi khởi động để lấy thông tin.

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);
    ...
}

Ở cuối phương thức onCreate(), hãy lấy một thực thể của WifiP2pManager và gọi phương thức initialize(). Phương thức này trả về một đối tượng WifiP2pManager.Channel mà sau này bạn sẽ sử dụng để kết nối ứng dụng với khung 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);
}

Bây giờ, hãy tạo một lớp BroadcastReceiver mới mà bạn sẽ dùng để theo dõi các thay đổi đối với trạng thái Wi-Fi của hệ thống. Trong phương thức onReceive(), hãy thêm một điều kiện để xử lý từng thay đổi về trạng thái nêu trên.

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));

    }
}

Cuối cùng, hãy thêm mã để đăng ký bộ lọc ý định và broadcast receiver khi hoạt động chính của bạn đang hoạt động và huỷ đăng ký khi hoạt động bị tạm dừng. Phương thức tốt nhất để thực hiện việc này là 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);
}

Bắt đầu khám phá ứng dụng ngang hàng

Để bắt đầu tìm thiết bị ở gần bằng Wi-Fi P2P, hãy gọi discoverPeers(). Phương thức này nhận các đối số sau:

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.
    }
});

Xin lưu ý rằng thao tác này chỉ bắt đầu quá trình khám phá ứng dụng ngang hàng. Phương thức discoverPeers() bắt đầu quá trình khám phá và sau đó trả về ngay lập tức. Hệ thống sẽ thông báo cho bạn nếu quá trình khám phá ứng dụng ngang hàng được bắt đầu thành công bằng các phương thức gọi trong trình nghe hành động được cung cấp. Ngoài ra, tính năng khám phá vẫn hoạt động cho đến khi bắt đầu kết nối hoặc tạo nhóm P2P.

Tìm nạp danh sách ứng dụng ngang hàng

Bây giờ, hãy viết mã tìm nạp và xử lý danh sách các ứng dụng ngang hàng. Trước tiên, hãy triển khai giao diện WifiP2pManager.PeerListListener. Giao diện này cung cấp thông tin về các kết nối ngang hàng mà Wi-Fi Direct đã phát hiện. Thông tin này cũng cho phép ứng dụng của bạn xác định thời điểm các ứng dụng ngang hàng tham gia hoặc rời khỏi mạng. Đoạn mã sau đây minh hoạ các thao tác liên quan đến các ứng dụng ngang hàng:

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;
        }
    }
}

Bây giờ, hãy sửa đổi phương thức onReceive() của broadcast receiver để gọi requestPeers() khi nhận được một ý định có thao tác WIFI_P2P_PEERS_CHANGED_ACTION. Bạn cần truyền trình nghe này vào receiver bằng cách nào đó. Bạn có thể gửi đối số này dưới dạng đối số đến hàm khởi tạo của broadcast receiver.

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");
    }...
}

Bây giờ, một ý định với ý định hành động WIFI_P2P_PEERS_CHANGED_ACTION sẽ kích hoạt yêu cầu về một danh sách ứng dụng ngang hàng đã cập nhật.

Kết nối với ứng dụng ngang hàng

Để kết nối với một ứng dụng ngang hàng, hãy tạo một đối tượng WifiP2pConfig mới rồi sao chép dữ liệu vào đối tượng đó từ WifiP2pDevice đại diện cho thiết bị mà bạn muốn kết nối. Sau đó, hãy gọi phương thức 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();
        }
    });
}

Nếu mỗi thiết bị trong nhóm của bạn hỗ trợ Wi-Fi trực tiếp, thì bạn không cần phải yêu cầu rõ ràng mật khẩu của nhóm khi kết nối. Tuy nhiên, để cho phép một thiết bị không hỗ trợ Wi-Fi Direct tham gia nhóm, bạn cần truy xuất mật khẩu này bằng cách gọi requestGroupInfo(), như minh hoạ trong đoạn mã sau:

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();
  }
});

Xin lưu ý rằng WifiP2pManager.ActionListener được triển khai trong phương thức connect() chỉ thông báo cho bạn khi thực hiện thành công hay không thành công. Để theo dõi các thay đổi ở trạng thái kết nối, hãy triển khai giao diện WifiP2pManager.ConnectionInfoListener. Lệnh gọi lại onConnectionInfoAvailable() sẽ thông báo cho bạn khi trạng thái của kết nối thay đổi. Trong trường hợp nhiều thiết bị sẽ được kết nối với một thiết bị duy nhất (chẳng hạn như trò chơi có từ ba người chơi trở lên hoặc một ứng dụng trò chuyện), một thiết bị sẽ được chỉ định là "chủ sở hữu nhóm". Bạn có thể chỉ định một thiết bị cụ thể làm chủ sở hữu nhóm của mạng bằng cách làm theo các bước trong phần Tạo nhóm.

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.
    }
}

Bây giờ, hãy quay lại phương thức onReceive() của broadcast receiver và sửa đổi phần lắng nghe ý định WIFI_P2P_CONNECTION_CHANGED_ACTION. Khi nhận được ý định này, hãy gọi requestConnectionInfo(). Đây là lệnh gọi không đồng bộ, do đó, trình nghe thông tin kết nối mà bạn cung cấp dưới dạng tham số sẽ nhận được kết quả.

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);
        }
        ...

Tạo nhóm

Nếu muốn thiết bị đang chạy ứng dụng của mình đóng vai trò là chủ sở hữu nhóm cho một mạng bao gồm các thiết bị cũ (tức là các thiết bị không hỗ trợ Wi-Fi Direct), bạn hãy làm theo trình tự các bước như trong phần Kết nối với ứng dụng ngang hàng, ngoại trừ việc bạn tạo một WifiP2pManager.ActionListener mới bằng createGroup() thay vì connect(). Cách xử lý lệnh gọi lại trong WifiP2pManager.ActionListener cũng tương tự như trong đoạn mã sau:

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();
    }
});

Lưu ý: Nếu tất cả thiết bị trong một mạng đều hỗ trợ Wi-Fi Direct, thì bạn có thể sử dụng phương thức connect() trên từng thiết bị vì phương thức này sẽ tự động tạo nhóm và chọn một chủ sở hữu nhóm.

Sau khi tạo một nhóm, bạn có thể gọi requestGroupInfo() để truy xuất thông tin chi tiết về các ứng dụng ngang hàng trên mạng, bao gồm cả tên thiết bị và trạng thái kết nối.