在Server中获取的流量数据
根据包名获取该应用的uid
public int getUid(String package) {
try {
PackageManager pm = mEcarService.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(package, PackageManager.GET_ACTIVITIES);
return ai.uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return -1;
}
流量统计工具类
public class DataUsageUtil {
private static final String TAG = DataUsageUtil.class.getSimpleName();
private static Context mContext ;
private static DataUsageUtil INSTANCE = null;
private static final int LOADER_CHART_DATA = 2;
private static final int LOADER_SUMMARY = 3;
INetworkStatsSession mSession ;
PackageManager pm = null;
NetworkStats mStats = null;
public DataUsageUtil(Context context){
mContext = context;
}
public static DataUsageUtil getInstance(Context context){
if(INSTANCE == null){
INSTANCE = new DataUsageUtil(context);
}
return INSTANCE;
}
public Map<Integer, DataUsageWifi> forLoaderManager(NetworkTemplate template, long start, long end){
INetworkStatsService mService
= INetworkStatsService.Stub.asInterface(ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
try {
mSession = mService.openSession();
if (mSession == null) {
Log.e(TAG, "getDataUsageWifi: the session is null" );
return null;
}
mStats = null;
((Activity)mContext).getLoaderManager().restartLoader(LOADER_SUMMARY,
SummaryForAllUidLoader.buildArgs(template, start, end), mSummaryCallbacks);
int time = 50;
while(true){
if(mStats != null)
break;
if(time-- < 0)
break;
Thread.sleep(50);
}
if(mStats == null){
Log.e(TAG, "getDataUsageWifi: get the netword data usage failed" );
return null;
}
pm = mContext.getPackageManager();
Map<Integer, DataUsageWifi> map = new HashMap<>();
int size = mStats.size();
NetworkStats.Entry entity = null;
for(int i=0; i<size; i++){
entity = mStats.getValues(i, entity);
if(map.containsKey(entity.uid)){
//uid相同,则将值相加
DataUsageWifi info = map.get(entity.uid);
info.rxByte += entity.rxBytes;
info.txByte += entity.txBytes;
map.put(entity.uid, info);
}else{
String name = pm.getNameForUid(entity.uid);
map.put(entity.uid, new DataUsageWifi(entity.uid, name, entity.rxBytes, entity.txBytes));
// Log.d(TAG, "onLoadFinished: name="+ name);
// Log.d(TAG, "onLoadFinished: uid="+ entity.uid);
// Log.d(TAG, "onLoadFinished: set="+ entity.set);
// Log.d(TAG, "onLoadFinished: rxByte="+ entity.rxBytes);
// Log.d(TAG, "onLoadFinished: txByte="+ entity.txBytes);
}
}
return map;
} catch (RemoteException e) {
e.printStackTrace();
return null;
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
private final LoaderManager.LoaderCallbacks<NetworkStats> mSummaryCallbacks = new LoaderManager.LoaderCallbacks<
NetworkStats>() {
@Override
public Loader<NetworkStats> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader: id="+ id);
return new SummaryForAllUidLoader(mContext, mSession, args);
}
@Override
public void onLoadFinished(Loader<NetworkStats> loader, NetworkStats data) {
Log.d(TAG, "onLoadFinished: loader="+ loader+ ", data="+ data);
mStats = data;
}
@Override
public void onLoaderReset(Loader<NetworkStats> loader) {
Log.d(TAG, "onLoaderReset: loader="+ loader);
}
private void updateEmptyVisible() {
Log.d(TAG, "updateEmptyVisible: executed");
}
};
public class DataUsageWifi{
public long uid = 0;
public String packageName = null;
public long rxByte = 0;
public long txByte = 0;
public DataUsageWifi(long uid, String packageName, long rxByte, long txByte) {
this.uid = uid;
this.packageName = packageName;
this.rxByte = rxByte;
this.txByte = txByte;
}
}
public Map<Integer, DataUsageWifi> forNetworkStatsManager(int type, long start, long end){
Log.d(TAG, "getAllDataUsage: start="+ start+ ", end="+ end);
PackageManager pm = (PackageManager) mContext.getPackageManager();
if(pm == null){
Log.e(TAG, "getAllDataUsage: get the telephone manager failed" );
return null;
}
TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(pm == null){
Log.e(TAG, "getAllDataUsage: get the telephone manager failed" );
return null;
}
NetworkStatsManager nsm = (NetworkStatsManager) mContext.getSystemService(Context.NETWORK_STATS_SERVICE);
if(nsm == null){
Log.e(TAG, "getAllDataUsage: get the network stats manager failed");
return null;
}
List<ApplicationInfo> list = pm.getInstalledApplications(PackageManager.GET_ACTIVITIES);
try {
Map<Integer, DataUsageWifi> result = getDataUsageByUid(nsm, tm, type, start, end);
if(result == null)return null;
for (ApplicationInfo info: list) {
DataUsageWifi data = result.get(info.uid);
if(data == null)
continue;
data.packageName = info.packageName;
}
return result;
} catch (RemoteException e) {
e.printStackTrace();
return null;
}
}
private Map<Integer, DataUsageWifi> getDataUsageByUid(NetworkStatsManager nsm, TelephonyManager tm,
int type, long start, long end) throws RemoteException {
Log.d(TAG, "listDataUsageByUid: executed");
// 获取subscriberId
String subId = tm.getSubscriberId();
if((type==ConnectivityManager.TYPE_MOBILE) && (subId==null)){
Log.e(TAG, "listDataUsageByUid: get sub id fail" );
return null;
}
android.app.usage.NetworkStats summaryStats;
android.app.usage.NetworkStats.Bucket summaryBucket
= new android.app.usage.NetworkStats.Bucket();
Map<Integer, DataUsageWifi> map = new HashMap<>();
summaryStats = nsm.querySummary(type, subId, start, end);
do {
summaryStats.getNextBucket(summaryBucket);
int summaryUid = summaryBucket.getUid();
long summaryRx = summaryBucket.getRxBytes();
long summaryTx = summaryBucket.getTxBytes();
Log.i(TAG, "uid:" + summaryBucket.getUid() + " rx:" + summaryBucket.getRxBytes() +
" tx:" + summaryBucket.getTxBytes());
DataUsageWifi info = new DataUsageWifi(summaryUid, "", summaryRx, summaryTx);
map.put(summaryUid, info);
} while (summaryStats.hasNextBucket());
return map;
}
}
该类是拷贝设置里面的一个类
public class SummaryForAllUidLoader extends AsyncTaskLoader<NetworkStats> {
private static final String KEY_TEMPLATE = "template";
private static final String KEY_START = "start";
private static final String KEY_END = "end";
private final INetworkStatsSession mSession;
private final Bundle mArgs;
public static Bundle buildArgs(NetworkTemplate template, long start, long end) {
final Bundle args = new Bundle();
args.putParcelable(KEY_TEMPLATE, template);
args.putLong(KEY_START, start);
args.putLong(KEY_END, end);
return args;
}
public SummaryForAllUidLoader(Context context, INetworkStatsSession session, Bundle args) {
super(context);
mSession = session;
mArgs = args;
}
@Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
@Override
public NetworkStats loadInBackground() {
final NetworkTemplate template = mArgs.getParcelable(KEY_TEMPLATE);
final long start = mArgs.getLong(KEY_START);
final long end = mArgs.getLong(KEY_END);
try {
return mSession.getSummaryForAllUid(template, start, end, false);
} catch (RemoteException e) {
return null;
}
}
@Override
protected void onStopLoading() {
super.onStopLoading();
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
cancelLoad();
}
}
最终获取应用流量数据
public long forNetworkStatsManager(){
long start = SystemClock.elapsedRealtime();
long end = System.currentTimeMillis();
Map<Integer, DataUsageUtil.DataUsageWifi> mapMobile = DataUsageUtil.getInstance(this).forNetworkStatsManager(
ConnectivityManager.TYPE_MOBILE, start, end);
Map<Integer, DataUsageUtil.DataUsageWifi> mapWifi = DataUsageUtil.getInstance(this).forNetworkStatsManager(
ConnectivityManager.TYPE_WIFI, start, end);
if(mapMobile==null && mapWifi==null){
Log.e(TAG,"应用使用流量获取失败");
return 0;
}
Log.e(TAG,"使用流量:mobile="+ mapMobile.size()+ ", wifi="+ mapWifi.size()+ "\n");
Map<Integer, String[]> list = new HashMap<>();
Set<Integer> keys = mapMobile.keySet();
for(Integer key : keys){
DataUsageUtil.DataUsageWifi data
= mapMobile.get(key);
if(list.get(key) == null) {
String[] tmp = new String[5];
tmp[0] = String.valueOf(key);
tmp[1] = String.valueOf(data.rxByte);
tmp[2] = String.valueOf(data.txByte);
list.put(key, tmp);
}else{
String[] tmp = list.get(key);
tmp[1] = String.valueOf(data.rxByte);
tmp[2] = String.valueOf(data.txByte);
list.put(key, tmp);
}
}
keys = mapWifi.keySet();
for(Integer key : keys){
DataUsageUtil.DataUsageWifi data
= mapWifi.get(key);
if(list.get(key) == null) {
String[] tmp = new String[5];
tmp[0] = String.valueOf(key);
tmp[3] = String.valueOf(data.rxByte);
tmp[4] = String.valueOf(data.txByte);
list.put(key, tmp);
}else{
String[] tmp = list.get(key);
tmp[3] = String.valueOf(data.rxByte);
tmp[4] = String.valueOf(data.txByte);
list.put(key, tmp);
}
}
keys = list.keySet();
for(Integer key : keys){
String[] lst = list.get(key);
if(Long.parseLong(lst[0]) == getUid()){
Log.e(TAG,"getUid() : "+ getUid()+ "\n");
Log.e(TAG,"packageName: "+ lst[0]+ "\n");
Log.e(TAG,"Mobile Rx: "+ lst[1]+ "\n");
Log.e(TAG,"Mobile Tx: "+ lst[2]+ "\n");
Log.e(TAG,"Wifi Rx: "+ lst[3]+ "\n");
Log.e(TAG,"Wifi Tx: "+ lst[4]+ "\n");
return Long.parseLong(lst[1])+Long.parseLong(lst[2]);
}
}
return 0;
}