我可以列出成功使用网络的应用程序,对于Android N以下的设备使用TrafficStats
,对于Android N及以上的设备使用NetworkStatsManager
,如下所示:
TrafficStats代码:
private void getTrafficInfosByTrafficStatsAPI(PackageManager pm) {
//List<TrafficInfo> trafficlnfos = new ArrayList<>();
TrafficStats.setThreadStatsTag(0);
List<PackageInfo> packinfos = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for (PackageInfo info : packinfos) {
String[] premissions = info.requestedPermissions;
if (premissions != null && premissions.length > 0) {
for (String premission : premissions) {
if ("android.permission.INTERNET".equals(premission)) {
int uid = info.applicationInfo.uid;
long totalRx = TrafficStats.getTotalRxBytes();
long totalTx = TrafficStats.getTotalTxBytes();
Log.d(TAG, info.packageName + " " + totalRx + " " + totalTx);
}
}
}
}
}
及以下使用NetworkStatsManager:
private void getNetworkStatsBuckets(PackageManager pm) throws PackageManager.NameNotFoundException, RemoteException {
NetworkStatsManager networkStatsManager = (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String subscriberId = manager.getSubscriberId();
List<PackageInfo> packinfos = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for (PackageInfo pInfo : packinfos) {
String[] premissions = pInfo.requestedPermissions;
if (premissions != null && premissions.length > 0) {
for (String premission : premissions) {
if ("android.permission.INTERNET".equals(premission)) {
ApplicationInfo info = pm.getApplicationInfo(pInfo.packageName, 0);
int uid = info.uid;
NetworkStats networkStats = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, subscriberId , 0, System.currentTimeMillis(), uid );
long rxBytes = 0 , txBytes = 0;
while (networkStats.hasNextBucket()){
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);
rxBytes += bucket.getRxBytes();
txBytes += bucket.getTxBytes();
}
Log.d(TAG, pInfo.packageName + " " + rxBytes + " " + txBytes);
}
}
}
}
return;
}
通过两种方法,我可以在LogCat中看到所有包及其发送和接收的字节。
我要允许用户重置这些计数器并从清除计数器开始就开始监视应用程序的网络使用情况的问题。
我知道TrafficStats
API中有可用的方法,例如
clearThreadStatsTag()
->我使用了它,但计数器没有清除。clearThreadStatsUid()
->无法解决,我也不知道为什么对于NetworkStatsManager
API,我找不到相应的方法。
所以我在这里有两个问题?
TrafficStats
API中的两种清除方法?NetworkStatsManager
清除应用程序的网络使用情况计数器?如果是,我该怎么办?我们非常感谢您的帮助。 预先感谢。