استخدام "اتصال Wi-Fi مباشر" (P2P) لاكتشاف الخدمة

وقد أوضح لك الدرس الأول في هذا الصف، استخدام ميزة اكتشاف خدمات الشبكة، كيفية اكتشاف الخدمات المتصلة بشبكة محلية. مع ذلك، يتيح لك استخدام "اكتشاف خدمة Wi-Fi المباشر" (P2P) اكتشاف خدمات الأجهزة المجاورة مباشرةً، بدون الاتصال بأي شبكة. يمكنك أيضًا الإعلان عن الخدمات التي تعمل على جهازك. تساعدك هذه الإمكانات في التواصل بين التطبيقات، حتى في حال عدم توفّر شبكة محلية أو نقطة اتصال.

وعلى الرغم من أنّ هذه المجموعة من واجهات برمجة التطبيقات هذه تتشابه في الغرض مع واجهات برمجة التطبيقات الخاصة باكتشاف خدمات الشبكة في درس سابق، إلا أن تنفيذها في التعليمات البرمجية يختلف كثيرًا. يوضح لك هذا الدرس كيفية اكتشاف الخدمات المتاحة من الأجهزة الأخرى، باستخدام اتصال Wi-Fi المباشر. يفترض الدرس أنك على دراية بواجهة برمجة التطبيقات Wi-Fi Direct.

إعداد البيان

لاستخدام شبكة Wi-Fi P2P، عليك إضافة الأذونات CHANGE_WIFI_STATE وACCESS_WIFI_STATE وACCESS_FINE_LOCATION وINTERNET إلى البيان. إذا كان تطبيقك يستهدف نظام التشغيل Android 13 (المستوى 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" />
    ...

بالإضافة إلى الأذونات السابقة، تتطلب واجهات برمجة التطبيقات التالية أيضًا تفعيل وضع الموقع الجغرافي:

إضافة خدمة محلية

إذا كنت تقدّم خدمة محلية، عليك تسجيلها لرصد الخدمة. بعد تسجيل خدمتك المحلية، يستجيب إطار العمل تلقائيًا لطلبات اكتشاف الخدمة من التطبيقات المشابهة.

لإنشاء خدمة محلية:

  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 للاستماع إلى السجلات الواردة. ويمكن بث هذا السجلّ اختياريًا على أجهزة أخرى. عندما يأتي أحدهما، انسخ عنوان الجهاز وأي معلومات أخرى ذات صلة تريدها في بنية بيانات خارج الطريقة الحالية، حتى تتمكن من الوصول إليها لاحقًا. يفترض المثال التالي أن السجل يحتوي على حقل "budyname"، تمت تعبئته بهوية المستخدم.

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 لإقران عنوان جهاز باسم الصديق. تستخدم أداة معالجة بيانات الخدمة هذه الأداة لربط سجلّ نظام أسماء النطاقات بمعلومات الخدمة المتجاوبة. بعد تنفيذ كلا المستمعين، يمكنك إضافتهما إلى 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(). تأخذ هذه الطريقة أيضًا المستمع للإبلاغ عن النجاح أو الفشل.

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 كوسيطة، ويوفّر لك ذلك استدعاءات تشير إلى النجاح أو الفشل. لتشخيص المشاكل، أضِف رمز تصحيح الأخطاء في onFailure(). يشير رمز الخطأ المقدم من الطريقة إلى المشكلة. إليك قيم الخطأ المحتملة وما تعنيه

P2P_UNSUPPORTED
شبكة Wi-Fi المباشرة غير متوافقة مع الجهاز الذي يتم تشغيل التطبيق عليه.
BUSY
النظام مشغول جدًا بحيث لا يمكنه معالجة الطلب.
ERROR
تعذَّر تنفيذ العملية بسبب خطأ داخلي.