ใช้ Wi-Fi Direct (P2P) เพื่อค้นหาบริการ

บทเรียนแรกของชั้นเรียนนี้เรื่องการใช้บริการเครือข่าย Discovery แสดงให้เห็นว่าคุณ วิธีค้นหาบริการที่เชื่อมต่อกับเครือข่าย LAN อย่างไรก็ตาม การใช้ การค้นพบบริการ Wi-Fi Direct (P2P) ช่วยให้คุณค้นพบบริการของอุปกรณ์ที่อยู่ใกล้เคียง โดยตรงโดยไม่ต้องเชื่อมต่อกับเครือข่าย คุณสามารถโฆษณาบริการ ที่กำลังทำงานในอุปกรณ์ของคุณ ความสามารถเหล่านี้ช่วยให้คุณสื่อสารระหว่างแอปต่างๆ แม้ในกรณีที่ไม่มีเครือข่าย LAN หรือฮอตสปอตให้ใช้งาน

แม้ว่า API ชุดนี้มีจุดประสงค์คล้ายกับการค้นพบบริการเครือข่าย API ที่สรุปไว้ในบทเรียนก่อนหน้านี้ การนำ API เหล่านั้นมาใช้ในโค้ดนั้นแตกต่างกันอย่างมาก บทเรียนนี้จะแสดงวิธีค้นหาบริการที่พร้อมใช้งานจากอุปกรณ์อื่นๆ โดยใช้ Wi-Fi Direct บทเรียนนี้จะถือว่าคุณคุ้นเคยกับ Wi-Fi Direct API

ตั้งค่าไฟล์ Manifest

หากต้องการใช้ Wi-Fi P2P ให้เพิ่ม CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_FINE_LOCATION, และ INTERNET สิทธิ์ในไฟล์ Manifest หากแอปกำหนดเป้าหมายเป็น Android 13 (API ระดับ 33) ขึ้นไป ให้เพิ่ม NEARBY_WIFI_DEVICES, สิทธิ์ในไฟล์ Manifest ของคุณ แม้ว่า Wi-Fi Direct จะไม่ต้องใช้ฟังก์ชัน การเชื่อมต่ออินเทอร์เน็ต จะใช้ซ็อกเก็ต Java มาตรฐาน และใช้ซ็อกเก็ตเหล่านี้ใน Android ต้องได้รับสิทธิ์ที่ขอ

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

นอกจากสิทธิ์ก่อนหน้านี้แล้ว API ต่อไปนี้จำเป็นต้องเปิดใช้โหมดตำแหน่งด้วย

เพิ่มบริการในท้องถิ่น

หากคุณให้บริการในท้องถิ่น คุณจะต้องลงทะเบียนบริการดังกล่าว Service Discovery เมื่อลงทะเบียนบริการในท้องถิ่นแล้ว เฟรมเวิร์ก ตอบกลับคำขอค้นพบบริการจากแอปเทียบเท่าโดยอัตโนมัติ

วิธีสร้างบริการในพื้นที่

  1. สร้าง ออบเจ็กต์ WifiP2pServiceInfo รายการ
  2. ใส่ข้อมูลเกี่ยวกับบริการของคุณลงไป
  3. โทรหา addLocalService() เพื่อลงทะเบียนร้านค้าในท้องถิ่น Service Discovery

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

สำรวจบริการที่อยู่ใกล้เคียง

Android ใช้วิธีการติดต่อกลับเพื่อแจ้งเตือนแอปพลิเคชันของคุณถึงบริการที่มีอยู่ ดังนั้น สิ่งแรกที่ต้องทำคือการตั้งค่า สร้างWifiP2pManager.DnsSdTxtRecordListenerเพื่อฟัง ระเบียนที่เข้ามาใหม่ บุคคลอื่นสามารถออกอากาศบันทึกนี้หรือไม่ก็ได้ อุปกรณ์ เมื่อมีที่อยู่อุปกรณ์เข้ามา ให้คัดลอกที่อยู่อุปกรณ์และ ที่คุณต้องการไว้ในโครงสร้างข้อมูลภายนอก เพื่อให้คุณสามารถเข้าถึงได้ในภายหลัง ตัวอย่างต่อไปนี้มีสมมติฐานว่า ระเบียนมี "buddyname" ซึ่งมีข้อมูลประจําตัวของผู้ใช้

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

หากต้องการรับข้อมูลบริการ ให้สร้าง WifiP2pManager.DnsSdServiceResponseListener ช่วงเวลานี้ จะได้รับคำอธิบายและข้อมูลการเชื่อมต่อจริง โค้ดก่อนหน้า ข้อมูลโค้ดใช้ออบเจ็กต์ Map เพื่อจับคู่ที่อยู่อุปกรณ์กับเพื่อน ชื่อ Listener การตอบกลับบริการใช้ค่านี้เพื่อลิงก์ระเบียน DNS กับ ข้อมูลบริการที่เกี่ยวข้อง ครั้งเดียว ใช้งาน Listener แล้ว ให้เพิ่มพวกเขาลงใน WifiP2pManager โดยใช้เมธอด 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);
    ...
}

ตอนนี้ให้สร้างคำขอบริการและโทรหา addServiceRequest() วิธีนี้ทำให้ Listener รายงานสถานะสำเร็จหรือล้มเหลวด้วย

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

ขั้นตอนสุดท้าย โทรหา 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(...)
                    ...
            }
        });

ไชโย ทุกอย่างเรียบร้อยดีแล้วล่ะ หากพบปัญหา โปรดทราบว่า การโทรแบบไม่พร้อมกันที่คุณได้โทร WifiP2pManager.ActionListener เป็นอาร์กิวเมนต์ และ วิธีนี้จะแสดง Callback ที่บ่งชี้ว่าสำเร็จหรือล้มเหลว วิธีวินิจฉัย ใส่โค้ดการดีบักใน onFailure() รหัสข้อผิดพลาด ที่ให้ไว้โดยการแนะนำของโจทย์ ค่าข้อผิดพลาดที่เป็นไปได้มีดังนี้ และความหมาย

P2P_UNSUPPORTED
อุปกรณ์ที่ใช้แอปไม่รองรับ Wi-Fi Direct
BUSY
ระบบไม่ว่างที่จะดำเนินการตามคำขอ
ERROR
การดำเนินการล้มเหลวเนื่องจากข้อผิดพลาดภายใน