0

这是我的代码

                Calendar startCalendar;
                Calendar stopCalendar;
            startCalendar= Calendar.getInstance();
            stopCalendar=Calendar.getInstance();
            startCalendar.set(2020,10,2,0,0);
            stopCalendar.set(2020,10,3,0,0);
            NetworkStatsManager networkStatsManager = (NetworkStatsManager) getContext().getSystemService(Context.NETWORK_STATS_SERVICE);
            NetworkStats.Bucket bucket;
                bucket = networkStatsManager.querySummaryForDevice(NetworkStats.Bucket.DEFAULT_NETWORK_ALL,"",startCalendar.getTimeInMillis(),stopCalendar.getTimeInMillis());
                long rxBytes = bucket.getRxBytes();
                long txBytes = bucket.getTxBytes();

我想获得每天的互联网使用情况。该应用程序可以访问数据使用,我还在清单中检查了所需的权限。

这是日志

2020-10-02 10:42:56.448 28091-28091/com.sreejithsreejayan.internetspeedometer D/AndroidRuntime: Shutting down VM
2020-10-02 10:42:56.452 28091-28091/com.sreejithsreejayan.internetspeedometer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sreejithsreejayan.internetspeedometer, PID: 28091
    java.lang.NullPointerException: Attempt to invoke virtual method 'long android.app.usage.NetworkStats$Bucket.getRxBytes()' on a null object reference
        at com.sreejithsreejayan.internetspeedometer.ui.home.HomeFragment$2.onClick(HomeFragment.java:71)
        at android.view.View.performClick(View.java:7870)
        at android.widget.TextView.performClick(TextView.java:14970)
        at android.view.View.performClickInternal(View.java:7839)
        at android.view.View.access$3600(View.java:886)
        at android.view.View$PerformClick.run(View.java:29363)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:7814)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
2020-10-02 10:42:56.490 28091-28091/com.sreejithsreejayan.internetspeedometer I/Process: Sending signal. PID: 28091 SIG: 9

为什么桶是空的(空)。我是android开发新手,请帮忙。

4

1 回答 1

0

我替换NetworkStats.Bucket.DEFAULT_NETWORK_ALLConnectivityManager.TYPE_WIFIthen 它不是 null 但ConnectivityManager.TYPE_WIFI已弃用

于 2020-10-02T16:11:45.683 回答