اتصال Wi-Fi المباشر (المعروف أيضًا باسم شبكة الند للند أو P2P) يسمح لتطبيقك بالعثور على الأجهزة المجاورة والتفاعل معها بسرعة، على نطاق يتجاوز إمكانات البلوتوث.
تسمح واجهات برمجة التطبيقات Wi-Fi Direct (P2P) للتطبيقات بالاتصال بالأجهزة المجاورة بدون الحاجة إلى الاتصال بشبكة أو نقطة اتصال. إذا تم تصميم تطبيقك ليكون جزءًا من شبكة آمنة قريبة النطاق، يُعدّ اتصال Wi-Fi المباشر خيارًا مناسبًا أكثر من شبكة Wi-Fi التقليدية للأسباب التالية:
- يتوافق اتصال Wi-Fi المباشر مع تشفير WPA2. (تتوافق بعض الشبكات المخصّصة مع تشفير WEP فقط).
- يمكن للأجهزة بث الخدمات التي تقدّمها، ما يساعد الأجهزة الأخرى في اكتشاف الأجهزة المشابهة المناسبة بسهولة أكبر.
- عند تحديد الجهاز الذي يجب أن يكون مالك المجموعة للشبكة، يفحص اتصال Wi-Fi المباشر إدارة الطاقة وواجهة المستخدم وإمكانات الخدمة لكل جهاز ويستخدم هذه المعلومات لاختيار الجهاز الذي يمكنه التعامل مع مسؤوليات الخادم بفعالية أكبر.
- لا يتوافق Android مع وضع تخصيص شبكة Wi-Fi.
يشرح لك هذا الدرس كيفية العثور على الأجهزة المجاورة والاتصال بها باستخدام خدمة Wi-Fi P2P.
إعداد أذونات التطبيقات
لاستخدام اتصال Wi-Fi مباشر، أضِف أذونات
ACCESS_FINE_LOCATION
وCHANGE_WIFI_STATE
وACCESS_WIFI_STATE
وINTERNET
إلى ملف البيان.
إذا كان تطبيقك يستهدف نظام التشغيل Android 13 (المستوى 33 لواجهة برمجة التطبيقات) أو الإصدارات الأحدث، عليك أيضًا إضافة
إذن NEARBY_WIFI_DEVICES
إلى ملف البيان. ولا تتطلّب تقنية Wi-Fi
مباشرة اتصالاً بالإنترنت، لكنّها تستخدم مقابس Java عادية
يتطلب ذلك الحصول على
إذن INTERNET
. لذا، عليك الحصول على الأذونات التالية لاستخدام اتصال Wi-Fi مباشر:
<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 مباشر، عليك الاستماع إلى أهداف البث التي تخبر تطبيقك عند وقوع أحداث معينة. في تطبيقك، أنشئ مثيلاً
للرمز IntentFilter
واضبطه لرصد ما يلي:
WIFI_P2P_STATE_CHANGED_ACTION
- تشير إلى ما إذا كانت ميزة Wi-Fi المباشرة مفعَّلة
WIFI_P2P_PEERS_CHANGED_ACTION
- تشير إلى أنّه تم تغيير قائمة التطبيقات المشابهة المتوفّرة.
WIFI_P2P_CONNECTION_CHANGED_ACTION
يشير الرمز -
إلى تغيير حالة اتصال Wi-Fi المباشر. بدءًا من نظام التشغيل Android 10، لن يكون هذا الموقع ثابتًا. إذا كان تطبيقك يعتمد على تلقّي عمليات البث هذه عند التسجيل لأنّها ثابتة، استخدِم طريقة
get
المناسبة عند الإعداد للحصول على المعلومات. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
-
يشير إلى أنّه تم تغيير تفاصيل إعداد هذا الجهاز. بدءًا من نظام التشغيل Android 10، لن يكون هذا الموقع ثابتًا. إذا كان تطبيقك يعتمد على تلقّي عمليات البث هذه عند التسجيل لأنّها ثابتة، استخدِم طريقة
get
المناسبة عند الإعداد للحصول على المعلومات.
Kotlin
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) ... }
Java
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 المباشر.
Kotlin
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) }
Java
Channel channel; WifiP2pManager manager; @Override public void onCreate(Bundle savedInstanceState) { ... manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); }
يمكنك الآن إنشاء صف BroadcastReceiver
جديد ستستخدمه للاستماع إلى أي تغييرات
في حالة شبكة Wi-Fi للنظام. في الطريقة onReceive()
، أضِف شرطًا لمعالجة كل تغيير في الحالة المذكورة أعلاه.
Kotlin
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 ) } } } }
Java
@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()
.
Kotlin
/** 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) }
Java
/** 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); }
بدء اكتشاف التطبيقات المشابهة
لبدء البحث عن أجهزة مجاورة باستخدام شبكة Wi-Fi P2P، يمكنك الاتصال بالرقم discoverPeers()
. تأخذ هذه الطريقة الوسيطات التالية:
- تمثّل هذه السمة
WifiP2pManager.Channel
الذي تلقّيته مرة أخرى عند إعداد تطبيق mManager الند للند. - يشير ذلك المصطلح إلى تنفيذ
WifiP2pManager.ActionListener
بالطرق التي يستدعيها النظام لاكتشاف المحتوى بنجاح وغير ناجح.
Kotlin
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. } })
Java
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()
عملية الاكتشاف ثم تعود على الفور. يُعلمك النظام إذا بدأت عملية اكتشاف الزملاء بنجاح
من خلال استدعاء الطرق في أداة معالجة الإجراء المقدمة.
ويظل الاكتشاف نشطًا إلى أن يتم بدء الاتصال أو تكوين مجموعة P2P.
استرجاع قائمة التطبيقات المشابهة
اكتب الآن الكود الذي يجلب قائمة الأقران ويعالجها. عليك أولاً تنفيذ واجهة WifiP2pManager.PeerListListener
التي تقدّم معلومات حول التطبيقات المشابهة التي رصدتها اتصالات Wi-Fi المباشرة. تتيح هذه المعلومات أيضًا لتطبيقك تحديد وقت انضمام
الأقران إلى الشبكة أو مغادرتهم لها. يوضح مقتطف الرمز التالي هذه العمليات
المتعلقة بالزملاء:
Kotlin
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 } }
Java
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; } } }
يمكنك الآن تعديل طريقة onReceive()
الخاصة بمستقبِل البث لاستدعاء requestPeers()
عند تلقّي هدف مع الإجراء WIFI_P2P_PEERS_CHANGED_ACTION
. أنت بحاجة إلى
تمرير هذا المستمع إلى المتلقي بطريقة ما. تتمثل إحدى الطرق في إرساله كوسيطة إلى الدالة الإنشائية لاستقبال البث.
Kotlin
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") } ... } }
Java
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()
.
Kotlin
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() } }) }
Java
@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(); } }); }
إذا كان كل جهاز من الأجهزة في مجموعتك يتوافق مع اتصال Wi-Fi المباشر، لن تحتاج إلى طلب كلمة مرور المجموعة صراحةً عند الاتصال. للسماح لجهاز لا يتوافق مع اتصال Wi-Fi المباشر بالانضمام إلى مجموعة، يجب استعادة كلمة المرور هذه من خلال الاتصال بـ requestGroupInfo()
، كما هو موضّح في مقتطف الرمز التالي:
Kotlin
manager.requestGroupInfo(channel) { group -> val groupPassword = group.passphrase }
Java
manager.requestGroupInfo(channel, new GroupInfoListener() { @Override public void onGroupInfoAvailable(WifiP2pGroup group) { String groupPassword = group.getPassphrase(); } });
تجدر الإشارة إلى أنّ عملية WifiP2pManager.ActionListener
التي تم تنفيذها في الإجراء connect()
لا تُعلمك إلا عند نجاح عملية البدء أو تعذُّر إكمالها. لرصد التغييرات في حالة الاتصال، نفِّذ واجهة WifiP2pManager.ConnectionInfoListener
.
وتُعلمك ميزة معاودة الاتصال في "onConnectionInfoAvailable()
" عند تغيير حالة الاتصال. في الحالات التي يتم فيها توصيل أجهزة متعددة بجهاز واحد (مثل لعبة بها ثلاثة لاعبين أو أكثر، أو تطبيق دردشة)، يتم تعيين جهاز واحد على أنه "مالك المجموعة". يمكنك تحديد جهاز معيّن كمالك
لمجموعة الشبكة من خلال اتّباع الخطوات الواردة في قسم
إنشاء مجموعة.
Kotlin
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. } }
Java
@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()
. هذه مكالمة غير متزامنة، لذلك يتم تلقي النتائج من خلال أداة معالجة معلومات الاتصال التي تقدمها كمعلمة.
Kotlin
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) } } } ... }
Java
... } 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 المباشر، عليك اتّباع تسلسل الخطوات نفسه كما في قسم
الاتصال بزميل، باستثناء إنشاء
WifiP2pManager.ActionListener
جديد باستخدام createGroup()
بدلاً من connect()
. تتم معالجة عملية معاودة الاتصال داخل
WifiP2pManager.ActionListener
كما هو موضّح في مقتطف الرمز التالي:
Kotlin
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() } })
Java
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(); } });
ملاحظة: إذا كانت جميع الأجهزة في الشبكة متوافقة مع Wi-Fi
Direct، يمكنك استخدام طريقة connect()
على كل جهاز لأنّ
الطريقة ستنشئ المجموعة وتختار مالك المجموعة تلقائيًا.
بعد إنشاء مجموعة، يمكنك الاتصال بـ
requestGroupInfo()
لاسترداد تفاصيل حول التطبيقات المشابهة على الشبكة، بما في ذلك أسماء الأجهزة وحالات الاتصال.