下面採用Kotlin實現方式,java 實現方法對照着修改就可以使用,廢話不多說直接上代碼:
/** * 獲取本機IP地址 */ fun getIpAddressString(): String { try { var enNetI: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces() while (enNetI.hasMoreElements()) { var netI = enNetI.nextElement() var enumIpAddr: Enumeration<InetAddress> = netI.inetAddresses while (enumIpAddr.hasMoreElements()) { var inetAddress = enumIpAddr.nextElement(); if (inetAddress is Inet4Address && !inetAddress.isLoopbackAddress) { return inetAddress.hostAddress } } } } catch (e: Exception) { e.toString() } return "0.0.0.0"; } /** * 獲得SD卡總大小 * * @return */ public fun getSDTotalSize(context: Context): String? { val path: File = Environment.getExternalStorageDirectory() val stat = StatFs(path.getPath()) val blockSize: Long = stat.blockSizeLong val totalBlocks: Long = stat.blockCountLong return formatFileSize(context, blockSize * totalBlocks) } /** * 獲得sd卡剩餘容量,即可用大小 * * @return */ public fun getSDAvailableSize(context: Context): String? { val path: File = Environment.getExternalStorageDirectory() val stat = StatFs(path.getPath()) val blockSize: Long = stat.blockSizeLong val availableBlocks: Long = stat.availableBlocksLong return formatFileSize(context, blockSize * availableBlocks) } /** * 獲取系統內存大小 * @return */ public fun getSysteTotalMemorySize(context: Context): String? { //獲得ActivityManager服務的對象 val mActivityManager: ActivityManager? = (context as Activity).getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? //獲得MemoryInfo對象 val memoryInfo: ActivityManager.MemoryInfo = ActivityManager.MemoryInfo() //獲得系統可用內存,保存在MemoryInfo對象上 mActivityManager?.getMemoryInfo(memoryInfo) val memSize: Long = memoryInfo.totalMem //字符類型轉換 return formatFileSize(context,memSize) } /** * 獲取系統可用的內存大小 * @return */ public fun getSystemAvaialbeMemorySize(context: Context): String? { //獲得ActivityManager服務的對象 val mActivityManager: ActivityManager? = (context as Activity).getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? //獲得MemoryInfo對象 val memoryInfo: ActivityManager.MemoryInfo = ActivityManager.MemoryInfo() //獲得系統可用內存,保存在MemoryInfo對象上 mActivityManager?.getMemoryInfo(memoryInfo) val memSize: Long = memoryInfo.availMem //字符類型轉換 return formatFileSize(context,memSize) }