שימוש ב-Wi-Fi ישיר (P2P) לחיפוש שירות

בשיעור הראשון בקורס הזה, שימוש בזיהוי שירותים ברשת, הסברנו איך לזהות שירותים שמחוברים לרשת מקומית. עם זאת, באמצעות זיהוי שירותים של Wi-Fi ישיר (P2P) אתם יכולים לזהות את השירותים של מכשירים קרובים ישירות, בלי להתחבר לרשת. אתם יכולים גם לפרסם את השירותים שפועלים במכשיר שלכם. היכולות האלה מאפשרות לכם לתקשר בין אפליקציות, גם כשאין רשת מקומית או נקודה לשיתוף אינטרנט (Hotspot) זמינה.

המטרה של קבוצת ממשקי ה-API הזו דומה לזו של ממשקי ה-API לזיהוי שירותי רשת שמתוארים בשיעור הקודם, אבל ההטמעה שלהם בקוד שונה מאוד. בשיעור הזה נסביר איך לגלות שירותים שזמינים ממכשירים אחרים באמצעות Wi-Fi ישיר. השיעור מתבסס על ההנחה שאתם כבר מכירים את ה-API של Wi-Fi ישיר.

הגדרת המניפסט

כדי להשתמש ב-Wi-Fi P2P, צריך להוסיף למניפסט את ההרשאות CHANGE_WIFI_STATE,‏ ACCESS_WIFI_STATE,‏ ACCESS_FINE_LOCATION ו-INTERNET. אם האפליקציה מטרגטת ל-Android 13 (רמת API ‏33) ומעלה, צריך להוסיף למניפסט גם את ההרשאה NEARBY_WIFI_DEVICES. למרות ש-Wi-Fi ישיר לא דורש חיבור לאינטרנט, הוא משתמש בשקעי 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 הבאים דורשים גם הפעלה של מצב מיקום:

הוספת שירות מקומי

אם אתם מספקים שירות מקומי, אתם צריכים לרשום אותו לזיהוי שירותים. אחרי שרושמים את השירות המקומי, המסגרת מגיבה באופן אוטומטי לבקשות לזיהוי שירותים מעמיתים.

כדי ליצור שירות מקומי:

  1. יוצרים אובייקט WifiP2pServiceInfo.
  2. ממלאים את הפרטים של השירות.
  3. קוראים ל-addLocalService() כדי לרשום את השירות המקומי לזיהוי שירותים.

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 כדי להתאים בין כתובת המכשיר לשם של איש הקשר. המאזין לתגובת השירות משתמש בזה כדי לקשר את רשומת ה-DNS למידע המתאים על השירות. אחרי שמטמיעים את שני המאזינים, מוסיפים אותם ל-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 כארגומנט, וזה מספק לכם קריאות חוזרות (callbacks) שמציינות הצלחה או כישלון. כדי לאבחן בעיות, צריך להוסיף קוד ניפוי באגים ב-onFailure(). קוד השגיאה שמוחזר מהשיטה מרמז על הבעיה. אלה ערכי השגיאה האפשריים והמשמעות שלהם

P2P_UNSUPPORTED
אין תמיכה ב-Wi-Fi ישיר במכשיר שבו פועלת האפליקציה.
BUSY
‫
המערכת עסוקה מדי ולא יכולה לעבד את הבקשה.
ERROR
הפעולה נכשלה בגלל שגיאה פנימית.