diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt index 9b764c0d..71837467 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt @@ -9,15 +9,15 @@ import org.json.JSONObject import java.net.URI import java.net.URLConnection -val Context.v2RayApplication: AngApplication - get() = applicationContext as AngApplication +val Context.v2RayApplication: AngApplication? + get() = applicationContext as? AngApplication fun Context.toast(message: Int) { - ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() } + ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Context.toast(message: CharSequence) { - ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() } + ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).show() } fun JSONObject.putOpt(pair: Pair) { @@ -34,26 +34,14 @@ const val DIVISOR = 1024.0 fun Long.toSpeedString(): String = this.toTrafficString() + "/s" fun Long.toTrafficString(): String { - if (this < THRESHOLD) { - return "$this B" + val units = arrayOf("B", "KB", "MB", "GB", "TB", "PB") + var size = this.toDouble() + var unitIndex = 0 + while (size >= THRESHOLD && unitIndex < units.size - 1) { + size /= DIVISOR + unitIndex++ } - val kb = this / DIVISOR - if (kb < THRESHOLD) { - return "${String.format("%.1f KB", kb)}" - } - val mb = kb / DIVISOR - if (mb < THRESHOLD) { - return "${String.format("%.1f MB", mb)}" - } - val gb = mb / DIVISOR - if (gb < THRESHOLD) { - return "${String.format("%.1f GB", gb)}" - } - val tb = gb / DIVISOR - if (tb < THRESHOLD) { - return "${String.format("%.1f TB", tb)}" - } - return String.format("%.1f PB", tb / DIVISOR) + return String.format("%.1f %s", size, units[unitIndex]) } val URLConnection.responseLength: Long