Wi-Fi Direct की मदद से P2P कनेक्शन बनाएं

Wi-Fi Direct (इसे पीयर-टू-पीयर या P2P भी कहा जाता है) की मदद से, आपका ऐप्लिकेशन आस-पास मौजूद डिवाइसों को तुरंत ढूंढ सकता है और उनसे इंटरैक्ट कर सकता है. यह ब्लूटूथ की पहुंच से ज़्यादा दूरी पर भी काम करता है.

Wi-Fi Direct (P2P) API, ऐप्लिकेशन को आस-पास मौजूद डिवाइसों से कनेक्ट करने की अनुमति देता है किसी नेटवर्क या हॉटस्पॉट से कनेक्ट करने की ज़रूरत न हो. अगर आपके ऐप्लिकेशन को किसी सुरक्षित और कम रेंज वाले किसी वाई-फ़ाई नेटवर्क का हिस्सा बनने के लिए डिज़ाइन किया गया है पारंपरिक वाई-फ़ाई ऐड-हॉक की तुलना में डायरेक्ट विकल्प एक बेहतर विकल्प है नीचे दी गई वजहों से नेटवर्किंग:

  • Wi-Fi Direct, WPA2 एन्क्रिप्शन का समर्थन करता है. (कुछ ऐड-हॉक नेटवर्क सिर्फ़ WEP एन्क्रिप्शन के साथ काम करते हैं.)
  • डिवाइस, अपनी सेवाओं को ब्रॉडकास्ट कर सकते हैं. इससे, दूसरे डिवाइसों को अपने लिए सही पीयर ढूंढने में आसानी होती है.
  • यह तय करते समय कि नेटवर्क के लिए किस डिवाइस को ग्रुप का मालिक बनाना चाहिए, Wi-Fi Direct हर डिवाइस के पावर मैनेजमेंट, यूज़र इंटरफ़ेस, और सेवा की सुविधाओं की जांच करता है. साथ ही, इस जानकारी का इस्तेमाल करके वह डिवाइस चुनता है जो सर्वर की ज़िम्मेदारियों को सबसे असरदार तरीके से मैनेज कर सकता है.
  • Android पर, वाई-फ़ाई ऐड-हॉक मोड की सुविधा काम नहीं करती.

इस लेसन में, P2P वाई-फ़ाई का इस्तेमाल करके, आस-पास मौजूद डिवाइसों को ढूंढने और उनसे कनेक्ट करने का तरीका बताया गया है.

ऐप्लिकेशन अनुमतियां सेट करना

वाई-फ़ाई डायरेक्ट का इस्तेमाल करने के लिए, अपने मेनिफ़ेस्ट में ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, और INTERNET अनुमतियां जोड़ें. अगर आपका ऐप्लिकेशन Android 13 (एपीआई लेवल 33) या उसके बाद के वर्शन को टारगेट करता है, तो अपने मेनिफ़ेस्ट में NEARBY_WIFI_DEVICES अनुमति भी जोड़ें. वाई-फ़ाई उपलब्ध डायरेक्ट को इंटरनेट कनेक्शन की ज़रूरत नहीं होती, लेकिन यह स्टैंडर्ड Java का इस्तेमाल करता है सॉकेट के लिए, INTERNET की ज़रूरत होती है अनुमति. इसलिए 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"/>
    ...

ऊपर दी गई अनुमतियों के अलावा, इन एपीआई के लिए भी जगह की जानकारी का मोड चालू होना ज़रूरी है:

ब्रॉडकास्ट रिसीवर और पीयर-टू-पीयर मैनेजर सेट अप करना

Wi-Fi Direct का इस्तेमाल करने के लिए, आपको ब्रॉडकास्ट इंटेंट सुनने होंगे कुछ खास इवेंट के होने पर ऐप्लिकेशन. अपने ऐप्लिकेशन में, IntentFilter का उदाहरण बनाएं और इसे इनके लिए सुनने के लिए सेट करें:

WIFI_P2P_STATE_CHANGED_ACTION
यह बताता है कि Wi-Fi Direct चालू है या नहीं
WIFI_P2P_PEERS_CHANGED_ACTION
इससे पता चलता है कि मिलते-जुलते ऐप्लिकेशन की उपलब्ध सूची बदल गई है.
WIFI_P2P_CONNECTION_CHANGED_ACTION
अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है इससे पता चलता है कि Wi-Fi Direct की कनेक्टिविटी बदल गई है. Android 10 से, यह सुविधा काम नहीं करती. अगर आपका ऐप्लिकेशन इन शर्तों को रजिस्ट्रेशन पर ब्रॉडकास्ट करता है, क्योंकि वह स्टिकी था. इसलिए, सही get का इस्तेमाल करें तो इस तरीके का इस्तेमाल करें.
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है इससे पता चलता है कि इस डिवाइस के कॉन्फ़िगरेशन की जानकारी बदल गई है. इससे शुरू हो रहा है Android 10, यह स्टिकी नहीं है. अगर आपका ऐप्लिकेशन, रजिस्टर करने के समय इन ब्रॉडकास्ट को पाने पर भरोसा करता है, क्योंकि ये स्टिक थे, तो जानकारी पाने के लिए, शुरू करने के समय सही get तरीका इस्तेमाल करें.
KotlinJava
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)
    ...
}
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);
    ...
}

onCreate() तरीके के आखिर में, WifiP2pManager का एक इंस्टेंस पाएं और उसके initialize() को कॉल करें तरीका. यह तरीका एक WifiP2pManager.Channel ऑब्जेक्ट दिखाता है. इसका इस्तेमाल, बाद में अपने ऐप्लिकेशन को Wi-Fi Direct फ़्रेमवर्क से कनेक्ट करने के लिए किया जाएगा.

KotlinJava
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)
}
Channel channel;
WifiP2pManager manager;

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
}

अब एक नई BroadcastReceiver क्लास बनाएं. इसका इस्तेमाल, सिस्टम के वाई-फ़ाई स्टेटस में होने वाले बदलावों को सुनने के लिए किया जाएगा. onReceive() में तरीका है, तो ऊपर दिए गए हर स्थिति बदलाव को मैनेज करने के लिए एक शर्त जोड़ें.

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

    }
}

आखिर में, इंटेंट फ़िल्टर और ब्रॉडकास्ट रिसीवर को रजिस्टर करने के लिए कोड जोड़ें आपकी मुख्य गतिविधि चालू है और गतिविधि के रोके जाने पर उसका रजिस्ट्रेशन रद्द कर दें. ऐसा करने के लिए, onResume() और onPause() तरीके सबसे सही हैं.

KotlinJava
/** 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)
}
/** 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);
}

मिलते-जुलते कॉन्टेंट की खोज शुरू करना

वाई-फ़ाई पी2पी की मदद से, आस-पास मौजूद डिवाइसों को खोजने के लिए, discoverPeers() को कॉल करें. इस तरीके से इन आर्ग्युमेंट का इस्तेमाल करें:

  • WifiP2pManager.Channel आपने पीयर-टू-पीयर mManager को शुरू करने पर मिला कैशबैक
  • तरीकों के साथ WifiP2pManager.ActionListener को लागू करना सिस्टम, खोज के नतीजों में सफल होने और असफल होने की कोशिश करता है.
KotlinJava
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.
    }
})
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.
    }
});

ध्यान रखें कि इससे सिर्फ़ मिलते-जुलते ऐप्लिकेशन की खोज शुरू होती है. कॉन्टेंट बनाने discoverPeers() तरीका खोजने की प्रोसेस शुरू करता है. इसके बाद, तुरंत वापस आ जाता है. सिस्टम आपको इसकी सूचना देता है कि मिलते-जुलते ऐप्लिकेशन का पता लगाने की प्रोसेस दिए गए ऐक्शन लिसनर में तरीकों को कॉल करके शुरू किया जा सकता है. साथ ही, डिस्कवरी तब तक चालू रहती है, जब तक कोई कनेक्शन शुरू नहीं हो जाता या कोई पी2पी ग्रुप नहीं बन जाता.

मिलते-जुलते ऐप्लिकेशन की सूची फ़ेच करें

अब वह कोड लिखें जो पीयर की सूची को फ़ेच और प्रोसेस करता है. पहला WifiP2pManager.PeerListListener को लागू करें इंटरफ़ेस, जो उन पीयर के बारे में जानकारी देता है जिन्हें Wi-Fi Direct की पहचान की गई. इस जानकारी की मदद से, आपके ऐप्लिकेशन को यह भी पता चलता है कि पीयर नेटवर्क में कब शामिल हुए या कब छोड़ा. नीचे दिया गया कोड स्निपेट इन कार्रवाइयों के बारे में बताता है मिलते-जुलते ऐप्लिकेशन से संबंधित:

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

अब WIFI_P2P_PEERS_CHANGED_ACTION ऐक्शन वाला इंटेंट मिलने पर, requestPeers() को कॉल करने के लिए, अपने ब्रॉडकास्ट रिसीवर के onReceive() तरीके में बदलाव करें. आपको इस लिसनर को किसी तरह रिसीवर में पास करना होगा. एक तरीका यह है कि का इस्तेमाल, ब्रॉडकास्ट रिसीवर के कंस्ट्रक्टर के लिए आर्ग्युमेंट के तौर पर करता है.

KotlinJava
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")


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

अब, कार्रवाई WIFI_P2P_PEERS_CHANGED_ACTION के साथ कोई इंटेंट, अपडेट की गई पीयर सूची के लिए अनुरोध को ट्रिगर करता है.

किसी मिलते-जुलते ऐप्लिकेशन से कनेक्ट करें

किसी मिलते-जुलते ऐप्लिकेशन से कनेक्ट करने के लिए, एक नया WifiP2pConfig ऑब्जेक्ट बनाएं. इसके बाद, WifiP2pDevice उस डिवाइस का प्रतिनिधित्व कर रहा है जिसे आपको जोड़ना है कनेक्ट करें. इसके बाद, connect() वाला तरीका कॉल करें.

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

अगर आपके ग्रुप में मौजूद हर डिवाइस पर वाई-फ़ाई डायरेक्ट की सुविधा काम करती है, तो कनेक्ट करते समय आपको ग्रुप का पासवर्ड पूछने की ज़रूरत नहीं पड़ेगी. हालांकि, वाई-फ़ाई डायरेक्ट की सुविधा के बिना काम करने वाले डिवाइस को ग्रुप में शामिल करने के लिए, आपको requestGroupInfo() को कॉल करके यह पासवर्ड फिर से पाना होगा. इस बारे में यहां दिए गए कोड स्निपेट में बताया गया है:

KotlinJava
manager.requestGroupInfo(channel) { group ->
    val groupPassword = group.passphrase
}
manager.requestGroupInfo(channel, new GroupInfoListener() {
  @Override
  public void onGroupInfoAvailable(WifiP2pGroup group) {
      String groupPassword = group.getPassphrase();
  }
});

ध्यान दें कि WifiP2pManager.ActionListener connect() तरीके से आपको इसकी सूचना सिर्फ़ तब मिलती है, जब सदस्यता लेने की प्रक्रिया सफल या असफल हो जाता है. कनेक्शन की स्थिति में होने वाले बदलावों को सुनने के लिए, WifiP2pManager.ConnectionInfoListener इंटरफ़ेस. इसका onConnectionInfoAvailable() कॉलबैक आपको तब सूचना देता है, जब कनेक्शन में बदलाव. ऐसे मामलों में जहां कनेक्ट किए जाने वाले कई डिवाइस एक डिवाइस (जैसे, तीन या उससे ज़्यादा खिलाड़ियों वाला गेम या कोई चैट ऐप्लिकेशन), एक डिवाइस को "समूह का मालिक" नियुक्त किया गया है. आप किसी विशेष डिवाइस को आप नेटवर्क के समूह के मालिक को ग्रुप बनाएं सेक्शन.

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

अब ब्रॉडकास्ट रिसीवर के लिए onReceive() तरीके पर वापस जाएं और सेक्शन में बदलाव करें जो WIFI_P2P_CONNECTION_CHANGED_ACTION इंटेंट को सुनता है. यह इंटेंट मिलने पर, requestConnectionInfo() पर कॉल करें. यह एक असाइनोक्रोनस कॉल है, इसलिए नतीजे, पैरामीटर के तौर पर दिए गए कनेक्शन की जानकारी सुनने वाले को मिलते हैं.

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

ग्रुप बनाना

अगर आप चाहते हैं कि आपका ऐप्लिकेशन चल रहा डिवाइस किसी ऐसा नेटवर्क जिसमें लेगसी डिवाइस शामिल हैं—यानी, वे डिवाइस जो काम नहीं करते Wi-Fi Direct—आप चरणों के समान अनुक्रम का अनुसरण करते हैं, जैसे कि किसी मिलते-जुलते ऐप्लिकेशन से कनेक्ट करना सेक्शन WifiP2pManager.ActionListener connect() के बजाय createGroup() का इस्तेमाल किया जा रहा है. WifiP2pManager.ActionListener में कॉलबैक मैनेज करने का तरीका एक जैसा है, जैसा कि नीचे दिए गए कोड स्निपेट में दिखाया गया है:

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

ध्यान दें: अगर नेटवर्क के सभी डिवाइस, वाई-फ़ाई की सुविधा देते हैं यानि आप हर डिवाइस पर connect() तरीके का इस्तेमाल कर सकते हैं, क्योंकि तरीके से ग्रुप बनाया जाता है और अपने-आप ग्रुप के मालिक को चुना जाता है.

ग्रुप बनाने के बाद, नेटवर्क पर मौजूद पीयर के बारे में जानकारी पाने के लिए, requestGroupInfo() को कॉल किया जा सकता है. इसमें डिवाइस के नाम और कनेक्शन की स्थिति शामिल है.