Bài học đầu tiên trong lớp học này, Sử dụng chức năng khám phá dịch vụ mạng, đã hướng dẫn bạn cách khám phá các dịch vụ được kết nối với mạng cục bộ. Tuy nhiên, việc sử dụng tính năng Khám phá dịch vụ Wi-Fi Direct (P2P) cho phép bạn khám phá trực tiếp các dịch vụ của thiết bị ở gần mà không cần kết nối với mạng. Bạn cũng có thể quảng cáo các dịch vụ đang chạy trên thiết bị của mình. Các chức năng này giúp bạn giao tiếp giữa các ứng dụng, ngay cả khi không có mạng cục bộ hoặc điểm phát sóng.
Mặc dù mục đích của nhóm API này tương tự như API Khám phá dịch vụ mạng được trình bày trong một bài học trước, nhưng việc triển khai chúng trong mã lại rất khác nhau. Bài học này sẽ hướng dẫn bạn cách khám phá các dịch vụ có trên các thiết bị khác bằng Wi-Fi Direct. Bài học này giả định rằng bạn đã quen thuộc với API Wi-Fi Direct.
Thiết lập tệp kê khai
Để sử dụng Wi-Fi P2P, hãy thêm các quyền CHANGE_WIFI_STATE
, ACCESS_WIFI_STATE
, ACCESS_FINE_LOCATION
và INTERNET
vào tệp kê khai của bạn. Nếu ứng dụng của bạn nhắm đến Android 13 (API cấp 33) trở lên, hãy thêm quyền NEARBY_WIFI_DEVICES
vào tệp kê khai. Mặc dù Wi-Fi Direct không yêu cầu kết nối Internet, nhưng nó sử dụng các socket Java tiêu chuẩn và việc sử dụng các socket này trong Android yêu cầu các quyền được yêu cầu.
<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" /> ...
Ngoài các quyền nêu trên, các API sau đây cũng yêu cầu bạn bật Chế độ vị trí:
Thêm dịch vụ tại địa phương
Nếu đang cung cấp dịch vụ tại địa phương, bạn cần đăng ký dịch vụ đó để phát hiện dịch vụ. Sau khi dịch vụ tại địa phương của bạn được đăng ký, khung này sẽ tự động phản hồi các yêu cầu khám phá dịch vụ từ các thiết bị ngang hàng.
Cách tạo dịch vụ tại địa phương:
- Tạo một đối tượng
WifiP2pServiceInfo
. - Điền thông tin về dịch vụ của bạn vào mẫu này.
- Gọi
addLocalService()
để đăng ký dịch vụ cục bộ cho tính năng khám phá dịch vụ.
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 } }); }
Khám phá các dịch vụ lân cận
Android sử dụng các phương thức gọi lại để thông báo cho ứng dụng của bạn về các dịch vụ hiện có, vì vậy, việc đầu tiên bạn cần làm là thiết lập các phương thức đó. Tạo một WifiP2pManager.DnsSdTxtRecordListener
để theo dõi các bản ghi đến. Các thiết bị khác có thể phát bản ghi này (không bắt buộc). Khi một yêu cầu đến, hãy sao chép địa chỉ thiết bị và mọi thông tin liên quan khác mà bạn muốn vào một cấu trúc dữ liệu bên ngoài phương thức hiện tại để bạn có thể truy cập vào thông tin đó sau này. Ví dụ sau đây giả định rằng bản ghi chứa một trường "buddyname", được điền sẵn danh tính của người dùng.
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")); } }; }
Để lấy thông tin dịch vụ, hãy tạo một WifiP2pManager.DnsSdServiceResponseListener
. Thao tác này nhận được nội dung mô tả thực tế và thông tin kết nối. Đoạn mã trước đó đã triển khai một đối tượng Map
để ghép nối địa chỉ thiết bị với tên bạn bè. Trình nghe phản hồi dịch vụ sử dụng thông tin này để liên kết bản ghi DNS với thông tin dịch vụ tương ứng. Sau khi triển khai cả hai trình nghe, hãy thêm chúng vào WifiP2pManager
bằng phương thức 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); ... }
Bây giờ, hãy tạo một yêu cầu dịch vụ và gọi addServiceRequest()
.
Phương thức này cũng lấy một trình nghe để báo cáo thành công hoặc không thành công.
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 } });
Cuối cùng, hãy gọi đến 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(...) ... } });
Nếu mọi thứ đều ổn, xin chúc mừng, bạn đã hoàn tất! Nếu gặp vấn đề, hãy nhớ rằng các lệnh gọi không đồng bộ mà bạn đã thực hiện sẽ lấy WifiP2pManager.ActionListener
làm đối số và đối số này cung cấp cho bạn các lệnh gọi lại cho biết trạng thái thành công hoặc không thành công. Để chẩn đoán vấn đề, hãy đặt mã gỡ lỗi trong onFailure()
. Mã lỗi do phương thức cung cấp cho biết vấn đề. Dưới đây là các giá trị lỗi có thể xảy ra và ý nghĩa của từng giá trị
-
P2P_UNSUPPORTED
- Wi-Fi Direct không được hỗ trợ trên thiết bị chạy ứng dụng.
-
BUSY
- Hệ thống đang quá bận để xử lý yêu cầu.
-
ERROR
- Thao tác không thành công do lỗi nội bộ.