getNetworkBandwithUsageByPid function

(int, int) getNetworkBandwithUsageByPid({
  1. int? pidProcces,
  2. bool isThrowOnError = false,
})

Implementation

(int bandwith_download, int bandwith_upload) getNetworkBandwithUsageByPid({
  int? pidProcces,
  bool isThrowOnError = false,
}) {
  pidProcces ??= pid;

  try {
    if (Dart.isAndroid || Dart.isLinux) {
      final file = File('/proc/${pidProcces}/net/dev');
      final String data = (file.readAsStringSync()).trim();

      if (data.isNotEmpty) {
        final List<String> datas = data.split("\n");
        datas.removeAt(0);
        datas.removeAt(0);

        int bandwith_download = 0;
        int bandwith_upload = 0;

        for (var i = 0; i < datas.length; i++) {
          final String data_loop = datas[i];

          List<String> data_loops = data_loop
              .split(" ")
              .where((element) => element.trim().isNotEmpty)
              .toList();
          if (data_loops.isEmpty) {
            continue;
          }
          try {
            bandwith_download += int.tryParse("${data_loops[1]}") ?? 0;
            bandwith_upload += int.tryParse("${data_loops[9]}") ?? 0;
          } catch (e) {}
        }
        return (bandwith_download, bandwith_upload);
      }
    }
  } catch (e) {
    if (isThrowOnError) {
      rethrow;
    }
  }

  return (0, 0);
}