Sử dụng Wi-Fi Direct (P2P) để khám phá dịch vụ

Bài học đầu tiên trong lớp này, Sử dụng Khám phá dịch vụ mạng, đã hướng dẫn bạn cách khám phá các dịch vụ được kết nối với mạng cục bộ. Tuy nhiên, việc sử dụng tính năng Khám phá dịch vụ Wi-Fi Direct (P2P) cho phép bạn trực tiếp khám phá dịch vụ của các thiết bị ở gần mà không cần kết nối mạng. Bạn cũng có thể quảng cáo các dịch vụ chạy trên thiết bị của mình. Những chức năng này giúp bạn giao tiếp giữa các ứng dụng, ngay cả khi không có mạng cục bộ hoặc điểm phát sóng.

Mặc dù bộ API này tương tự như các API Khám phá dịch vụ mạng đã nêu trong một bài học trước, nhưng việc triển khai các API này trong mã là rất khác. Bài học này sẽ hướng dẫn bạn cách khám phá các dịch vụ có sẵn trên các thiết bị khác bằng Wi-Fi Direct. Bài học này giả định rằng bạn đã quen thuộc với API Wi-Fi Direct.

Thiết lập tệp kê khai

Để sử dụng Wi-Fi P2P, hãy thêm các quyền CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_FINE_LOCATIONINTERNET 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. Mặc dù Wi-Fi Direct không yêu cầu kết nối Internet, nhưng Wi-Fi Direct sử dụng các ổ cắm Java tiêu chuẩn và việc sử dụng các cổng này trong Android đòi hỏi các quyền được yêu cầu.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.nsdchat"
    ...

    <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"/>
    <!-- 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" />
    ...

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

Thêm dịch vụ địa phương

Nếu đang cung cấp một dịch vụ cục bộ, bạn cần đăng ký dịch vụ đó để khám phá dịch vụ. Sau khi bạn đăng ký dịch vụ cục bộ, khung này sẽ tự động phản hồi các yêu cầu khám phá dịch vụ từ các ứng dụng ngang hàng.

Cách tạo một dịch vụ cục bộ:

  1. Tạo một đối tượng WifiP2pServiceInfo.
  2. Điền thông tin về dịch vụ của bạn vào biểu mẫu.
  3. Hãy gọi addLocalService() để đăng ký dịch vụ cục bộ nhằm khám phá dịch vụ.

Kotlin

    private fun startRegistration() {
        //  Create a string map containing information about your service.
        val record: Map<String, String> = mapOf(
                "listenport" to SERVER_PORT.toString(),
                "buddyname" to "John Doe${(Math.random() * 1000).toInt()}",
                "available" to "visible"
        )

        // Service information.  Pass it an instance name, service type
        // _protocol._transportlayer , and the map containing
        // information other devices will want once they connect to this one.
        val serviceInfo =
                WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record)

        // Add the local service, sending the service info, network channel,
        // and listener that will be used to indicate success or failure of
        // the request.
        manager.addLocalService(channel, serviceInfo, object : WifiP2pManager.ActionListener {
            override fun onSuccess() {
                // Command successful! Code isn't necessarily needed here,
                // Unless you want to update the UI or add logging statements.
            }

            override fun onFailure(arg0: Int) {
                // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
            }
        })
    }

Java

    private void startRegistration() {
        //  Create a string map containing information about your service.
        Map record = new HashMap();
        record.put("listenport", String.valueOf(SERVER_PORT));
        record.put("buddyname", "John Doe" + (int) (Math.random() * 1000));
        record.put("available", "visible");

        // Service information.  Pass it an instance name, service type
        // _protocol._transportlayer , and the map containing
        // information other devices will want once they connect to this one.
        WifiP2pDnsSdServiceInfo serviceInfo =
                WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);

        // Add the local service, sending the service info, network channel,
        // and listener that will be used to indicate success or failure of
        // the request.
        manager.addLocalService(channel, serviceInfo, new ActionListener() {
            @Override
            public void onSuccess() {
                // Command successful! Code isn't necessarily needed here,
                // Unless you want to update the UI or add logging statements.
            }

            @Override
            public void onFailure(int arg0) {
                // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
            }
        });
    }

Khám phá các dịch vụ lân cận

Android sử dụng các phương thức gọi lại để thông báo cho ứng dụng về các dịch vụ hiện có, vì vậy, điều đầu tiên cần làm là thiết lập các phương thức đó. Tạo một WifiP2pManager.DnsSdTxtRecordListener để theo dõi các bản ghi được gửi đến. Các thiết bị khác có thể tuỳ ý truyền bản ghi này. Khi có phương thức, hãy sao chép địa chỉ thiết bị và mọi thông tin liên quan khác mà bạn muốn vào một cấu trúc dữ liệu bên ngoài phương thức hiện tại để có thể truy cập sau. Ví dụ sau giả định rằng bản ghi này có chứa trường "tên bạn thân", được điền sẵn danh tính của người dùng.

Kotlin

private val buddies = mutableMapOf<String, String>()
...
private fun discoverService() {
    /* Callback includes:
     * fullDomain: full domain name: e.g. "printer._ipp._tcp.local."
     * record: TXT record dta as a map of key/value pairs.
     * device: The device running the advertised service.
     */
    val txtListener = DnsSdTxtRecordListener { fullDomain, record, device ->
        Log.d(TAG, "DnsSdTxtRecord available -$record")
        record["buddyname"]?.also {
            buddies[device.deviceAddress] = it
        }
    }
}

Java

final HashMap<String, String> buddies = new HashMap<String, String>();
...
private void discoverService() {
    DnsSdTxtRecordListener txtListener = new DnsSdTxtRecordListener() {
        @Override
        /* Callback includes:
         * fullDomain: full domain name: e.g. "printer._ipp._tcp.local."
         * record: TXT record dta as a map of key/value pairs.
         * device: The device running the advertised service.
         */

        public void onDnsSdTxtRecordAvailable(
                String fullDomain, Map record, WifiP2pDevice device) {
                Log.d(TAG, "DnsSdTxtRecord available -" + record.toString());
                buddies.put(device.deviceAddress, record.get("buddyname"));
            }
        };
}

Để nhận thông tin về dịch vụ, hãy tạo một WifiP2pManager.DnsSdServiceResponseListener. Mã này nhận được nội dung mô tả thực tế và thông tin kết nối. Đoạn mã trước đó đã triển khai đối tượng Map để ghép nối địa chỉ thiết bị với tên bạn thân. Trình nghe phản hồi của dịch vụ sử dụng chức năng này để liên kết bản ghi DNS với thông tin về dịch vụ tương ứng. Sau khi triển khai cả hai trình nghe, hãy thêm chúng vào WifiP2pManager bằng phương thức setDnsSdResponseListeners().

Kotlin

private fun discoverService() {
    ...

    val servListener = DnsSdServiceResponseListener { instanceName, registrationType, resourceType ->
        // Update the device name with the human-friendly version from
        // the DnsTxtRecord, assuming one arrived.
        resourceType.deviceName = buddies[resourceType.deviceAddress] ?: resourceType.deviceName

        // Add to the custom adapter defined specifically for showing
        // wifi devices.
        val fragment = fragmentManager
                .findFragmentById(R.id.frag_peerlist) as WiFiDirectServicesList
        (fragment.listAdapter as WiFiDevicesAdapter).apply {
            add(resourceType)
            notifyDataSetChanged()
        }

        Log.d(TAG, "onBonjourServiceAvailable $instanceName")
    }

    manager.setDnsSdResponseListeners(channel, servListener, txtListener)
    ...
}

Java

private void discoverService() {
...

    DnsSdServiceResponseListener servListener = new DnsSdServiceResponseListener() {
        @Override
        public void onDnsSdServiceAvailable(String instanceName, String registrationType,
                WifiP2pDevice resourceType) {

                // Update the device name with the human-friendly version from
                // the DnsTxtRecord, assuming one arrived.
                resourceType.deviceName = buddies
                        .containsKey(resourceType.deviceAddress) ? buddies
                        .get(resourceType.deviceAddress) : resourceType.deviceName;

                // Add to the custom adapter defined specifically for showing
                // wifi devices.
                WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
                        .findFragmentById(R.id.frag_peerlist);
                WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
                        .getListAdapter());

                adapter.add(resourceType);
                adapter.notifyDataSetChanged();
                Log.d(TAG, "onBonjourServiceAvailable " + instanceName);
        }
    };

    manager.setDnsSdResponseListeners(channel, servListener, txtListener);
    ...
}

Bây giờ, hãy tạo một yêu cầu dịch vụ và gọi addServiceRequest(). Phương thức này cũng đưa trình nghe báo cáo thành công hoặc không thành công.

Kotlin

        serviceRequest = WifiP2pDnsSdServiceRequest.newInstance()
        manager.addServiceRequest(
                channel,
                serviceRequest,
                object : WifiP2pManager.ActionListener {
                    override fun onSuccess() {
                        // Success!
                    }

                    override fun onFailure(code: Int) {
                        // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                    }
                }
        )

Java

        serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
        manager.addServiceRequest(channel,
                serviceRequest,
                new ActionListener() {
                    @Override
                    public void onSuccess() {
                        // Success!
                    }

                    @Override
                    public void onFailure(int code) {
                        // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                    }
                });

Cuối cùng, hãy gọi đến số discoverServices().

Kotlin

        manager.discoverServices(
                channel,
                object : WifiP2pManager.ActionListener {
                    override fun onSuccess() {
                        // Success!
                    }

                    override fun onFailure(code: Int) {
                        // Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
                        when (code) {
                            WifiP2pManager.P2P_UNSUPPORTED -> {
                                Log.d(TAG, "Wi-Fi Direct isn't supported on this device.")
                            }
                        }
                    }
                }
        )

Java

        manager.discoverServices(channel, new ActionListener() {

            @Override
            public void onSuccess() {
                // Success!
            }

            @Override
            public void onFailure(int code) {
                // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                if (code == WifiP2pManager.P2P_UNSUPPORTED) {
                    Log.d(TAG, "Wi-Fi Direct isn't supported on this device.");
                else if(...)
                    ...
            }
        });

Nếu mọi việc đều suôn sẻ, thì bạn đã hoàn tất! Nếu bạn gặp sự cố, hãy nhớ rằng các lệnh gọi không đồng bộ mà bạn đã thực hiện lấy WifiP2pManager.ActionListener làm đối số. Việc này sẽ cung cấp cho bạn các lệnh gọi lại cho biết có thành công hay không. Để chẩn đoán sự cố, hãy đặt mã gỡ lỗi vào onFailure(). Mã lỗi do gợi ý phương thức cung cấp ở bài toán. Dưới đây là các giá trị lỗi có thể xảy ra và ý nghĩa của chúng

P2P_UNSUPPORTED
Wi-Fi Direct không được hỗ trợ trên thiết bị đang chạy ứng dụng.
BUSY
Hệ thống quá bận nên không xử lý được yêu cầu.
ERROR
Thao tác không thành công do lỗi nội bộ.