Android program traffic monitoring

TestTrafficMonitor

This is a program for testing the system traffic statistics class TrafficStats, which can be used to easily monitor APP traffic;

Summary of the use of the TrafficStats class:

1. This class provides methods directly: the number of traffic and packets used by all APPs using the mobile network, the number of traffic and packets used by all APPs, and the number of traffic and packets used by an APP;

2. The data provided by this category is accumulated by switching the mobile phone on and off, and the data will be reset to 0 after the shutdown and restart;

3. It is not possible to directly obtain the traffic statistics of an APP using the mobile network and wifi network through this category. If you need to distinguish the network type for traffic statistics, you need to open the background service, monitor the network status change broadcast, and record and record according to the network status change. Calculate traffic statistics under different network types;

4. All network traffic statistics provided by this category may not only include mobile networks and wifi networks, but may also include traffic generated by socket communication between APPs;

main code

package com.itzs.testtrafficmonitor;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private final String TAG = MainActivity.class.getSimpleName();

    private RecyclerView recyclerView;
    private MainAdapter mainAdapter = null;

    private List<AppTrafficModel> listApps = new ArrayList<AppTrafficModel>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv_main);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mainAdapter = new MainAdapter ();
        recyclerView.setAdapter (mainAdapter);

        trafficMonitor();
        mainAdapter.notifyDataSetChanged();
    }

    /**
     * Traverse the traffic records of applications with Internet access
     */
    private void trafficMonitor(){
        PackageManager pm = this.getPackageManager();
        List<PackageInfo> packinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | 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)) {
                        // System.out.println(info.packageName+"Access Network");
                        int uid = info.applicationInfo.uid;
                        long rx = TrafficStats.getUidRxBytes(uid);
                        long tx = TrafficStats.getUidTxBytes(uid);

                        AppTrafficModel appTrafficModel = new AppTrafficModel();
                        appTrafficModel.setAppInfo(info.applicationInfo);
                        appTrafficModel.setDownload(rx);
                        appTrafficModel.setUpload(tx);
                        listApps.add(appTrafficModel);


                        /** Get the total number of bytes received by the phone via 2G/3G*/
                        TrafficStats.getMobileRxBytes();
                        /** Get the total number of packets received by the phone via 2G/3G*/
                        TrafficStats.getMobileRxPackets();
                        /** Get the total number of bytes sent by the phone via 2G/3G*/
                        TrafficStats.getMobileTxBytes();
                        /** Get the total number of data packets sent by the phone via 2G/3G*/
                        TrafficStats.getMobileTxPackets();
                        /** Get the total number of bytes received by the phone through all network methods (including wifi) */
                        TrafficStats.getTotalRxBytes ();
                        /** Get the total number of data packets received by the phone through all network methods (including wifi) */
                        TrafficStats.getTotalRxPackets ();
                        /** Get the total number of bytes sent by the phone through all network methods (including wifi) */
                        TrafficStats.getTotalTxBytes ();
                        /** Get the total number of data packets sent by the phone through all network methods (including wifi) */
                        TrafficStats.getTotalTxPackets ();
                        /** Get the total number of bytes received by the application corresponding to the specified UID of the mobile phone through all network methods (including wifi) */
                        TrafficStats.getUidRxBytes(uid);
                        /** Get the total number of bytes sent by the application corresponding to the specified UID of the mobile phone through all network methods (including wifi) */
                        TrafficStats.getUidTxBytes(uid);

                    }
                }
            }
        }
    }

    class MainAdapter extends RecyclerView.Adapter{
        PackageManager pm = MainActivity.this.getPackageManager();
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_main_item, parent, false);
            return new MainHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            AppTrafficModel trafficModel = listApps.get(position);
            MainHolder mainHolder = (MainHolder) holder;
            mainHolder.ivLauncher.setImageDrawable(trafficModel.getAppInfo().loadIcon(pm));
            mainHolder.tvName.setText((String) pm.getApplicationLabel(trafficModel.getAppInfo()));
            mainHolder.tvDownload.setText("下行:" + Formatter.formatFileSize(MainActivity.this, trafficModel.getDownload()));
            mainHolder.tvUpload.setText("上行:" + Formatter.formatFileSize(MainActivity.this, trafficModel.getUpload()));
        }

        @Override
        public int getItemCount() {
            return listApps.size();
        }

        class MainHolder extends RecyclerView.ViewHolder{

            ImageView ivLauncher;
            TextView tvName;
            TextView tvDownload;
            TextView tvUpload;

            public MainHolder(View itemView) {
                super(itemView);
                ivLauncher = (ImageView) itemView.findViewById(R.id.iv_main_item_laucher);
                tvName = (TextView) itemView.findViewById(R.id.tv_main_item_name);
                tvDownload = (TextView) itemView.findViewById(R.id.tv_main_item_download);
                tvUpload = (TextView) itemView.findViewById(R.id.tv_main_item_upload);
            }
        }
    }

}


Program screenshot:

image1


Demo download address:

https://github.com/ZhangSir/TestTrafficMonitor

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325901588&siteId=291194637