Bài học đầu tiên trong lớp học này, Sử dụng tính 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. Những 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ù bộ API này có mục đích tương tự như API Khám phá dịch vụ mạng được nêu trong bài học trước, nhưng việc triển khai các API này trong mã lại rất khác. Bài học này sẽ hướng dẫn bạn cách khám phá các dịch vụ có sẵn 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. 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 công nghệ này sử dụng các cổng Java tiêu chuẩn và việc sử dụng các cổng 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 cũng yêu cầu bật Chế độ vị trí:
Thêm dịch vụ tại địa phương
Nếu đang cung cấp dịch vụ cục bộ, bạn cần đăng ký dịch vụ đó để khám phá dịch vụ. Sau khi dịch vụ cục bộ của bạn được đăng ký, khung sẽ tự động phản hồi các yêu cầu khám phá dịch vụ từ các ứng dụng 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ụ có sẵn, vì vậy, việc đầu tiên cần làm là thiết lập các phương thức đó. Tạo WifiP2pManager.DnsSdTxtRecordListener để theo dõi các bản ghi đến. Bản ghi này có thể được phát sóng bởi các thiết bị khác. Khi có một thiết bị, 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 để có thể truy cập sau này. Ví dụ sau đây giả định rằng bản ghi chứa trường "buddyname" (tên bạn bè), được điền thông tin nhận dạng 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. Thành phần này nhận thông tin mô tả và thông tin kết nối thực tế. Đ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 của người bạn. 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 sử dụng một trình nghe để báo cáo thành công hay khô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 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 việc suôn sẻ, xin chúc mừng, bạn đã hoàn tất! Nếu bạn gặp sự cố, 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ều này cung cấp cho bạn các lệnh gọi lại cho biết thành công hay thất bại. Để chẩn đoán
vấn đề, hãy đặt mã gỡ lỗi vào onFailure(). Mã lỗi do phương thức cung cấp gợi ý về vấn đề. Dưới đây là các giá trị lỗi có thể xảy ra
và ý nghĩa của các 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 quá bận nên không thể xử lý yêu cầu.
-
ERROR - Không thực hiện được thao tác này do lỗi nội bộ.