public class MainApplication extends Application{ int uid = -1; long begin_rx = 0; long begin_tx = 0; @Override public void onCreate() { super.onCreate(); uid = this.getUid(); Log.i("MainApplication","当前进程的名字:"+getCurProcessName(this)); Log.i("MainApplication","onCreate:"); Log.i("MainApplication","uid:"+uid); begin_rx = TrafficStats.getUidRxBytes(uid);//获取接收到的数据 begin_tx = TrafficStats.getUidTxBytes(uid);//获取发送的数据 Log.i("MainApplication","开始时 接收数据:"+ Formatter.formatFileSize(this,begin_rx)); Log.i("MainApplication","开始时 发送数据:"+ Formatter.formatFileSize(this,begin_tx)); } //获取活动进程的名字 private String getCurProcessName(Context context) { int pid = android.os.Process.myPid(); ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) { if (appProcess.pid == pid) { return appProcess.processName; } } return ""; } //获取uid public int getUid() { try { PackageManager pm = this.getPackageManager(); ApplicationInfo ai = pm.getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA); return ai.uid; } catch (Exception e) { e.printStackTrace(); } return -1; } @Override public void onLowMemory() { Log.i("MainApplication","onLowMemory"); super.onLowMemory(); } @Override public void onTrimMemory(int level) {//系统回收内存时执行 long rx = TrafficStats.getUidRxBytes(uid); long tx = TrafficStats.getUidTxBytes(uid); Log.i("MainApplication","onTrimMemory"); Log.i("MainApplication","app一共接收数据:"+Formatter.formatFileSize(this,rx-begin_rx)); Log.i("MainApplication","app一共发送数据:"+Formatter.formatFileSize(this,tx-begin_tx)); super.onTrimMemory(level); } @Override public void onTerminate() {//退出时执行 不保证一定执行 super.onTerminate(); long rx = TrafficStats.getUidRxBytes(uid); long tx = TrafficStats.getUidTxBytes(uid); Log.i("MainApplication","onTerminate"); Log.i("MainApplication","结束时 接收数据:"+Formatter.formatFileSize(this,rx)); Log.i("MainApplication","结束时 发送数据:"+Formatter.formatFileSize(this,tx)); } }如图:
如果有独立的进程,那么application increase方法会多次调用。