您好,登錄后才能下訂單哦!
這篇文章主要介紹“Android掃描WIFI權限功能怎么實現”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Android掃描WIFI權限功能怎么實現”文章能幫助大家解決問題。
根據官方文檔描述,掃描WIFI需要申請相關權限,如下:
Android 13以上
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!--在Android13以上,當usesPermissionFlags設置為neverForLocation時,無需再申請ACCESS_FINE_LOCATION權限--> <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" /> </manifest>
Android 13以下
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> </manifest>
需要注意,在實際測試中,Android 13以上的設備仍然需要申請android.permission.ACCESS_FINE_LOCATION
才能掃描到WIFI,測試設備為小米13。
通過注冊廣播監聽WIFI掃描是否完成,代碼如下:
class WIFIExampleActivity : AppCompatActivity() { private val scanResultReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false) == true) { // 掃描完成 } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 注冊廣播 registerReceiver(scanResultReceiver, IntentFilter().apply { addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) }) } override fun onDestroy() { super.onDestroy() // 移除廣播 unregisterReceiver(scanResultReceiver) } }
通過WifiManager掃描WIFI,并獲取掃描結果,代碼如下:
// 列表適配器 class WIFIAdapter : RecyclerView.Adapter<WIFIAdapter.WIFIViewHolder>() { private val wifiData = ArrayList<WIFIEntity>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WIFIViewHolder { return WIFIViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_wifi_item, parent, false)) } override fun onBindViewHolder(holder: WIFIViewHolder, position: Int) { wifiData[position].run { holder.tvWifiName.text = wifiSSID holder.tvWifiSSID.text = wifiBSSID holder.ivWifiStrength.setImageResource(getStrengthIcon(wifiStrength)) holder.ivNeedPassword.setImageResource(if (needPassword) R.drawable.icon_lock else R.drawable.icon_unlock) } } override fun getItemCount(): Int { return wifiData.size } fun setNewData(wifiData: ArrayList<WIFIEntity>?) { val lastItemCount = itemCount if (lastItemCount != 0) { this.wifiData.clear() notifyItemRangeRemoved(0, lastItemCount) } wifiData?.let { this.wifiData.addAll(it) } notifyItemChanged(0, itemCount) } private fun getStrengthIcon(wifiStrength: Int): Int { return when (wifiStrength) { 0 -> R.drawable.wifi_strength_0 1 -> R.drawable.wifi_strength_1 2 -> R.drawable.wifi_strength_2 else -> R.drawable.wifi_strength_3 } } interface ItemClickListener { fun onItemClick(wifiInfo: WIFIEntity) } class WIFIViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val tvWifiName: AppCompatTextView = itemView.findViewById(R.id.tv_wifi_name) val tvWifiSSID: AppCompatTextView = itemView.findViewById(R.id.tv_wifi_ssid) val ivNeedPassword: AppCompatImageView = itemView.findViewById(R.id.iv_need_password) val ivWifiStrength: AppCompatImageView = itemView.findViewById(R.id.iv_wifi_strength) } } class WIFIExampleActivity : AppCompatActivity() { private lateinit var binding: LayoutWifiExampleActivityBinding private val wifiAdapter = WIFIAdapter() private var wifiManager: WifiManager? = null private var requestPermissionName: String = Manifest.permission.ACCESS_FINE_LOCATION private val requestSinglePermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted: Boolean -> if (granted) { // 申請定位權限通過,掃描WIFI if (wifiManager?.isWifiEnabled == true) { wifiManager?.startScan() } } else { //未同意授權 if (!shouldShowRequestPermissionRationale(requestPermissionName)) { //用戶拒絕權限并且系統不再彈出請求權限的彈窗 //這時需要我們自己處理,比如自定義彈窗告知用戶為何必須要申請這個權限 } } } private val scanResultReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false) == true) { val wifiData = ArrayList<WIFIEntity>() wifiManager?.scanResults?.forEach { val ssid = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { it.wifiSsid.toString() } else { it.SSID } val bssid = it.BSSID // 獲取WIFI加密類型 val capabilities = it.capabilities // 獲取WIFI信號強度 val level = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { wifiManager?.calculateSignalLevel(it.level) ?: 0 } else { WifiManager.calculateSignalLevel(it.level, 4) } wifiData.add(WIFIEntity(ssid, bssid, capabilities.contains("wpa", true) || capabilities.contains("web", true), capabilities, level)) } // 根據信號強度降序排列 wifiData.sortByDescending { it.wifiStrength } wifiAdapter.setNewData(wifiData) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.layout_wifi_example_activity) wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager binding.includeTitle.tvTitle.text = "WIFI Example" binding.btnStartScan.setOnClickListener { // 檢測定位權限 if (ActivityCompat.checkSelfPermission(this, requestPermissionName) == PackageManager.PERMISSION_GRANTED) { if (wifiManager?.isWifiEnabled == true) { wifiManager?.startScan() } } else { requestSinglePermissionLauncher.launch(requestPermissionName) } } binding.rvWifiInfo.adapter = wifiAdapter registerReceiver(scanResultReceiver, IntentFilter().apply { addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) }) } override fun onDestroy() { super.onDestroy() unregisterReceiver(scanResultReceiver) } }
關于“Android掃描WIFI權限功能怎么實現”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。