Kablosuz Doğrudan Bağlantı (Eşler arası veya P2P olarak da bilinir), uygulamanızın yakındakileri hızlıca bulup etkileşime geçmesini sağlar kapsama alanı içindedir.
Wi-Fi Direct (P2P) API'leri, uygulamaların yakındaki cihazlara Bir ağa veya hotspot'a bağlanmanız gerekiyorsa. Uygulamanız güvenli, yakın mesafedeki bir ağın parçası olarak tasarlandıysa, Doğrudan, geleneksel kablosuz ağdan daha uygun bir seçenektir. sosyal bağlantı kurmanıza neden olabilir:
- Kablosuz Doğrudan bağlantı, WPA2 şifrelemeyi destekler. (Bazı geçici ağlar yalnızca WEP şifrelemeyi destekler.)
- Cihazlar, sağladıkları hizmetleri yayınlayabilir. Bu sayede diğer cihazlar, uygun eşleri daha kolay keşfedebilir.
- Wi-Fi Direct, ağ için grup sahibinin hangi cihaz olması gerektiğini belirlerken her cihazın güç yönetimini, kullanıcı arayüzünü ve hizmet özelliklerini inceler ve bu bilgileri kullanarak sunucu sorumluluklarını en etkili şekilde yerine getirebilecek cihazı seçer.
- Android, Wi-Fi anlık modunu desteklemez.
Bu derste, kablosuz P2P'yi kullanarak yakındaki cihazları nasıl bulup bunlara bağlanacağınız gösterilmektedir.
Uygulama izinlerini ayarlama
Wi-Fi Direct'i kullanmak için manifest dosyanıza ACCESS_FINE_LOCATION
, CHANGE_WIFI_STATE
, ACCESS_WIFI_STATE
ve INTERNET
izinlerini ekleyin.
Uygulamanız Android 13'ü (API düzeyi 33) veya sonraki sürümleri hedefliyorsa manifest dosyanıza NEARBY_WIFI_DEVICES
izini de ekleyin. Wi-Fi Direct için internet bağlantısı gerekmez ancak standart Java soketlerini kullanır. Bu da INTERNET
izinini gerektirir. Bu nedenle, kablosuz doğrudan bağlantıyı kullanmak için aşağıdaki izinlere ihtiyacınız vardır:
<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"/> ...
Önceki izinlerin yanı sıra aşağıdaki API'ler de Konum Modu'nun etkinleştirilmesini gerektirir:
Yayın alıcı ve eşler arası yönetici ayarlama
Wi-Fi Direct'i kullanmak için, cihazınıza bunu bildiren yayın amaçlarını dinlemeniz gerekir
uygulama üzerinden
erişim sağlar. Uygulamanızda bir IntentFilter
nesnesi oluşturun ve aşağıdakileri dinleyecek şekilde ayarlayın:
WIFI_P2P_STATE_CHANGED_ACTION
- Kablosuz Doğrudan Bağlantının etkin olup olmadığını gösterir
WIFI_P2P_PEERS_CHANGED_ACTION
- Kullanılabilir benzerler listesinin değiştiğini belirtir.
WIFI_P2P_CONNECTION_CHANGED_ACTION
- .
Kablosuz Doğrudan Bağlantının durumunun değiştiğini belirtir. Başlangıç
Android 10 için bu sabit değildir. Uygulamanız, kalıcı oldukları için bu yayınları kayıt sırasında alıyorduysa bilgileri almak için başlatma sırasında uygun
get
yöntemini kullanın. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
- .
Bu cihazın yapılandırma ayrıntılarının değiştiğini belirtir. Android 10'dan itibaren bu ayar kalıcı değildir. Uygulamanız bu anahtar kelimeleri
sabit olabildiğinden kayıt sırasında yayınlar. Bunun için uygun
get
yöntemini kullanmanızı öneririz.
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()
yönteminin sonunda, WifiP2pManager
öğesinin bir örneğini alın ve initialize()
yöntemini çağırın
yöntemidir. Bu yöntem, uygulamanızı Wi-Fi Direct çerçevesine bağlamak için daha sonra kullanacağınız bir WifiP2pManager.Channel
nesnesi döndürür.
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); }
Şimdi, sistemin kablosuz bağlantı durumundaki değişiklikleri dinlemek için kullanacağınız yeni bir BroadcastReceiver
sınıfı oluşturun. onReceive()
içinde
yöntemini kullanıyorsanız yukarıda listelenen her durum değişikliğini işlemek için bir koşul ekleyin.
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)); } }
Son olarak, ana etkinliğiniz etkinken intent filtresini ve yayın alıcısını kaydedecek ve etkinlik duraklatıldığında bunların kaydını iptal edecek kod ekleyin.
Bunu yapmanın en iyi yolu onResume()
ve onPause()
yöntemleridir.
/** 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); }
Eş bulma işlemini başlatma
Kablosuz P2P ile yakındaki cihazları aramaya başlamak için discoverPeers()
numaralı telefonu arayın. Bu yöntem aşağıdaki bağımsız değişkenleri alır:
- Eşler arası mManager'ı başlattığınızda size döndürülen
WifiP2pManager.Channel
- Yöntemlerle
WifiP2pManager.ActionListener
uygulaması ve sistemin başarılı ve başarısız keşif için çağrıda bulunmasını sağlar.
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. } });
Bunun yalnızca benzerler keşfini başlattığını unutmayın. discoverPeers()
yöntemi, keşif işlemini başlatır ve hemen döndürür. Benzer keşif süreci devam ediyorsa sistem sizi bilgilendirir
sağlanan işlem işleyicide yöntemlerin çağrılmasıyla başarıyla başlatılır.
Ayrıca, bir bağlantı başlatılana veya P2P grubu oluşturulana kadar keşif etkin kalır.
Eşlerin listesini getirme
Şimdi eşlerin listesini getiren ve işleyen kodu yazın. Ad
WifiP2pManager.PeerListListener
öğesini uygula
arayüzü üzerinden, Kablosuz Doğrudan Bağlantının sahip olduğu benzerlerle
algılandı. Bu bilgiler, uygulamanızın eşler ne zaman ağa katılacağını veya ağdan ayrılacağını belirlemesine de olanak tanır. Aşağıdaki kod snippet'inde, eşlerle ilgili bu işlemler gösterilmektedir:
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; } } }
Şimdi yayın alıcınızın onReceive()
ayarını değiştirin
WIFI_P2P_PEERS_CHANGED_ACTION
işlemine sahip bir intent alındığında requestPeers()
yöntemini çağırmak için kullanılır. Bu dinleyiciyi alıcıya bir şekilde iletmeniz gerekir. Bunun bir yolu, yayın alıcısının kurucusuna bir bağımsız değişken olarak göndermektir.
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"); }... }
Artık WIFI_P2P_PEERS_CHANGED_ACTION
intent işlemine sahip bir intent, güncellenmiş bir eş listesi isteği tetikler.
Eşle bağlantı kurma
Bir eşe bağlanmak için yeni bir WifiP2pConfig
nesnesi oluşturun ve bağlanmak istediğiniz cihazı temsil eden WifiP2pDevice
nesnesinden bu nesneye veri kopyalayın. Ardından connect()
numaralı telefonu arayın
yöntemidir.
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(); } }); }
Grubunuzdaki cihazların her biri kablosuz doğrudan bağlantıyı destekliyorsa bağlanırken grubun şifresini açıkça sormanız gerekmez. Ancak, Wi-Fi Direct'i desteklemeyen bir cihazın gruba katılmasına izin vermek için aşağıdaki kod snippet'inde gösterildiği gibi requestGroupInfo()
işlevini çağırarak bu şifreyi almanız gerekir:
manager.requestGroupInfo(channel) { group -> val groupPassword = group.passphrase }
manager.requestGroupInfo(channel, new GroupInfoListener() { @Override public void onGroupInfoAvailable(WifiP2pGroup group) { String groupPassword = group.getPassphrase(); } });
connect()
yönteminde uygulanan WifiP2pManager.ActionListener
'nin yalnızca başlatma başarılı veya başarısız olduğunda sizi bilgilendirdiğini unutmayın. Bağlantı durumundaki değişiklikleri dinlemek için WifiP2pManager.ConnectionInfoListener
arayüzünü uygulayın.
onConnectionInfoAvailable()
geri çağırma işlevi, bağlantının durumu değiştiğinde sizi bilgilendirir. Birden fazla cihazın bağlanacağı durumlarda
Tek bir cihaz (ör. üç veya daha fazla oyuncusu olan bir oyun ya da sohbet uygulaması), bir cihaz
öğesi "grup sahibi" olarak belirlenir. Belirli bir cihazı
ağ'ın grup sahibini silmek için
Grup oluştur bölümünü inceleyin.
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. } }
Şimdi yayın alıcısının onReceive()
yöntemine dönün ve bölümü değiştirin
WIFI_P2P_CONNECTION_CHANGED_ACTION
niyetini dinleyen bir uygulamadır.
Bu intent alındığında requestConnectionInfo()
numaralı telefonu arayın. Bu asynkron bir çağrı olduğundan sonuçlar, parametre olarak sağladığınız bağlantı bilgileri dinleyicisi tarafından alınır.
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); } ...
Grup oluşturma
Uygulamanızı çalıştıran cihazın, eski cihazları (yani Wi-Fi Direct'i desteklemeyen cihazları) içeren bir ağ için grup sahibi olmasını istiyorsanız Eşleşimci cihaza bağlanma bölümündeki adımları uygularsınız. Bununla birlikte, connect()
yerine createGroup()
kullanarak yeni bir WifiP2pManager.ActionListener
oluşturursunuz. WifiP2pManager.ActionListener
içindeki geri çağırma işlevi, aşağıdaki kod snippet'inde gösterildiği gibi aynıdır:
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(); } });
Not: Bir ağdaki tüm cihazlar kablosuz doğrudan bağlantıyı destekliyorsa her cihazda connect()
yöntemini kullanabilirsiniz. Bu yöntem, grubu oluşturur ve otomatik olarak bir grup sahibi seçer.
Grup oluşturduktan sonra, ağdaki eşler hakkında cihaz adları ve bağlantı durumları da dahil olmak üzere ayrıntıları almak için requestGroupInfo()
'ü çağırabilirsiniz.