在 Android API 级别 28 及更高级别连接时,如何获取 Wifi AP 详细信息,如 SSID、Band 等? [英] How to get Wifi AP details like SSID, Band, etc when connected in Android API level 28 and above?

查看:61
本文介绍了在 Android API 级别 28 及更高级别连接时,如何获取 Wifi AP 详细信息,如 SSID、Band 等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 Wifi AP 详细信息.我正在使用以下代码

 private val TAG = "[MainActivity]";覆盖 fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val 接收器 = 对象:BroadcastReceiver() {覆盖乐趣 onReceive(上下文:上下文?,意图:意图?){如果(WifiManager.NETWORK_STATE_CHANGED_ACTION ==意图?.action){val networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)if(ConnectivityManager.TYPE_WIFI == networkInfo.type){val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) 作为 WifiManagerval 信息 = wifiManager.connectionInfoLog.d(TAG, "info = $info")}}}}val intentFilter = IntentFilter()intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)applicationContext.registerReceiver(接收器,intentFilter)}

NetworkInfo 和 ConnectivityManager.TYPE_WIFI 显示已弃用.我也将 SSID 设为 null.

info = SSID: , BSSID: 02:00:00:00:00:00, MAC: 02:00:00:00:00:00, 请求方状态:COMPLETED

我使用的权限:

 

完成上述任务的最佳方法是什么?

解决方案

@Shlomi 答案的补充,

这是在运行时从用户那里获取权限的示例

<块引用>

执行操作前先检查

if (!checkPermissions()) {//应用没有权限,请求权限.请求权限()} 别的 {//应用有权限//在这里执行你的操作......}

<块引用>

检查和询问权限的代码

<块引用>

科特林

/*** 返回所需权限的当前状态.*/私人乐趣检查权限():布尔{val permissionState = ActivityCompat.checkSelfPermission(需要上下文(),Manifest.permission.ACCESS_FINE_LOCATION)返回权限状态 == PackageManager.PERMISSION_GRANTED}私人乐趣 requestPermissions() {val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(需要活动(),Manifest.permission.ACCESS_FINE_LOCATION)//为用户提供额外的理由.如果用户拒绝了,就会发生这种情况//先前请求,但没有检查不再询问";复选框.如果(应该提供基本原理){日志.i(标签,显示许可理由以提供额外的上下文.")Snackbar.make(binding.wifiConnectionFragment,核心功能需要位置许可",Snackbar.LENGTH_INDEFINITE).setAction("OK") {//请求权限ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),REQUEST_PERMISSIONS_REQUEST_CODE)}.展示()} 别的 {Log.i(TAG,请求许可")//请求权限.如果设备策略,这可能会自动回答//在给定状态下设置权限或用户拒绝权限//之前并检查过不再询问".ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),REQUEST_PERMISSIONS_REQUEST_CODE)}}覆盖乐趣 onRequestPermissionsResult(请求代码:Int,权限:数组<输出字符串>,授予结果:IntArray){super.onRequestPermissionsResult(requestCode, permissions, grantResults)如果(请求代码 == REQUEST_PERMISSIONS_REQUEST_CODE){如果(grantResults.isEmpty()){} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//许可授予//执行你的操作} 别的 {//没有权限.//通过 SnackBar 通知用户他们拒绝了//app,这使得Activity无用.在真正的应用程序中,核心权限将//通常最好在欢迎屏幕流程中请求.//此外,重要的是要记住一个权限可能已经被//未经用户许可就被拒绝(设备策略或从不询问"//再次"提示).因此,通常实现用户界面可供性//当权限被拒绝时.否则,您的应用可能看起来对//具有所需权限的触摸或交互.Snackbar.make(binding.wifiConnectionFragment,权限被拒绝,但核心功能需要.",Snackbar.LENGTH_INDEFINITE).setAction(设置",View.OnClickListener {//构建显示应用设置屏幕的意图.val 意图 = 意图()intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGSval uri = Uri.fromParts(包",BuildConfig.APPLICATION_ID,空)意图.数据 = uriintent.flags = Intent.FLAG_ACTIVITY_NEW_TASK开始活动(意图)}).展示()}}}

I am trying to get Wifi AP details. I am using the following code

    private val TAG = "[MainActivity]"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

         val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if(WifiManager.NETWORK_STATE_CHANGED_ACTION == intent?.action){
                    val networkInfo = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)
                    if(ConnectivityManager.TYPE_WIFI == networkInfo.type){
                        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                        val info = wifiManager.connectionInfo
                        Log.d(TAG, "info = $info")
                    }
                }
            }
        }

        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        applicationContext.registerReceiver(receiver, intentFilter)
    }

NetworkInfo and ConnectivityManager.TYPE_WIFI are shown to be deprecated. Also I am getting SSID as null.

info = SSID: , BSSID: 02:00:00:00:00:00, MAC: 02:00:00:00:00:00, Supplicant state: COMPLETED

Permissions that I used:

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

What is the best way to achieve above task?

解决方案

An addition to @Shlomi's answer,

Here is the sample of getting permissions from user at runtime

Perform a check before performing operation

if (!checkPermissions()) {
    // App does not have permissions, ask for permissions.
    requestPermissions()
} else {
    // App has permissions
    // Perform your operations here......
}

Code to check and ask permissions

Kotlin

/**
 * Return the current state of the permissions needed.
 */
private fun checkPermissions(): Boolean {
   
    val permissionState = ActivityCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.ACCESS_FINE_LOCATION
    )
    return permissionState == PackageManager.PERMISSION_GRANTED
}

private fun requestPermissions() {
    val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(
            requireActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION
    )

    // Provide an additional rationale to the user. This would happen if the user denied the
    // request previously, but didn't check the "Don't ask again" checkbox.
    if (shouldProvideRationale) {
        Log.i(
                TAG,
                "Displaying permission rationale to provide additional context."
        )
        Snackbar.make(
                binding.wifiConnectionFragment,
                "Location permission is needed for core functionality",
                Snackbar.LENGTH_INDEFINITE
        )
            .setAction("OK") { // Request permission
                ActivityCompat.requestPermissions(
                        requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                        REQUEST_PERMISSIONS_REQUEST_CODE
                )
            }
            .show()
    } else {
        Log.i(TAG, "Requesting permission")
        // Request permission. It's possible this can be auto answered if device policy
        // sets the permission in a given state or the user denied the permission
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(
                requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_PERMISSIONS_REQUEST_CODE
        )
    }
}

override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.isEmpty()) {

        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            // Perform your operations
        } else {
            // Permission denied.

            // Notify the user via a SnackBar that they have rejected a core permission for the
            // app, which makes the Activity useless. In a real app, core permissions would
            // typically be best requested during a welcome-screen flow.

            // Additionally, it is important to remember that a permission might have been
            // rejected without asking the user for permission (device policy or "Never ask
            // again" prompts). Therefore, a user interface affordance is typically implemented
            // when permissions are denied. Otherwise, your app could appear unresponsive to
            // touches or interactions which have required permissions.
            Snackbar.make(
                    binding.wifiConnectionFragment,
                    "Permission was denied, but is needed for core functionality.",
                    Snackbar.LENGTH_INDEFINITE
            )
                .setAction(
                        "Settings",
                        View.OnClickListener { // Build intent that displays the App settings screen.
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            val uri = Uri.fromParts(
                                    "package",
                                    BuildConfig.APPLICATION_ID, null
                            )
                            intent.data = uri
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            startActivity(intent)
                        })
                .show()
        }
    }
}

这篇关于在 Android API 级别 28 及更高级别连接时,如何获取 Wifi AP 详细信息,如 SSID、Band 等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆