首页 > 解决方案 > 以推荐方式获取本地IP

问题描述

我是 kotlin 的新手。在我的应用程序中,我想在 wifi 网络中获取手机的 ip 并显示它。

fun runDvr(view: View) {        
        GetMyIP_A();
    }

我的选择:1)

private fun GetMyIP_A() {
        val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        val ipAddress: String = Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
        Log.i("TAG", "IP: $ipAddress")
        }

这可行,但不推荐使用 formatIpAddress。我想改用 InetAddress.getLocalHost().hostAddress

2)

private fun GetMyIP_B() {
   val executor = Executors.newSingleThreadExecutor()
        val handler = Handler(Looper.getMainLooper())
        executor.execute {
            val str = InetAddress.getLocalHost().hostAddress
            Log.i("TAG", "IP: $str")


            handler.post {
                val editText = findViewById<EditText>(R.id.TextBoxA)
                editText.text.clear();
                editText.text.append(str);
                
            }
        }
   }

这也有效,但我想使用协程来创建线程。

3)

 private fun GetMyIP_C() {


     // Start a coroutine
        GlobalScope.launch {
            val str = InetAddress.getLocalHost().hostAddress
           Log.i("TAG", "IP: $str")
        }

    }

这行得通,但我听说不建议使用 GlobalScope

4)

 private fun GetMyIP_D() = runBlocking { // this: CoroutineScope
        launch { // launch a new coroutine in the scope of runBlocking
            
           val str = InetAddress.getLocalHost().hostAddress;
           Log.i("TAG", "IP: $str")
        }
        
        Log.i("TAG",  "Back in GetMyIP_D")
    }

这不起作用(InetAddress.getLocalHost().hostAddress; 在阻塞乐趣中是不允许的)并且它会阻塞我的主线程。如何在不阻塞的情况下午餐协程?使用 InetAddress.getLocalHost().hostAddress 的推荐方法是什么?

标签: androidkotlin

解决方案


推荐阅读