Catering para dispositivos que ejecutan frijol Jelly así como versiones posteriores a Jelly bean cuando se obtiene el uso de datos de la aplicación

Quisiera abastecer para los dispositivos que funcionaban en la versión del frijol de la jalea y abajo así como versiones sobre Jelly Bean.

Mi método se supone para obtener el uso de aplicaciones / tráfico para todas las aplicaciones basadas en el ID de la aplicación. Por favor tome nota de esta línea rx = Long.parseLong(String.valueOf(id)); En la primera cláusula if que abastece a los dispositivos que ejecutan versiones inferiores o iguales a Jelly Bean.

El uso de datos de una aplicación instalada basada en su ID se obtiene utilizando TrafficStats.getUidTxBytes(uid) pero que sólo devuelve un valor de 0 en 4.3 sin embargo, la cláusula else con TrafficStats.getUidTxBytes(uid) recupera el uso de la aplicación por aplicación con precisión en Versiones superiores a 5.

Estoy particularmente preocupado por la cláusula if que abastece a dispositivo que ejecuta versión android inferior a 5 por ejemplo en este caso 4.3 (Jelly Bean)

 public void recordSnapshot(Context context) { TinyDB settings = new TinyDB(context); int boot_id = settings.getInt(AppPreferences.BOOT_ID); PackageManager pm = context.getPackageManager(); for (ApplicationInfo app : pm.getInstalledApplications(0)) { String androidOS = Build.VERSION.RELEASE; int currentapiVersion = android.os.Build.VERSION.SDK_INT; long tx = 0; long rx = 0; int uid = app.uid; if(currentapiVersion <= Build.VERSION_CODES.JELLY_BEAN) { File dir = new File("/proc/uid_stat/"); String[] children = dir.list(); List<Integer> uids = new ArrayList<Integer>(); for (int i = 0; i < children.length; i++) { uid = Integer.parseInt(children[i]); String uidString = String.valueOf(uid); File uidFileDir = new File("/proc/uid_stat/" + uidString); File uidActualFile = new File(uidFileDir, "tcp_rcv"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(uidActualFile)); String line; while ((line = br.readLine()) != null) { Log.d(String.valueOf(uid), line);//this returns the amount of data received for the particular uid rx = Long.parseLong(String.valueOf(uid)); text.append(line); text.append('\n'); } } catch (IOException e) { //handle this } uids.add(id); } } else { tx = TrafficStats.getUidTxBytes(uid); rx = TrafficStats.getUidRxBytes(uid); } } 

Método completo

 public void recordSnapshot(Context context) { TinyDB settings = new TinyDB(context); int boot_id = settings.getInt(AppPreferences.BOOT_ID); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); int networkType = NetworkState.GetNetworkState(context, info, "DataUsageRecorder"); // wifi, data, data roaming // Get all apps PackageManager pm = context.getPackageManager(); for (ApplicationInfo app : pm.getInstalledApplications(0)) { String androidOS = Build.VERSION.RELEASE; int currentapiVersion = android.os.Build.VERSION.SDK_INT; long tx = 0; long rx = 0; int uid = app.uid; if(currentapiVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { File dir = new File("/proc/uid_stat/"); String[] children = dir.list(); List<Integer> uids = new ArrayList<Integer>(); for (int i = 0; i < children.length; i++) { uid = Integer.parseInt(children[i]); String uidString = String.valueOf(uid); File uidFileDir = new File("/proc/uid_stat/" + uidString); File uidActualFile = new File(uidFileDir, "tcp_rcv"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(uidActualFile)); String line; while ((line = br.readLine()) != null) { Log.d(String.valueOf(uid), line);//this returns the amount of data received for the particular uid rx = Long.parseLong(String.valueOf(uid)); //text.append(line); //text.append('\n'); } } catch (IOException e) { //handle this } uids.add(uid); } } else { tx = TrafficStats.getUidTxBytes(uid); rx = TrafficStats.getUidRxBytes(uid); } if ((tx == 0 || rx == 0)) { // Skip inactive items continue; } else if (Globals.DEBUG && (tx < DEBUG_5MB && rx < DEBUG_5MB)) { // Let's skip all the BS for quick testing continue; } // Get package name String package_name; try { CharSequence name = pm.getApplicationLabel(app); package_name = name != null ? name.toString() : ""; } catch (Exception e) { e.printStackTrace(); package_name = ""; } AppUsage totals; AppUsage appUsage; // Get current data entry for app //appUsage = appUsageDao.queryBuilder().where(AppUsageDao.Properties.App_uid.eq(uid), AppUsageDao.Properties.Type.eq(networkType), AppUsageDao.Properties.Boot_id.eq(boot_id)).limit(1).unique(); // Get last recorded totals since device boot totals = appUsageDao.queryBuilder().where(AppUsageDao.Properties.App_uid.eq(uid), AppUsageDao.Properties.Type.eq(NetworkState.ALL), AppUsageDao.Properties.Boot_id.eq(boot_id)).limit(1).unique(); long tx_diff = tx; long rx_diff = rx; if (totals != null) { // Get difference, and update tx_diff -= totals.getTx(); rx_diff -= totals.getRx(); totals.setTx(tx); totals.setRx(rx); } else { // add new master totals = new AppUsage(null, new Date(), uid, package_name, NetworkState.ALL, tx_diff, rx_diff, 0, 0, boot_id); } // add new app appUsage = new AppUsage(null, new Date(), uid, package_name, networkType, tx_diff, rx_diff, 0, 0, boot_id); /*if (appUsage == null) { // Create new appUsage = new AppUsage(null, new Date(), uid, package_name, networkType, tx, rx, 0, 0, boot_id); } else { // Update appUsage.setTx(tx); appUsage.setRx(rx); }*/ try { // master appUsageDao.insertOrReplace(totals); } catch (DaoException e) { e.printStackTrace(); } try { appUsageDao.insertOrReplace(appUsage); } catch (DaoException e) { e.printStackTrace(); } //apps.put(app.uid, new DataUsageItem(app.uid, app.packageName, pm.getApplicationLabel(app).toString())); } } 

A pesar de lo que la documentación dice estadísticas de tráfico no parece funcionar bien en 4.3 en el sentido de que en algunos casos funciona para algunos id de la aplicación y no para algunos, por lo tanto, evitaría toda la clase trafficstats y crear dos métodos personalizados apuntando a la nativa c Archivo que contiene datos de uso de la aplicación para recuperar tx (datos transmitidos) y Rx (datos recibidos) dentro de la misma clase

  long tx = yourClass.getUidTxBytes(uid); long rx = yourClass.getUidRxBytes(uid); 

Entonces para RX

 public static Long getUidRxBytes(int uid) { BufferedReader reader; Long rxBytes = 0L; try { reader = new BufferedReader(new FileReader("/proc/uid_stat/" + uid + "/tcp_rcv")); rxBytes = Long.parseLong(reader.readLine()); reader.close(); } catch (FileNotFoundException e) { rxBytes = TrafficStats.getUidRxBytes(uid); //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rxBytes; }** 

Entonces para TX

  public static Long getUidTxBytes(int uid) { BufferedReader reader; Long txBytes = 0L; try { reader = new BufferedReader(new FileReader("/proc/uid_stat/" + uid + "/tcp_snd")); txBytes = Long.parseLong(reader.readLine()); reader.close(); } catch (FileNotFoundException e) { txBytes = TrafficStats.getUidTxBytes(uid); //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return txBytes; } 
  • Android detectar si constructor llamado en modo de diseño?
  • Android / java getIdentifier con
  • Cómo convertir automáticamente if-else if statement to switch
  • No se puede crear la compilación de la versión tras actualizar los servicios de reproducción a 8.3.0
  • Revise la fecha con la fecha de hoy
  • TEXTVIEW sustanciación ubicación
  • Ningún dispositivo de destino encontrado android studio 2.1.1
  • Cómo crear mi propia biblioteca android y alojarla
  • Java / Android: clases locales anónimas vs clases nombradas
  • Java: Necesita alguna manera de acortar este código
  • FLAG_ACTIVITY_CLEAR_TOP no funciona
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.