【问题标题】:getUidTxBytes(int uid) always return 0 in android 6.0getUidTxBytes(int uid) 在 android 6.0 中总是返回 0
【发布时间】:2017-07-21 18:40:49
【问题描述】:

我正在尝试获取所有应用的网络流量统计信息。我只是打印设备中每个应用程序的总网络流量。该代码在 android 4.4 和 5.1 设备中运行良好,但在 android 6.0 设备中它总是为所有应用程序返回 0。任何人都可以告诉我为什么会在 android 6.0 设备中发生这种情况。

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

    for(ApplicationInfo app : getPackageManager().getInstalledApplications(0)){
        long tx = TrafficStats.getUidTxBytes(app.uid);
        long rx = TrafficStats.getUidRxBytes(app.uid);
        long total = tx + rx;
        Log.e("total data of ", app.packageName + " = " + total);
    }
}

这是我的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mts.trafficstatsdemo">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

【问题讨论】:

    标签: android android-6.0-marshmallow android-trafficstats


    【解决方案1】:

    根据doc

    从 N 开始,这将只报告呼叫的流量统计信息 用户标识符。它将为所有其他 UID 返回 UNSUPPORTED 以保护隐私 原因。访问属于其他人的历史网络统计信息 UID,使用 NetworkStatsManager。

    【讨论】:

    • 问题是关于android 6 (M)...应该没有限制。我在 android 6 上有一些设备可以很好地检索此信息,而一个特定的设备则不能,但根据这个答案,限制应该会影响 android 7。
    【解决方案2】:

    尝试获取当前应用的数据,你会惊奇地发现,你实际上可以获取到自己应用的网络详细信息,原因如下:

    在 Android 4.3 之前,UID 流量统计信息可用于 TCP 和 UDP,并包括用于字节和数据包以及发送和接收的 API。该数据是从 /proc/uid_stat/[pid]/* 文件中提取的。

    在 Android 4.3 中,开发人员决定切换到更好、更安全的 API,使用 xt_qtaguid UID 统计信息,它是 Linux 中 netfilter 内核模块的一部分。此 API (procfs) 允许基于进程 UID 进行访问,这就是为什么当您尝试在 Android=>4.3 中访问 TrafficStats API 时,您将获得零信息的非自己 UID。

    所以目前处理问题的方式可以是:

    1) 网络统计管理器: 这涉及使用系统级权限。 2) 手动读取文件/proc/uid_stat/

    请注意,在后面的选项中,数据会在启动时被清除。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2015-10-01
      相关资源
      最近更新 更多