无法解析符号 'networkStatsManager' [networkStatsManager]

Cannot resolve symbol 'networkStatsManager' [networkStatsManager]

我正在编写一个应用程序的一小部分,它使用 android 的 networkstatsManager 查找 Uid 的 txBytes。但是,我在尝试使用 networkStatsManager 时遇到错误。 Android Studio 一直给我错误“无法解析符号 'networkStatsManager'”。我不确定我做错了什么。任何建议将不胜感激。

这是继续给我错误的行:networkStats = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, "", 0, System.currentTimeMillis(),stat);第 13 行。

这是我的代码:

PackageManager packageManager = getPackageManager();

    ApplicationInfo info = null;
    try {
        info = packageManager.getApplicationInfo(packname, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    int stat = info.uid;

    NetworkStats networkStats = null;
    NetworkStats.Bucket bucket = new NetworkStats.Bucket();
    networkStats = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, "", 0, System.currentTimeMillis(),stat);

    long txBytes = 0L;
    while (networkStats.hasNextBucket()) {
        networkStats.getNextBucket(bucket);
        txBytes += bucket.getTxBytes();
        TextView textView2 = (TextView) findViewById(R.id.test2);
        textView2.setText(String.valueOf(txBytes));
    }
    networkStats.close();

您收到此错误是因为 networkStatsManager 尚未声明和初始化

NetworkStats networkStats = null;
NetworkStats.Bucket bucket = new NetworkStats.Bucket();

//this is the missing line
NetworkStatsManager networkStatsManager = context.getSystemService(NetworkStatsManager.class)

networkStats = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, "", 0, System.currentTimeMillis(),stat);