Advertisement
yungKKKK

Untitled

Dec 6th, 2023
1,292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.18 KB | None | 0 0
  1. data class TelephonyProvider(
  2.     val name: String,
  3.     val id: String,
  4. )
  5.  
  6. fun Context.getTelephonyProvider(): TelephonyProvider {
  7.     val telephonyManager = getSystemService(TelephonyManager::class.java)
  8.     val operatorName = telephonyManager.networkOperatorName
  9.     val operatorId = telephonyManager.networkOperator
  10.     return TelephonyProvider(operatorName, operatorId)
  11. }
  12.  
  13. suspend fun Context.getDeviceIpAddress(): String? = withContext(Dispatchers.IO) {
  14.     val connectivityManager = getSystemService(ConnectivityManager::class.java)
  15.     val props = connectivityManager.getLinkProperties(connectivityManager.activeNetwork) as LinkProperties
  16.     props.linkAddresses.firstOrNull { linkAddress ->
  17.         linkAddress.address.hostAddress?.contains('.') ?: false
  18.     }?.address?.hostAddress
  19. }
  20.  
  21. suspend fun getPublicIpAddress(): Deferred<String> =
  22.     coroutineScope {
  23.         async(Dispatchers.IO) {
  24.             var result = ""
  25.             result = try {
  26.                 val url = URL("https://api.ipify.org")
  27.                 val httpsURLConnection = url.openConnection()
  28.                 val iStream = httpsURLConnection.getInputStream()
  29.                 val buff = ByteArray(1024)
  30.                 val read = iStream.read(buff)
  31.                 String(buff, 0, read)
  32.             } catch (e: Exception) {
  33.                 "error : $e"
  34.             }
  35.             return@async result
  36.         }
  37.     }
  38.  
  39. data class Wifi(
  40.     val name: String,
  41.     val id: String,
  42. )
  43.  
  44. fun Context.getWifiInfo(): Wifi {
  45.     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  46.         val connectivityManager = getSystemService(ConnectivityManager::class.java)
  47.  
  48.         val wifiInfo = connectivityManager
  49.             .getNetworkCapabilities(connectivityManager.activeNetwork)
  50.             ?.transportInfo as WifiInfo
  51.         return Wifi(
  52.             name = wifiInfo.ssid,
  53.             id = wifiInfo.networkId.toString(),
  54.         )
  55.     } else {
  56.         val wifiManager =
  57.             getSystemService(WifiManager::class.java)
  58.         val wifiInfo = wifiManager!!.connectionInfo
  59.         return Wifi(
  60.             name = wifiInfo.ssid,
  61.             id = wifiInfo.networkId.toString(),
  62.         )
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement