android - 以推荐方式获取本地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 的推荐方法是什么?
解决方案
推荐阅读
- reactjs - 是否有可能使酶与 RN + hooks 一起工作?
- reactjs - 如何在 redux react 中调试?
- python - 像素旋转图像
- meteor - Meteor js如何在服务器端上传图片?
- google-cloud-platform - GCP Cloud Run:一次性工作和“配置”
没有任何现成的修订版 - javascript - 在javascript中将数组中的项目移动到顶部
- arrays - 如何转换数组中的可观察数组并返回该新数组?
- flutter - 颤振亮度的 Amoled 黑色亮度设置
- node.js - 带有 Webpack、Typescript 和 ES6 的 elastic-apm-node 不起作用?
- python - 了解 lambda 函数重新格式化以进行闭包