我正在使用 NetworkStatsManager 的 querySummary() 方法来计算数据使用情况,它给了我正确的使用方法,但有时它会为此方法抛出 NullPointerException。
UsageTestService 中的错误:
java.lang.NullPointerException:
at android.os.Parcel.readException (Parcel.java:1626)
at android.os.Parcel.readException (Parcel.java:1573)
at android.net.INetworkStatsSession$Stub$Proxy.getSummaryForAllUid
(INetworkStatsSession.java:355)
at android.app.usage.NetworkStats.startSummaryEnumeration
(NetworkStats.java:330)
at android.app.usage.NetworkStatsManager.querySummary
(NetworkStatsManager.java:166)
at com.test.services.UsageTestService$1.run (UsageTestService.java:172)
我的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkStats networkStats = null;
try {
networkStatsManager = (NetworkStatsManager) getApplicationContext().getSystemService(Context.NETWORK_STATS_SERVICE);
networkStats = networkStatsManager.querySummary(0, getSubscriberId(UsageTestService.this, ConnectivityManager.TYPE_MOBILE), 0, System.currentTimeMillis());
} catch (RemoteException e) {
e.printStackTrace();
}
if(networkStats!=null)
{
while (networkStats.hasNextBucket()) {
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);
int uid = bucket.getUid();
double rx1 = bucket.getRxBytes();
double tx1 = bucket.getTxBytes();
int state1 = bucket.getState();
double totalRxTx1 = rx1+ tx1;
}
}
}
会有什么问题?