fun getFlowRanking(): ArrayList<FlowRankingData> { var installedPackages = context.packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES or PackageManager.GET_PERMISSIONS) var listInfo = ArrayList<FlowRankingData>() for (packagesInt in installedPackages) { val permissionsArray = packagesInt.requestedPermissions if (permissionsArray != null && permissionsArray.size > 0) { for (array in permissionsArray) { if (array.equals("android.permission.INTERNET")) { val loadLabel = packagesInt.applicationInfo.loadLabel(context.packageManager) .toString() val uidRxBytes = TrafficStats.getUidRxBytes(packagesInt.applicationInfo.uid) if (!(uidRxBytes != 0L && !(TrafficStats.getUidRxBytes(packagesInt.applicationInfo.uid) == -1L && TrafficStats.getUidTxBytes( packagesInt.applicationInfo.uid ) == -1L)) ) { val uidData = getUidData(packagesInt.applicationInfo.uid) if (uidData != null) { val textReceived = TraRankingData().textReceived val textSent = TraRankingData().textSent if (textReceived != null && textSent != null) { listInfo.add( FlowRankingData( loadLabel, bytegetMb(textReceived), bytegetMb(textSent) ) ) }else{ listInfo.add( FlowRankingData( loadLabel, bytegetMb(0), bytegetMb(0) ) ) } } } } } } } return listInfo } fun getUidData(localUid: Int): TraRankingData? { val dir = File("/proc/uid_stat/") val children = dir.list() val stringBuffer = StringBuffer() var traRankingData: TraRankingData? = TraRankingData() if (children != null) { for (i in children.indices) { stringBuffer.append(children[i]) stringBuffer.append(" ") } if (!Arrays.asList(*children).contains(localUid.toString())) { return null } } val uidFile = File("/proc/uid_stat/" + localUid.toString()) val uidActualFileReceived = File(uidFile, "tcp_rcv") val uidActualFileSent = File(uidFile, "tcp_snd") var textReceived: String? = "0" var textSent: String? = "0" try { val brReceived = BufferedReader(FileReader(uidActualFileReceived)) val brSent = BufferedReader(FileReader(uidActualFileSent)) var receivedLine: String? var sentLine: String? if (brReceived.readLine().also { receivedLine = it } != null) { textReceived = receivedLine } if (brSent.readLine().also { sentLine = it } != null) { textSent = sentLine } } catch (e: IOException) { e.printStackTrace() } if (traRankingData != null) { traRankingData.textReceived = textReceived?.toLong() traRankingData.textSent = textSent?.toLong() } else { var traRankingData = TraRankingData() traRankingData.textReceived = textReceived?.toLong() traRankingData.textSent = textSent?.toLong() } return traRankingData } fun bytegetMb(byte: Long): String { val kb: Long = 1024 val mb = kb * 1024 val gb = mb * 1024 return if (byte >= gb) { String.format("%.1f GB", byte as Float / gb) } else if (byte > kb) { val f = byte as Float / kb String.format(if (f > 100) "%.0f KB" else "%.1f KB", f) } else if (byte >= mb) { val f = byte as Float / mb String.format(if (f > 100) "%.0f MB" else "%.1f MB", f) } else { String.format("%d B", byte) } }