Merge "Add permissions to the shell to allow creation of CTS tests for trust."
diff --git a/Android.bp b/Android.bp
index 6260683..54fedaf 100644
--- a/Android.bp
+++ b/Android.bp
@@ -145,6 +145,7 @@
"framework-minus-apex",
"framework-appsearch.impl",
"framework-connectivity.impl",
+ "framework-connectivity-tiramisu.impl",
"framework-graphics.impl",
"framework-mediaprovider.impl",
"framework-permission.impl",
diff --git a/ApiDocs.bp b/ApiDocs.bp
index 4b5f473..ec7b194 100644
--- a/ApiDocs.bp
+++ b/ApiDocs.bp
@@ -117,6 +117,7 @@
":framework-appsearch-sources",
":framework-connectivity-sources",
+ ":framework-connectivity-tiramisu-updatable-sources",
":framework-graphics-srcs",
":framework-mediaprovider-sources",
":framework-permission-sources",
diff --git a/StubLibraries.bp b/StubLibraries.bp
index 14da6fb..2ce3792 100644
--- a/StubLibraries.bp
+++ b/StubLibraries.bp
@@ -212,6 +212,7 @@
"conscrypt.module.public.api.stubs",
"framework-appsearch.stubs",
"framework-connectivity.stubs",
+ "framework-connectivity-tiramisu.stubs",
"framework-graphics.stubs",
"framework-media.stubs",
"framework-mediaprovider.stubs",
@@ -231,6 +232,7 @@
"conscrypt.module.public.api.stubs", // Only has public stubs
"framework-appsearch.stubs.system",
"framework-connectivity.stubs.system",
+ "framework-connectivity-tiramisu.stubs.system",
"framework-graphics.stubs.system",
"framework-media.stubs.system",
"framework-mediaprovider.stubs.system",
diff --git a/api/Android.bp b/api/Android.bp
index d5d2105..0c3a3e6 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -111,6 +111,7 @@
"conscrypt.module.public.api",
"framework-appsearch",
"framework-connectivity",
+ "framework-connectivity-tiramisu",
"framework-graphics",
"framework-media",
"framework-mediaprovider",
diff --git a/boot/hiddenapi/hiddenapi-max-target-o.txt b/boot/hiddenapi/hiddenapi-max-target-o.txt
index 0ec918b..9153426 100644
--- a/boot/hiddenapi/hiddenapi-max-target-o.txt
+++ b/boot/hiddenapi/hiddenapi-max-target-o.txt
@@ -36441,93 +36441,6 @@
Landroid/net/MobileLinkQualityInfo;->mLteSignalStrength:I
Landroid/net/MobileLinkQualityInfo;->mMobileNetworkType:I
Landroid/net/MobileLinkQualityInfo;->mRssi:I
-Landroid/net/nsd/DnsSdTxtRecord;-><init>()V
-Landroid/net/nsd/DnsSdTxtRecord;-><init>(Landroid/net/nsd/DnsSdTxtRecord;)V
-Landroid/net/nsd/DnsSdTxtRecord;-><init>([B)V
-Landroid/net/nsd/DnsSdTxtRecord;->contains(Ljava/lang/String;)Z
-Landroid/net/nsd/DnsSdTxtRecord;->CREATOR:Landroid/os/Parcelable$Creator;
-Landroid/net/nsd/DnsSdTxtRecord;->get(Ljava/lang/String;)Ljava/lang/String;
-Landroid/net/nsd/DnsSdTxtRecord;->getKey(I)Ljava/lang/String;
-Landroid/net/nsd/DnsSdTxtRecord;->getRawData()[B
-Landroid/net/nsd/DnsSdTxtRecord;->getValue(I)[B
-Landroid/net/nsd/DnsSdTxtRecord;->getValue(Ljava/lang/String;)[B
-Landroid/net/nsd/DnsSdTxtRecord;->getValueAsString(I)Ljava/lang/String;
-Landroid/net/nsd/DnsSdTxtRecord;->insert([B[BI)V
-Landroid/net/nsd/DnsSdTxtRecord;->keyCount()I
-Landroid/net/nsd/DnsSdTxtRecord;->mData:[B
-Landroid/net/nsd/DnsSdTxtRecord;->mSeperator:B
-Landroid/net/nsd/DnsSdTxtRecord;->remove(Ljava/lang/String;)I
-Landroid/net/nsd/DnsSdTxtRecord;->set(Ljava/lang/String;Ljava/lang/String;)V
-Landroid/net/nsd/DnsSdTxtRecord;->size()I
-Landroid/net/nsd/INsdManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
-Landroid/net/nsd/INsdManager$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String;
-Landroid/net/nsd/INsdManager$Stub$Proxy;->getMessenger()Landroid/os/Messenger;
-Landroid/net/nsd/INsdManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;
-Landroid/net/nsd/INsdManager$Stub$Proxy;->setEnabled(Z)V
-Landroid/net/nsd/INsdManager$Stub;-><init>()V
-Landroid/net/nsd/INsdManager$Stub;->DESCRIPTOR:Ljava/lang/String;
-Landroid/net/nsd/INsdManager$Stub;->TRANSACTION_getMessenger:I
-Landroid/net/nsd/INsdManager$Stub;->TRANSACTION_setEnabled:I
-Landroid/net/nsd/INsdManager;->setEnabled(Z)V
-Landroid/net/nsd/NsdManager;-><init>(Landroid/content/Context;Landroid/net/nsd/INsdManager;)V
-Landroid/net/nsd/NsdManager;->BASE:I
-Landroid/net/nsd/NsdManager;->checkListener(Ljava/lang/Object;)V
-Landroid/net/nsd/NsdManager;->checkProtocol(I)V
-Landroid/net/nsd/NsdManager;->checkServiceInfo(Landroid/net/nsd/NsdServiceInfo;)V
-Landroid/net/nsd/NsdManager;->DBG:Z
-Landroid/net/nsd/NsdManager;->DISABLE:I
-Landroid/net/nsd/NsdManager;->disconnect()V
-Landroid/net/nsd/NsdManager;->DISCOVER_SERVICES:I
-Landroid/net/nsd/NsdManager;->DISCOVER_SERVICES_FAILED:I
-Landroid/net/nsd/NsdManager;->DISCOVER_SERVICES_STARTED:I
-Landroid/net/nsd/NsdManager;->ENABLE:I
-Landroid/net/nsd/NsdManager;->EVENT_NAMES:Landroid/util/SparseArray;
-Landroid/net/nsd/NsdManager;->fatal(Ljava/lang/String;)V
-Landroid/net/nsd/NsdManager;->FIRST_LISTENER_KEY:I
-Landroid/net/nsd/NsdManager;->getListenerKey(Ljava/lang/Object;)I
-Landroid/net/nsd/NsdManager;->getMessenger()Landroid/os/Messenger;
-Landroid/net/nsd/NsdManager;->getNsdServiceInfoType(Landroid/net/nsd/NsdServiceInfo;)Ljava/lang/String;
-Landroid/net/nsd/NsdManager;->init()V
-Landroid/net/nsd/NsdManager;->mAsyncChannel:Lcom/android/internal/util/AsyncChannel;
-Landroid/net/nsd/NsdManager;->mConnected:Ljava/util/concurrent/CountDownLatch;
-Landroid/net/nsd/NsdManager;->mContext:Landroid/content/Context;
-Landroid/net/nsd/NsdManager;->mHandler:Landroid/net/nsd/NsdManager$ServiceHandler;
-Landroid/net/nsd/NsdManager;->mListenerKey:I
-Landroid/net/nsd/NsdManager;->mListenerMap:Landroid/util/SparseArray;
-Landroid/net/nsd/NsdManager;->mMapLock:Ljava/lang/Object;
-Landroid/net/nsd/NsdManager;->mService:Landroid/net/nsd/INsdManager;
-Landroid/net/nsd/NsdManager;->mServiceMap:Landroid/util/SparseArray;
-Landroid/net/nsd/NsdManager;->nameOf(I)Ljava/lang/String;
-Landroid/net/nsd/NsdManager;->NATIVE_DAEMON_EVENT:I
-Landroid/net/nsd/NsdManager;->nextListenerKey()I
-Landroid/net/nsd/NsdManager;->putListener(Ljava/lang/Object;Landroid/net/nsd/NsdServiceInfo;)I
-Landroid/net/nsd/NsdManager;->REGISTER_SERVICE:I
-Landroid/net/nsd/NsdManager;->REGISTER_SERVICE_FAILED:I
-Landroid/net/nsd/NsdManager;->REGISTER_SERVICE_SUCCEEDED:I
-Landroid/net/nsd/NsdManager;->removeListener(I)V
-Landroid/net/nsd/NsdManager;->RESOLVE_SERVICE:I
-Landroid/net/nsd/NsdManager;->RESOLVE_SERVICE_FAILED:I
-Landroid/net/nsd/NsdManager;->RESOLVE_SERVICE_SUCCEEDED:I
-Landroid/net/nsd/NsdManager;->SERVICE_FOUND:I
-Landroid/net/nsd/NsdManager;->SERVICE_LOST:I
-Landroid/net/nsd/NsdManager;->setEnabled(Z)V
-Landroid/net/nsd/NsdManager;->STOP_DISCOVERY:I
-Landroid/net/nsd/NsdManager;->STOP_DISCOVERY_FAILED:I
-Landroid/net/nsd/NsdManager;->STOP_DISCOVERY_SUCCEEDED:I
-Landroid/net/nsd/NsdManager;->TAG:Ljava/lang/String;
-Landroid/net/nsd/NsdManager;->UNREGISTER_SERVICE:I
-Landroid/net/nsd/NsdManager;->UNREGISTER_SERVICE_FAILED:I
-Landroid/net/nsd/NsdManager;->UNREGISTER_SERVICE_SUCCEEDED:I
-Landroid/net/nsd/NsdServiceInfo;-><init>(Ljava/lang/String;Ljava/lang/String;)V
-Landroid/net/nsd/NsdServiceInfo;->getTxtRecord()[B
-Landroid/net/nsd/NsdServiceInfo;->getTxtRecordSize()I
-Landroid/net/nsd/NsdServiceInfo;->mHost:Ljava/net/InetAddress;
-Landroid/net/nsd/NsdServiceInfo;->mPort:I
-Landroid/net/nsd/NsdServiceInfo;->mServiceName:Ljava/lang/String;
-Landroid/net/nsd/NsdServiceInfo;->mServiceType:Ljava/lang/String;
-Landroid/net/nsd/NsdServiceInfo;->mTxtRecord:Landroid/util/ArrayMap;
-Landroid/net/nsd/NsdServiceInfo;->setTxtRecords(Ljava/lang/String;)V
-Landroid/net/nsd/NsdServiceInfo;->TAG:Ljava/lang/String;
Landroid/net/PacProxySelector;-><init>()V
Landroid/net/PacProxySelector;->mDefaultList:Ljava/util/List;
Landroid/net/PacProxySelector;->mProxyService:Lcom/android/net/IProxyService;
diff --git a/boot/hiddenapi/hiddenapi-max-target-r-loprio.txt b/boot/hiddenapi/hiddenapi-max-target-r-loprio.txt
index 79d2521..20d7cc0 100644
--- a/boot/hiddenapi/hiddenapi-max-target-r-loprio.txt
+++ b/boot/hiddenapi/hiddenapi-max-target-r-loprio.txt
@@ -21,7 +21,6 @@
Landroid/Manifest$permission;->READ_FRAME_BUFFER:Ljava/lang/String;
Landroid/media/IVolumeController$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IVolumeController;
Landroid/net/INetworkPolicyListener$Stub;-><init>()V
-Landroid/net/nsd/INsdManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/nsd/INsdManager;
Landroid/net/sip/ISipSession$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/sip/ISipSession;
Landroid/nfc/INfcAdapter$Stub;->TRANSACTION_enable:I
Landroid/os/IPowerManager$Stub;->TRANSACTION_acquireWakeLock:I
diff --git a/core/api/current.txt b/core/api/current.txt
index d696bc7..3550d32 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -9061,6 +9061,7 @@
field public static final int SOURCE_CODEC_TYPE_APTX = 2; // 0x2
field public static final int SOURCE_CODEC_TYPE_APTX_HD = 3; // 0x3
field public static final int SOURCE_CODEC_TYPE_INVALID = 1000000; // 0xf4240
+ field public static final int SOURCE_CODEC_TYPE_LC3 = 5; // 0x5
field public static final int SOURCE_CODEC_TYPE_LDAC = 4; // 0x4
field public static final int SOURCE_CODEC_TYPE_SBC = 0; // 0x0
}
@@ -26984,65 +26985,6 @@
}
-package android.net.nsd {
-
- public final class NsdManager {
- method public void discoverServices(String, int, android.net.nsd.NsdManager.DiscoveryListener);
- method public void registerService(android.net.nsd.NsdServiceInfo, int, android.net.nsd.NsdManager.RegistrationListener);
- method public void resolveService(android.net.nsd.NsdServiceInfo, android.net.nsd.NsdManager.ResolveListener);
- method public void stopServiceDiscovery(android.net.nsd.NsdManager.DiscoveryListener);
- method public void unregisterService(android.net.nsd.NsdManager.RegistrationListener);
- field public static final String ACTION_NSD_STATE_CHANGED = "android.net.nsd.STATE_CHANGED";
- field public static final String EXTRA_NSD_STATE = "nsd_state";
- field public static final int FAILURE_ALREADY_ACTIVE = 3; // 0x3
- field public static final int FAILURE_INTERNAL_ERROR = 0; // 0x0
- field public static final int FAILURE_MAX_LIMIT = 4; // 0x4
- field public static final int NSD_STATE_DISABLED = 1; // 0x1
- field public static final int NSD_STATE_ENABLED = 2; // 0x2
- field public static final int PROTOCOL_DNS_SD = 1; // 0x1
- }
-
- public static interface NsdManager.DiscoveryListener {
- method public void onDiscoveryStarted(String);
- method public void onDiscoveryStopped(String);
- method public void onServiceFound(android.net.nsd.NsdServiceInfo);
- method public void onServiceLost(android.net.nsd.NsdServiceInfo);
- method public void onStartDiscoveryFailed(String, int);
- method public void onStopDiscoveryFailed(String, int);
- }
-
- public static interface NsdManager.RegistrationListener {
- method public void onRegistrationFailed(android.net.nsd.NsdServiceInfo, int);
- method public void onServiceRegistered(android.net.nsd.NsdServiceInfo);
- method public void onServiceUnregistered(android.net.nsd.NsdServiceInfo);
- method public void onUnregistrationFailed(android.net.nsd.NsdServiceInfo, int);
- }
-
- public static interface NsdManager.ResolveListener {
- method public void onResolveFailed(android.net.nsd.NsdServiceInfo, int);
- method public void onServiceResolved(android.net.nsd.NsdServiceInfo);
- }
-
- public final class NsdServiceInfo implements android.os.Parcelable {
- ctor public NsdServiceInfo();
- method public int describeContents();
- method public java.util.Map<java.lang.String,byte[]> getAttributes();
- method public java.net.InetAddress getHost();
- method public int getPort();
- method public String getServiceName();
- method public String getServiceType();
- method public void removeAttribute(String);
- method public void setAttribute(String, String);
- method public void setHost(java.net.InetAddress);
- method public void setPort(int);
- method public void setServiceName(String);
- method public void setServiceType(String);
- method public void writeToParcel(android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.net.nsd.NsdServiceInfo> CREATOR;
- }
-
-}
-
package android.net.rtp {
@Deprecated public class AudioCodec {
diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt
index 21e3cc3..445512e 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -56,6 +56,11 @@
public class NetworkStatsManager {
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) public void forceUpdate();
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) public void notifyNetworkStatus(@NonNull java.util.List<android.net.Network>, @NonNull java.util.List<android.net.NetworkStateSnapshot>, @Nullable String, @NonNull java.util.List<android.net.UnderlyingNetworkInfo>);
+ method @NonNull @WorkerThread public android.app.usage.NetworkStats queryDetailsForDevice(@NonNull android.net.NetworkTemplate, long, long);
+ method @NonNull @WorkerThread public android.app.usage.NetworkStats queryDetailsForUidTagState(@NonNull android.net.NetworkTemplate, long, long, int, int, int) throws java.lang.SecurityException;
+ method @NonNull @WorkerThread public android.app.usage.NetworkStats querySummary(@NonNull android.net.NetworkTemplate, long, long) throws java.lang.SecurityException;
+ method @NonNull @WorkerThread public android.app.usage.NetworkStats.Bucket querySummaryForDevice(@NonNull android.net.NetworkTemplate, long, long);
+ method @NonNull @WorkerThread public android.app.usage.NetworkStats queryTaggedSummary(@NonNull android.net.NetworkTemplate, long, long) throws java.lang.SecurityException;
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) public void setDefaultGlobalAlert(long);
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) public void setPollOnOpen(boolean);
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) public void setStatsProviderWarningAndLimitAsync(@NonNull String, long, long);
@@ -64,6 +69,14 @@
}
+package android.bluetooth {
+
+ public final class BluetoothPan implements android.bluetooth.BluetoothProfile {
+ method @Nullable @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED, android.Manifest.permission.TETHER_PRIVILEGED}) public android.net.TetheringManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull java.util.concurrent.Executor, @NonNull android.net.TetheringManager.TetheredInterfaceCallback);
+ }
+
+}
+
package android.content {
public abstract class ContentProvider implements android.content.ComponentCallbacks2 {
@@ -206,10 +219,6 @@
package android.net {
- public final class ConnectivityFrameworkInitializerTiramisu {
- method public static void registerServiceWrappers();
- }
-
public final class EthernetNetworkSpecifier extends android.net.NetworkSpecifier implements android.os.Parcelable {
ctor public EthernetNetworkSpecifier(@NonNull String);
method public int describeContents();
@@ -351,6 +360,7 @@
}
public class Process {
+ field public static final int NFC_UID = 1027; // 0x403
field public static final int VPN_UID = 1016; // 0x3f8
}
@@ -382,6 +392,16 @@
method @NonNull public java.util.List<android.content.ComponentName> getEnabledComponentOverrides(@NonNull String);
}
+ public final class Trace {
+ method public static void asyncTraceBegin(long, @NonNull String, int);
+ method public static void asyncTraceEnd(long, @NonNull String, int);
+ method public static boolean isTagEnabled(long);
+ method public static void traceBegin(long, @NonNull String);
+ method public static void traceCounter(long, @NonNull String, int);
+ method public static void traceEnd(long);
+ field public static final long TRACE_TAG_NETWORK = 2097152L; // 0x200000L
+ }
+
}
package android.os.storage {
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index a8ef47e..1fde724 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -1850,6 +1850,8 @@
}
public class NetworkStatsManager {
+ method @NonNull @RequiresPermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) public android.net.NetworkStats getMobileUidStats();
+ method @NonNull @RequiresPermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) public android.net.NetworkStats getWifiUidStats();
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_STATS_PROVIDER, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public void registerNetworkStatsProvider(@NonNull String, @NonNull android.net.netstats.provider.NetworkStatsProvider);
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_STATS_PROVIDER, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public void unregisterNetworkStatsProvider(@NonNull android.net.netstats.provider.NetworkStatsProvider);
}
@@ -2099,7 +2101,7 @@
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public java.util.List<android.bluetooth.BluetoothDevice> getConnectedDevices();
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getConnectionState(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean isTetheringOn();
- method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED, android.Manifest.permission.TETHER_PRIVILEGED}) public void setBluetoothTethering(boolean);
+ method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED, android.Manifest.permission.TETHER_PRIVILEGED}) public void setBluetoothTethering(boolean);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice, int);
field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.pan.profile.action.CONNECTION_STATE_CHANGED";
field public static final String ACTION_TETHERING_STATE_CHANGED = "android.bluetooth.action.TETHERING_STATE_CHANGED";
@@ -7523,11 +7525,12 @@
field public static final String PERMISSION_MAINLINE_NETWORK_STACK = "android.permission.MAINLINE_NETWORK_STACK";
}
- public final class NetworkStats implements android.os.Parcelable {
+ public final class NetworkStats implements java.lang.Iterable<android.net.NetworkStats.Entry> android.os.Parcelable {
ctor public NetworkStats(long, int);
method @NonNull public android.net.NetworkStats add(@NonNull android.net.NetworkStats);
method @NonNull public android.net.NetworkStats addEntry(@NonNull android.net.NetworkStats.Entry);
method public int describeContents();
+ method @NonNull public java.util.Iterator<android.net.NetworkStats.Entry> iterator();
method @NonNull public android.net.NetworkStats subtract(@NonNull android.net.NetworkStats);
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkStats> CREATOR;
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 9f37c48..2030571 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -129,6 +129,7 @@
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
@TestApi
+ @SystemApi(client = MODULE_LIBRARIES)
public static final int NFC_UID = 1027;
/**
diff --git a/core/java/android/os/Trace.java b/core/java/android/os/Trace.java
index d974e0c..6b869f1 100644
--- a/core/java/android/os/Trace.java
+++ b/core/java/android/os/Trace.java
@@ -16,7 +16,10 @@
package android.os;
+import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
+
import android.annotation.NonNull;
+import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import dalvik.annotation.optimization.CriticalNative;
@@ -90,6 +93,7 @@
/** @hide */
public static final long TRACE_TAG_DATABASE = 1L << 20;
/** @hide */
+ @SystemApi(client = MODULE_LIBRARIES)
public static final long TRACE_TAG_NETWORK = 1L << 21;
/** @hide */
public static final long TRACE_TAG_ADB = 1L << 22;
@@ -148,6 +152,7 @@
* @hide
*/
@UnsupportedAppUsage
+ @SystemApi(client = MODULE_LIBRARIES)
public static boolean isTagEnabled(long traceTag) {
long tags = nativeGetEnabledTags();
return (tags & traceTag) != 0;
@@ -163,7 +168,8 @@
* @hide
*/
@UnsupportedAppUsage
- public static void traceCounter(long traceTag, String counterName, int counterValue) {
+ @SystemApi(client = MODULE_LIBRARIES)
+ public static void traceCounter(long traceTag, @NonNull String counterName, int counterValue) {
if (isTagEnabled(traceTag)) {
nativeTraceCounter(traceTag, counterName, counterValue);
}
@@ -202,7 +208,8 @@
* @hide
*/
@UnsupportedAppUsage
- public static void traceBegin(long traceTag, String methodName) {
+ @SystemApi(client = MODULE_LIBRARIES)
+ public static void traceBegin(long traceTag, @NonNull String methodName) {
if (isTagEnabled(traceTag)) {
nativeTraceBegin(traceTag, methodName);
}
@@ -217,6 +224,7 @@
* @hide
*/
@UnsupportedAppUsage
+ @SystemApi(client = MODULE_LIBRARIES)
public static void traceEnd(long traceTag) {
if (isTagEnabled(traceTag)) {
nativeTraceEnd(traceTag);
@@ -237,7 +245,8 @@
* @hide
*/
@UnsupportedAppUsage
- public static void asyncTraceBegin(long traceTag, String methodName, int cookie) {
+ @SystemApi(client = MODULE_LIBRARIES)
+ public static void asyncTraceBegin(long traceTag, @NonNull String methodName, int cookie) {
if (isTagEnabled(traceTag)) {
nativeAsyncTraceBegin(traceTag, methodName, cookie);
}
@@ -255,7 +264,8 @@
* @hide
*/
@UnsupportedAppUsage
- public static void asyncTraceEnd(long traceTag, String methodName, int cookie) {
+ @SystemApi(client = MODULE_LIBRARIES)
+ public static void asyncTraceEnd(long traceTag, @NonNull String methodName, int cookie) {
if (isTagEnabled(traceTag)) {
nativeAsyncTraceEnd(traceTag, methodName, cookie);
}
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 270b5d6..8faffac 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -83,7 +83,6 @@
import android.util.LongSparseArray;
import android.util.LongSparseLongArray;
import android.util.MutableInt;
-import android.util.Pools;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.util.Slog;
@@ -136,9 +135,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Queue;
-import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
@@ -11522,8 +11519,6 @@
}
}
- private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
-
private final Object mWifiNetworkLock = new Object();
@GuardedBy("mWifiNetworkLock")
@@ -11541,13 +11536,15 @@
private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
@VisibleForTesting
- protected NetworkStats readNetworkStatsLocked(@NonNull NetworkStatsManager networkStatsManager,
- String[] ifaces) {
- Objects.requireNonNull(networkStatsManager);
- if (!ArrayUtils.isEmpty(ifaces)) {
- return networkStatsManager.getDetailedUidStats(Set.of(ifaces));
- }
- return null;
+ protected NetworkStats readMobileNetworkStatsLocked(
+ @NonNull NetworkStatsManager networkStatsManager) {
+ return networkStatsManager.getMobileUidStats();
+ }
+
+ @VisibleForTesting
+ protected NetworkStats readWifiNetworkStatsLocked(
+ @NonNull NetworkStatsManager networkStatsManager) {
+ return networkStatsManager.getWifiUidStats();
}
/**
@@ -11564,21 +11561,15 @@
// Grab a separate lock to acquire the network stats, which may do I/O.
NetworkStats delta = null;
synchronized (mWifiNetworkLock) {
- final NetworkStats latestStats = readNetworkStatsLocked(networkStatsManager,
- mWifiIfaces);
+ final NetworkStats latestStats = readWifiNetworkStatsLocked(networkStatsManager);
if (latestStats != null) {
- delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
- mNetworkStatsPool.acquire());
- mNetworkStatsPool.release(mLastWifiNetworkStats);
+ delta = latestStats.subtract(mLastWifiNetworkStats);
mLastWifiNetworkStats = latestStats;
}
}
synchronized (this) {
if (!mOnBatteryInternal || mIgnoreNextExternalStats) {
- if (delta != null) {
- mNetworkStatsPool.release(delta);
- }
if (mIgnoreNextExternalStats) {
// TODO: Strictly speaking, we should re-mark all 5 timers for each uid (and the
// global one) here like we do for display. But I'm not sure it's worth the
@@ -11685,7 +11676,6 @@
uidRunningMs, uidScanMs, uidBatchScanMs));
}
}
- mNetworkStatsPool.release(delta);
delta = null;
}
@@ -11932,21 +11922,15 @@
// Grab a separate lock to acquire the network stats, which may do I/O.
NetworkStats delta = null;
synchronized (mModemNetworkLock) {
- final NetworkStats latestStats = readNetworkStatsLocked(networkStatsManager,
- mModemIfaces);
+ final NetworkStats latestStats = readMobileNetworkStatsLocked(networkStatsManager);
if (latestStats != null) {
- delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
- mNetworkStatsPool.acquire());
- mNetworkStatsPool.release(mLastModemNetworkStats);
+ delta = latestStats.subtract(mLastModemNetworkStats);
mLastModemNetworkStats = latestStats;
}
}
synchronized (this) {
if (!mOnBatteryInternal || mIgnoreNextExternalStats) {
- if (delta != null) {
- mNetworkStatsPool.release(delta);
- }
return;
}
@@ -12148,7 +12132,6 @@
totalEstimatedConsumptionMah);
}
- mNetworkStatsPool.release(delta);
delta = null;
}
}
diff --git a/core/proto/OWNERS b/core/proto/OWNERS
index 931ef44..43d2439 100644
--- a/core/proto/OWNERS
+++ b/core/proto/OWNERS
@@ -17,7 +17,8 @@
per-file apphibernationservice.proto = file:/core/java/android/apphibernation/OWNERS
# Biometrics
-kchyn@google.com
+jaggies@google.com
+jbolinger@google.com
# Launcher
hyunyoungs@google.com
diff --git a/core/proto/android/service/netstats.proto b/core/proto/android/service/netstats.proto
index c8cdfdd..ba2b6d6b 100644
--- a/core/proto/android/service/netstats.proto
+++ b/core/proto/android/service/netstats.proto
@@ -17,15 +17,11 @@
syntax = "proto2";
package android.service;
-import "frameworks/base/core/proto/android/privacy.proto";
-
option java_multiple_files = true;
option java_outer_classname = "NetworkStatsServiceProto";
// Represents dumpsys from NetworkStatsService (netstats).
message NetworkStatsServiceDumpProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
repeated NetworkInterfaceProto active_interfaces = 1;
repeated NetworkInterfaceProto active_uid_interfaces = 2;
@@ -45,8 +41,6 @@
// Corresponds to NetworkStatsService.mActiveIfaces/mActiveUidIfaces.
message NetworkInterfaceProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
// Name of the network interface (eg: wlan).
optional string interface = 1;
@@ -55,26 +49,14 @@
// Corresponds to NetworkIdentitySet.
message NetworkIdentitySetProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
repeated NetworkIdentityProto identities = 1;
}
// Corresponds to NetworkIdentity.
message NetworkIdentityProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
// Constants from ConnectivityManager.TYPE_*.
optional int32 type = 1;
- // Full subscriber ID on eng builds. The IMSI is scrubbed on user & userdebug
- // builds to only include the info about the GSM network operator (the info
- // that uniquely identifies the subscriber is removed).
- optional string subscriber_id = 2 [ (android.privacy).dest = DEST_EXPLICIT ];
-
- // Name of the network (eg: MyWifi).
- optional string network_id = 3 [ (android.privacy).dest = DEST_EXPLICIT ];
-
optional bool roaming = 4;
optional bool metered = 5;
@@ -86,8 +68,6 @@
// Corresponds to NetworkStatsRecorder.
message NetworkStatsRecorderProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
optional int64 pending_total_bytes = 1;
optional NetworkStatsCollectionProto complete_history = 2;
@@ -95,15 +75,11 @@
// Corresponds to NetworkStatsCollection.
message NetworkStatsCollectionProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
repeated NetworkStatsCollectionStatsProto stats = 1;
}
// Corresponds to NetworkStatsCollection.mStats.
message NetworkStatsCollectionStatsProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
optional NetworkStatsCollectionKeyProto key = 1;
optional NetworkStatsHistoryProto history = 2;
@@ -111,8 +87,6 @@
// Corresponds to NetworkStatsCollection.Key.
message NetworkStatsCollectionKeyProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
optional NetworkIdentitySetProto identity = 1;
optional int32 uid = 2;
@@ -124,8 +98,6 @@
// Corresponds to NetworkStatsHistory.
message NetworkStatsHistoryProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
// Duration for this bucket in milliseconds.
optional int64 bucket_duration_ms = 1;
@@ -134,8 +106,6 @@
// Corresponds to each bucket in NetworkStatsHistory.
message NetworkStatsHistoryBucketProto {
- option (android.msg_privacy).dest = DEST_AUTOMATIC;
-
// Bucket start time in milliseconds since epoch.
optional int64 bucket_start_ms = 1;
diff --git a/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java b/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
index db0c934..8b14c62 100644
--- a/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
+++ b/core/tests/coretests/src/com/android/internal/os/MockBatteryStatsImpl.java
@@ -40,6 +40,7 @@
public class MockBatteryStatsImpl extends BatteryStatsImpl {
public BatteryStatsImpl.Clocks clocks;
public boolean mForceOnBattery;
+ // The mNetworkStats will be used for both wifi and mobile categories
private NetworkStats mNetworkStats;
MockBatteryStatsImpl(Clocks clocks) {
@@ -107,11 +108,16 @@
}
@Override
- protected NetworkStats readNetworkStatsLocked(@NonNull NetworkStatsManager networkStatsManager,
- String[] ifaces) {
+ protected NetworkStats readMobileNetworkStatsLocked(
+ @NonNull NetworkStatsManager networkStatsManager) {
return mNetworkStats;
}
+ @Override
+ protected NetworkStats readWifiNetworkStatsLocked(
+ @NonNull NetworkStatsManager networkStatsManager) {
+ return mNetworkStats;
+ }
public MockBatteryStatsImpl setPowerProfile(PowerProfile powerProfile) {
mPowerProfile = powerProfile;
return this;
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index f0e42c0..143b11f 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -242,7 +242,8 @@
AUDIO_FORMAT_SBC,
AUDIO_FORMAT_APTX,
AUDIO_FORMAT_APTX_HD,
- AUDIO_FORMAT_LDAC}
+ AUDIO_FORMAT_LDAC,
+ AUDIO_FORMAT_LC3}
)
@Retention(RetentionPolicy.SOURCE)
public @interface AudioFormatNativeEnumForBtCodec {}
@@ -274,6 +275,7 @@
case AUDIO_FORMAT_APTX: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX;
case AUDIO_FORMAT_APTX_HD: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD;
case AUDIO_FORMAT_LDAC: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC;
+ case AUDIO_FORMAT_LC3: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_LC3;
default:
Log.e(TAG, "Unknown audio format 0x" + Integer.toHexString(audioFormat)
+ " for conversion to BT codec");
@@ -314,6 +316,8 @@
return AudioSystem.AUDIO_FORMAT_APTX_HD;
case BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC:
return AudioSystem.AUDIO_FORMAT_LDAC;
+ case BluetoothCodecConfig.SOURCE_CODEC_TYPE_LC3:
+ return AudioSystem.AUDIO_FORMAT_LC3;
default:
Log.e(TAG, "Unknown BT codec 0x" + Integer.toHexString(btCodec)
+ " for conversion to audio format");
@@ -414,6 +418,8 @@
return "AUDIO_FORMAT_LHDC_LL";
case /* AUDIO_FORMAT_APTX_TWSP */ 0x2A000000:
return "AUDIO_FORMAT_APTX_TWSP";
+ case /* AUDIO_FORMAT_LC3 */ 0x2B000000:
+ return "AUDIO_FORMAT_LC3";
/* Aliases */
case /* AUDIO_FORMAT_PCM_16_BIT */ 0x1:
diff --git a/packages/ConnectivityT/framework-t/Android.bp b/packages/ConnectivityT/framework-t/Android.bp
index 90bb76a..d3d8bba 100644
--- a/packages/ConnectivityT/framework-t/Android.bp
+++ b/packages/ConnectivityT/framework-t/Android.bp
@@ -156,8 +156,18 @@
":framework-connectivity-ethernet-sources",
":framework-connectivity-ipsec-sources",
":framework-connectivity-netstats-sources",
+ ],
+ visibility: ["//frameworks/base"],
+}
+
+filegroup {
+ name: "framework-connectivity-tiramisu-updatable-sources",
+ srcs: [
":framework-connectivity-nsd-sources",
":framework-connectivity-tiramisu-internal-sources",
],
- visibility: ["//frameworks/base"],
+ visibility: [
+ "//frameworks/base",
+ "//packages/modules/Connectivity:__subpackages__",
+ ],
}
diff --git a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java
index d33666d..2b6570a 100644
--- a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java
+++ b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java
@@ -556,7 +556,7 @@
/**
* Collects history results for uid and resets history enumeration index.
*/
- void startHistoryEnumeration(int uid, int tag, int state) {
+ void startHistoryUidEnumeration(int uid, int tag, int state) {
mHistory = null;
try {
mHistory = mSession.getHistoryIntervalForUid(mTemplate, uid,
@@ -571,6 +571,20 @@
}
/**
+ * Collects history results for network and resets history enumeration index.
+ */
+ void startHistoryDeviceEnumeration() {
+ try {
+ mHistory = mSession.getHistoryIntervalForNetwork(
+ mTemplate, NetworkStatsHistory.FIELD_ALL, mStartTimeStamp, mEndTimeStamp);
+ } catch (RemoteException e) {
+ Log.w(TAG, e);
+ mHistory = null;
+ }
+ mEnumerationIndex = 0;
+ }
+
+ /**
* Starts uid enumeration for current user.
* @throws RemoteException
*/
diff --git a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java
index d00de36..683678a 100644
--- a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java
+++ b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java
@@ -17,6 +17,8 @@
package android.app.usage;
import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
+import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
+import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
import android.Manifest;
import android.annotation.NonNull;
@@ -55,7 +57,6 @@
import java.util.List;
import java.util.Objects;
-import java.util.Set;
/**
* Provides access to network usage history and statistics. Usage data is collected in
@@ -125,6 +126,19 @@
private final Context mContext;
private final INetworkStatsService mService;
+ /**
+ * Type constants for reading different types of Data Usage.
+ * @hide
+ */
+ // @SystemApi(client = MODULE_LIBRARIES)
+ public static final String PREFIX_DEV = "dev";
+ /** @hide */
+ public static final String PREFIX_XT = "xt";
+ /** @hide */
+ public static final String PREFIX_UID = "uid";
+ /** @hide */
+ public static final String PREFIX_UID_TAG = "uid_tag";
+
/** @hide */
public static final int FLAG_POLL_ON_OPEN = 1 << 0;
/** @hide */
@@ -211,9 +225,10 @@
*/
@NonNull
@WorkerThread
- // @SystemApi(client = MODULE_LIBRARIES)
+ @SystemApi(client = MODULE_LIBRARIES)
public Bucket querySummaryForDevice(@NonNull NetworkTemplate template,
long startTime, long endTime) {
+ Objects.requireNonNull(template);
try {
NetworkStats stats =
new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
@@ -385,10 +400,11 @@
* @hide
*/
@NonNull
- // @SystemApi(client = MODULE_LIBRARIES)
+ @SystemApi(client = MODULE_LIBRARIES)
@WorkerThread
public NetworkStats querySummary(@NonNull NetworkTemplate template, long startTime,
long endTime) throws SecurityException {
+ Objects.requireNonNull(template);
try {
NetworkStats result =
new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
@@ -418,10 +434,11 @@
* @hide
*/
@NonNull
- // @SystemApi(client = MODULE_LIBRARIES)
+ @SystemApi(client = MODULE_LIBRARIES)
@WorkerThread
public NetworkStats queryTaggedSummary(@NonNull NetworkTemplate template, long startTime,
long endTime) throws SecurityException {
+ Objects.requireNonNull(template);
try {
NetworkStats result =
new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
@@ -434,6 +451,43 @@
}
/**
+ * Query usage statistics details for networks matching a given {@link NetworkTemplate}.
+ *
+ * Result is not aggregated over time. This means buckets' start and
+ * end timestamps will be between 'startTime' and 'endTime' parameters.
+ * <p>Only includes buckets whose entire time period is included between
+ * startTime and endTime. Doesn't interpolate or return partial buckets.
+ * Since bucket length is in the order of hours, this
+ * method cannot be used to measure data usage on a fine grained time scale.
+ * This may take a long time, and apps should avoid calling this on their main thread.
+ *
+ * @param template Template used to match networks. See {@link NetworkTemplate}.
+ * @param startTime Start of period, in milliseconds since the Unix epoch, see
+ * {@link java.lang.System#currentTimeMillis}.
+ * @param endTime End of period, in milliseconds since the Unix epoch, see
+ * {@link java.lang.System#currentTimeMillis}.
+ * @return Statistics which is described above.
+ * @hide
+ */
+ @NonNull
+ @SystemApi(client = MODULE_LIBRARIES)
+ @WorkerThread
+ public NetworkStats queryDetailsForDevice(@NonNull NetworkTemplate template,
+ long startTime, long endTime) {
+ Objects.requireNonNull(template);
+ try {
+ final NetworkStats result =
+ new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
+ result.startHistoryDeviceEnumeration();
+ return result;
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+
+ return null; // To make the compiler happy.
+ }
+
+ /**
* Query network usage statistics details for a given uid.
* This may take a long time, and apps should avoid calling this on their main thread.
*
@@ -499,7 +553,8 @@
* @param endTime End of period. Defined in terms of "Unix time", see
* {@link java.lang.System#currentTimeMillis}.
* @param uid UID of app
- * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for no tags.
+ * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
+ * across all the tags.
* @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
* traffic from all states.
* @return Statistics object or null if an error happened during statistics collection.
@@ -514,21 +569,52 @@
return queryDetailsForUidTagState(template, startTime, endTime, uid, tag, state);
}
- /** @hide */
- public NetworkStats queryDetailsForUidTagState(NetworkTemplate template,
+ /**
+ * Query network usage statistics details for a given template, uid, tag, and state.
+ *
+ * Only usable for uids belonging to calling user. Result is not aggregated over time.
+ * This means buckets' start and end timestamps are going to be between 'startTime' and
+ * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag
+ * the same as the 'tag' parameter, and the state the same as the 'state' parameter.
+ * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL},
+ * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and
+ * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}.
+ * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't
+ * interpolate across partial buckets. Since bucket length is in the order of hours, this
+ * method cannot be used to measure data usage on a fine grained time scale.
+ * This may take a long time, and apps should avoid calling this on their main thread.
+ *
+ * @param template Template used to match networks. See {@link NetworkTemplate}.
+ * @param startTime Start of period, in milliseconds since the Unix epoch, see
+ * {@link java.lang.System#currentTimeMillis}.
+ * @param endTime End of period, in milliseconds since the Unix epoch, see
+ * {@link java.lang.System#currentTimeMillis}.
+ * @param uid UID of app
+ * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data
+ * across all the tags.
+ * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate
+ * traffic from all states.
+ * @return Statistics which is described above.
+ * @hide
+ */
+ @NonNull
+ @SystemApi(client = MODULE_LIBRARIES)
+ @WorkerThread
+ public NetworkStats queryDetailsForUidTagState(@NonNull NetworkTemplate template,
long startTime, long endTime, int uid, int tag, int state) throws SecurityException {
-
- NetworkStats result;
+ Objects.requireNonNull(template);
try {
- result = new NetworkStats(mContext, template, mFlags, startTime, endTime, mService);
- result.startHistoryEnumeration(uid, tag, state);
+ final NetworkStats result = new NetworkStats(
+ mContext, template, mFlags, startTime, endTime, mService);
+ result.startHistoryUidEnumeration(uid, tag, state);
+ return result;
} catch (RemoteException e) {
Log.e(TAG, "Error while querying stats for uid=" + uid + " tag=" + tag
+ " state=" + state, e);
- return null;
+ e.rethrowFromSystemServer();
}
- return result;
+ return null; // To make the compiler happy.
}
/**
@@ -585,26 +671,49 @@
}
/**
- * Query realtime network usage statistics details with interfaces constrains.
- * Return snapshot of current UID statistics, including any {@link TrafficStats#UID_TETHERING},
- * video calling data usage and count of network operations that set by
- * {@link TrafficStats#incrementOperationCount}. The returned data doesn't include any
- * statistics that is reported by {@link NetworkStatsProvider}.
+ * Query realtime mobile network usage statistics.
*
- * @param requiredIfaces A list of interfaces the stats should be restricted to, or
- * {@link NetworkStats#INTERFACES_ALL}.
+ * Return a snapshot of current UID network statistics, as it applies
+ * to the mobile radios of the device. The snapshot will include any
+ * tethering traffic, video calling data usage and count of
+ * network operations set by {@link TrafficStats#incrementOperationCount}
+ * made over a mobile radio.
+ * The snapshot will not include any statistics that cannot be seen by
+ * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
*
* @hide
*/
- //@SystemApi
+ @SystemApi
@RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
- @NonNull public android.net.NetworkStats getDetailedUidStats(
- @NonNull Set<String> requiredIfaces) {
- Objects.requireNonNull(requiredIfaces, "requiredIfaces cannot be null");
+ @NonNull public android.net.NetworkStats getMobileUidStats() {
try {
- return mService.getDetailedUidStats(requiredIfaces.toArray(new String[0]));
+ return mService.getUidStatsForTransport(TRANSPORT_CELLULAR);
} catch (RemoteException e) {
- if (DBG) Log.d(TAG, "Remote exception when get detailed uid stats");
+ if (DBG) Log.d(TAG, "Remote exception when get Mobile uid stats");
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Query realtime Wi-Fi network usage statistics.
+ *
+ * Return a snapshot of current UID network statistics, as it applies
+ * to the Wi-Fi radios of the device. The snapshot will include any
+ * tethering traffic, video calling data usage and count of
+ * network operations set by {@link TrafficStats#incrementOperationCount}
+ * made over a Wi-Fi radio.
+ * The snapshot will not include any statistics that cannot be seen by
+ * the kernel, e.g. statistics reported by {@link NetworkStatsProvider}s.
+ *
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
+ @NonNull public android.net.NetworkStats getWifiUidStats() {
+ try {
+ return mService.getUidStatsForTransport(TRANSPORT_WIFI);
+ } catch (RemoteException e) {
+ if (DBG) Log.d(TAG, "Remote exception when get WiFi uid stats");
throw e.rethrowFromSystemServer();
}
}
diff --git a/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsService.aidl b/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsService.aidl
index a4babb5..da0aa99 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsService.aidl
+++ b/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsService.aidl
@@ -49,14 +49,8 @@
@UnsupportedAppUsage
NetworkStats getDataLayerSnapshotForUid(int uid);
- /** Get a detailed snapshot of stats since boot for all UIDs.
- *
- * <p>Results will not always be limited to stats on requiredIfaces when specified: stats for
- * interfaces stacked on the specified interfaces, or for interfaces on which the specified
- * interfaces are stacked on, will also be included.
- * @param requiredIfaces Interface names to get data for, or {@link NetworkStats#INTERFACES_ALL}.
- */
- NetworkStats getDetailedUidStats(in String[] requiredIfaces);
+ /** Get the transport NetworkStats for all UIDs since boot. */
+ NetworkStats getUidStatsForTransport(int transport);
/** Return set of any ifaces associated with mobile networks since boot. */
@UnsupportedAppUsage
diff --git a/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsSession.aidl b/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsSession.aidl
index babe0bf..ab70be8 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsSession.aidl
+++ b/packages/ConnectivityT/framework-t/src/android/net/INetworkStatsSession.aidl
@@ -32,6 +32,11 @@
/** Return historical network layer stats for traffic that matches template. */
@UnsupportedAppUsage
NetworkStatsHistory getHistoryForNetwork(in NetworkTemplate template, int fields);
+ /**
+ * Return historical network layer stats for traffic that matches template, start and end
+ * timestamp.
+ */
+ NetworkStatsHistory getHistoryIntervalForNetwork(in NetworkTemplate template, int fields, long start, long end);
/**
* Return network layer usage summary per UID for traffic that matches template.
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentity.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentity.java
index 8f1115e..9b9d38a 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentity.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentity.java
@@ -17,17 +17,24 @@
package android.net;
import static android.net.ConnectivityManager.TYPE_WIFI;
+import static android.net.NetworkTemplate.NETWORK_TYPE_ALL;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.service.NetworkIdentityProto;
-import android.telephony.Annotation.NetworkType;
+import android.telephony.Annotation;
+import android.telephony.TelephonyManager;
import android.util.proto.ProtoOutputStream;
import com.android.net.module.util.NetworkCapabilitiesUtils;
import com.android.net.module.util.NetworkIdentityUtils;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Objects;
@@ -37,11 +44,24 @@
*
* @hide
*/
+// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkIdentity implements Comparable<NetworkIdentity> {
private static final String TAG = "NetworkIdentity";
+ /** @hide */
+ // TODO: Remove this after migrating all callers to use
+ // {@link NetworkTemplate#NETWORK_TYPE_ALL} instead.
public static final int SUBTYPE_COMBINED = -1;
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = { "OEM_MANAGED_" }, value = {
+ NetworkTemplate.OEM_MANAGED_NO,
+ NetworkTemplate.OEM_MANAGED_PAID,
+ NetworkTemplate.OEM_MANAGED_PRIVATE
+ })
+ public @interface OemManaged{}
+
/**
* Network has no {@code NetworkCapabilities#NET_CAPABILITY_OEM_*}.
* @hide
@@ -59,21 +79,22 @@
public static final int OEM_PRIVATE = 0x2;
final int mType;
- final int mSubType;
+ final int mRatType;
final String mSubscriberId;
- final String mNetworkId;
+ final String mWifiNetworkKey;
final boolean mRoaming;
final boolean mMetered;
final boolean mDefaultNetwork;
final int mOemManaged;
+ /** @hide */
public NetworkIdentity(
- int type, int subType, String subscriberId, String networkId, boolean roaming,
- boolean metered, boolean defaultNetwork, int oemManaged) {
+ int type, int ratType, @Nullable String subscriberId, @Nullable String wifiNetworkKey,
+ boolean roaming, boolean metered, boolean defaultNetwork, int oemManaged) {
mType = type;
- mSubType = subType;
+ mRatType = ratType;
mSubscriberId = subscriberId;
- mNetworkId = networkId;
+ mWifiNetworkKey = wifiNetworkKey;
mRoaming = roaming;
mMetered = metered;
mDefaultNetwork = defaultNetwork;
@@ -82,7 +103,7 @@
@Override
public int hashCode() {
- return Objects.hash(mType, mSubType, mSubscriberId, mNetworkId, mRoaming, mMetered,
+ return Objects.hash(mType, mRatType, mSubscriberId, mWifiNetworkKey, mRoaming, mMetered,
mDefaultNetwork, mOemManaged);
}
@@ -90,9 +111,9 @@
public boolean equals(@Nullable Object obj) {
if (obj instanceof NetworkIdentity) {
final NetworkIdentity ident = (NetworkIdentity) obj;
- return mType == ident.mType && mSubType == ident.mSubType && mRoaming == ident.mRoaming
+ return mType == ident.mType && mRatType == ident.mRatType && mRoaming == ident.mRoaming
&& Objects.equals(mSubscriberId, ident.mSubscriberId)
- && Objects.equals(mNetworkId, ident.mNetworkId)
+ && Objects.equals(mWifiNetworkKey, ident.mWifiNetworkKey)
&& mMetered == ident.mMetered
&& mDefaultNetwork == ident.mDefaultNetwork
&& mOemManaged == ident.mOemManaged;
@@ -104,18 +125,18 @@
public String toString() {
final StringBuilder builder = new StringBuilder("{");
builder.append("type=").append(mType);
- builder.append(", subType=");
- if (mSubType == SUBTYPE_COMBINED) {
+ builder.append(", ratType=");
+ if (mRatType == NETWORK_TYPE_ALL) {
builder.append("COMBINED");
} else {
- builder.append(mSubType);
+ builder.append(mRatType);
}
if (mSubscriberId != null) {
builder.append(", subscriberId=")
.append(NetworkIdentityUtils.scrubSubscriberId(mSubscriberId));
}
- if (mNetworkId != null) {
- builder.append(", networkId=").append(mNetworkId);
+ if (mWifiNetworkKey != null) {
+ builder.append(", wifiNetworkKey=").append(mWifiNetworkKey);
}
if (mRoaming) {
builder.append(", ROAMING");
@@ -153,18 +174,14 @@
}
}
+ /** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag);
proto.write(NetworkIdentityProto.TYPE, mType);
- // Not dumping mSubType, subtypes are no longer supported.
+ // TODO: dump mRatType as well.
- if (mSubscriberId != null) {
- proto.write(NetworkIdentityProto.SUBSCRIBER_ID,
- NetworkIdentityUtils.scrubSubscriberId(mSubscriberId));
- }
- proto.write(NetworkIdentityProto.NETWORK_ID, mNetworkId);
proto.write(NetworkIdentityProto.ROAMING, mRoaming);
proto.write(NetworkIdentityProto.METERED, mMetered);
proto.write(NetworkIdentityProto.DEFAULT_NETWORK, mDefaultNetwork);
@@ -173,77 +190,95 @@
proto.end(start);
}
+ /** Get the network type of this instance. */
public int getType() {
return mType;
}
- public int getSubType() {
- return mSubType;
+ /** Get the Radio Access Technology(RAT) type of this instance. */
+ public int getRatType() {
+ return mRatType;
}
+ /** Get the Subscriber Id of this instance. */
+ @Nullable
public String getSubscriberId() {
return mSubscriberId;
}
- public String getNetworkId() {
- return mNetworkId;
+ /** Get the Wifi Network Key of this instance. See {@link WifiInfo#getCurrentNetworkKey()}. */
+ @Nullable
+ public String getWifiNetworkKey() {
+ return mWifiNetworkKey;
}
+ /** @hide */
+ // TODO: Remove this function after all callers are removed.
public boolean getRoaming() {
return mRoaming;
}
+ /** Return the roaming status of this instance. */
+ public boolean isRoaming() {
+ return mRoaming;
+ }
+
+ /** @hide */
+ // TODO: Remove this function after all callers are removed.
public boolean getMetered() {
return mMetered;
}
+ /** Return the meteredness of this instance. */
+ public boolean isMetered() {
+ return mMetered;
+ }
+
+ /** @hide */
+ // TODO: Remove this function after all callers are removed.
public boolean getDefaultNetwork() {
return mDefaultNetwork;
}
+ /** Return the default network status of this instance. */
+ public boolean isDefaultNetwork() {
+ return mDefaultNetwork;
+ }
+
+ /** Get the OEM managed type of this instance. */
public int getOemManaged() {
return mOemManaged;
}
/**
- * Build a {@link NetworkIdentity} from the given {@link NetworkStateSnapshot} and
- * {@code subType}, assuming that any mobile networks are using the current IMSI.
- * The subType if applicable, should be set as one of the TelephonyManager.NETWORK_TYPE_*
- * constants, or {@link android.telephony.TelephonyManager#NETWORK_TYPE_UNKNOWN} if not.
+ * Assemble a {@link NetworkIdentity} from the passed arguments.
+ *
+ * This methods builds an identity based on the capabilities of the network in the
+ * snapshot and other passed arguments. The identity is used as a key to record data usage.
+ *
+ * @param snapshot the snapshot of network state. See {@link NetworkStateSnapshot}.
+ * @param defaultNetwork whether the network is a default network.
+ * @param ratType the Radio Access Technology(RAT) type of the network. Or
+ * {@link TelephonyManager#NETWORK_TYPE_UNKNOWN} if not applicable.
+ * See {@code TelephonyManager.NETWORK_TYPE_*}.
+ * @hide
+ * @deprecated See {@link NetworkIdentity#Builder}.
*/
+ // TODO: Remove this after all callers are migrated to use new Api.
+ @Deprecated
+ @NonNull
public static NetworkIdentity buildNetworkIdentity(Context context,
- NetworkStateSnapshot snapshot, boolean defaultNetwork, @NetworkType int subType) {
- final int legacyType = snapshot.getLegacyType();
-
- final String subscriberId = snapshot.getSubscriberId();
- String networkId = null;
- boolean roaming = !snapshot.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
- boolean metered = !(snapshot.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
- || snapshot.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
-
- final int oemManaged = getOemBitfield(snapshot.getNetworkCapabilities());
-
- if (legacyType == TYPE_WIFI) {
- final TransportInfo transportInfo = snapshot.getNetworkCapabilities()
- .getTransportInfo();
- if (transportInfo instanceof WifiInfo) {
- final WifiInfo info = (WifiInfo) transportInfo;
- networkId = info != null ? info.getCurrentNetworkKey() : null;
- }
- }
-
- return new NetworkIdentity(legacyType, subType, subscriberId, networkId, roaming, metered,
- defaultNetwork, oemManaged);
+ @NonNull NetworkStateSnapshot snapshot,
+ boolean defaultNetwork, @Annotation.NetworkType int ratType) {
+ return new NetworkIdentity.Builder().setNetworkStateSnapshot(snapshot)
+ .setDefaultNetwork(defaultNetwork).setRatType(ratType).build();
}
/**
* Builds a bitfield of {@code NetworkIdentity.OEM_*} based on {@link NetworkCapabilities}.
* @hide
*/
- public static int getOemBitfield(NetworkCapabilities nc) {
+ public static int getOemBitfield(@NonNull NetworkCapabilities nc) {
int oemManaged = OEM_NONE;
if (nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_OEM_PAID)) {
@@ -257,16 +292,17 @@
}
@Override
- public int compareTo(NetworkIdentity another) {
+ public int compareTo(@NonNull NetworkIdentity another) {
+ Objects.requireNonNull(another);
int res = Integer.compare(mType, another.mType);
if (res == 0) {
- res = Integer.compare(mSubType, another.mSubType);
+ res = Integer.compare(mRatType, another.mRatType);
}
if (res == 0 && mSubscriberId != null && another.mSubscriberId != null) {
res = mSubscriberId.compareTo(another.mSubscriberId);
}
- if (res == 0 && mNetworkId != null && another.mNetworkId != null) {
- res = mNetworkId.compareTo(another.mNetworkId);
+ if (res == 0 && mWifiNetworkKey != null && another.mWifiNetworkKey != null) {
+ res = mWifiNetworkKey.compareTo(another.mWifiNetworkKey);
}
if (res == 0) {
res = Boolean.compare(mRoaming, another.mRoaming);
@@ -282,4 +318,192 @@
}
return res;
}
+
+ /**
+ * Builder class for {@link NetworkIdentity}.
+ */
+ public static final class Builder {
+ private int mType;
+ private int mRatType;
+ private String mSubscriberId;
+ private String mWifiNetworkKey;
+ private boolean mRoaming;
+ private boolean mMetered;
+ private boolean mDefaultNetwork;
+ private int mOemManaged;
+
+ /**
+ * Creates a new Builder.
+ */
+ public Builder() {
+ // Initialize with default values. Will be overwritten by setters.
+ mType = ConnectivityManager.TYPE_NONE;
+ mRatType = NetworkTemplate.NETWORK_TYPE_ALL;
+ mSubscriberId = null;
+ mWifiNetworkKey = null;
+ mRoaming = false;
+ mMetered = false;
+ mDefaultNetwork = false;
+ mOemManaged = NetworkTemplate.OEM_MANAGED_NO;
+ }
+
+ /**
+ * Add an {@link NetworkStateSnapshot} into the {@link NetworkIdentity} instance.
+ * This is to read roaming, metered, wifikey... from the snapshot for convenience.
+ *
+ * @param snapshot The target {@link NetworkStateSnapshot} object.
+ * @return The builder object.
+ */
+ @SuppressLint("MissingGetterMatchingBuilder")
+ @NonNull
+ public Builder setNetworkStateSnapshot(@NonNull NetworkStateSnapshot snapshot) {
+ setType(snapshot.getLegacyType());
+
+ setSubscriberId(snapshot.getSubscriberId());
+ setRoaming(!snapshot.getNetworkCapabilities().hasCapability(
+ NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING));
+ setMetered(!(snapshot.getNetworkCapabilities().hasCapability(
+ NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
+ || snapshot.getNetworkCapabilities().hasCapability(
+ NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED)));
+
+ setOemManaged(getOemBitfield(snapshot.getNetworkCapabilities()));
+
+ if (mType == TYPE_WIFI) {
+ final TransportInfo transportInfo = snapshot.getNetworkCapabilities()
+ .getTransportInfo();
+ if (transportInfo instanceof WifiInfo) {
+ final WifiInfo info = (WifiInfo) transportInfo;
+ if (info != null) {
+ setWifiNetworkKey(info.getCurrentNetworkKey());
+ }
+ }
+ }
+ return this;
+ }
+
+ /**
+ * Set the network type of the network.
+ *
+ * @param type the network type. See {@link ConnectivityManager#TYPE_*}.
+ *
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setType(int type) {
+ mType = type;
+ return this;
+ }
+
+ /**
+ * Set the Radio Access Technology(RAT) type of the network.
+ *
+ * @param ratType the Radio Access Technology(RAT) type if applicable. See
+ * {@code TelephonyManager.NETWORK_TYPE_*}.
+ *
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setRatType(@Annotation.NetworkType int ratType) {
+ mRatType = ratType;
+ return this;
+ }
+
+ /**
+ * Clear the Radio Access Technology(RAT) type of the network.
+ *
+ * @return this builder.
+ */
+ @NonNull
+ public Builder clearRatType() {
+ mRatType = NetworkTemplate.NETWORK_TYPE_ALL;
+ return this;
+ }
+
+ /**
+ * Set the Subscriber Id.
+ *
+ * @param subscriberId the Subscriber Id of the network. Or null if not applicable.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setSubscriberId(@Nullable String subscriberId) {
+ mSubscriberId = subscriberId;
+ return this;
+ }
+
+ /**
+ * Set the Wifi Network Key.
+ *
+ * @param wifiNetworkKey Wifi Network Key of the network,
+ * see {@link WifiInfo#getCurrentNetworkKey()}.
+ * Or null if not applicable.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setWifiNetworkKey(@Nullable String wifiNetworkKey) {
+ mWifiNetworkKey = wifiNetworkKey;
+ return this;
+ }
+
+ /**
+ * Set the roaming.
+ *
+ * @param roaming the roaming status of the network.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setRoaming(boolean roaming) {
+ mRoaming = roaming;
+ return this;
+ }
+
+ /**
+ * Set the meteredness.
+ *
+ * @param metered the meteredness of the network.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setMetered(boolean metered) {
+ mMetered = metered;
+ return this;
+ }
+
+ /**
+ * Set the default network status.
+ *
+ * @param defaultNetwork the default network status of the network.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setDefaultNetwork(boolean defaultNetwork) {
+ mDefaultNetwork = defaultNetwork;
+ return this;
+ }
+
+ /**
+ * Set the OEM managed type.
+ *
+ * @param oemManaged Type of OEM managed network or unmanaged networks.
+ * See {@code NetworkTemplate#OEM_MANAGED_*}.
+ * @return this builder.
+ */
+ @NonNull
+ public Builder setOemManaged(@OemManaged int oemManaged) {
+ mOemManaged = oemManaged;
+ return this;
+ }
+
+ /**
+ * Builds the instance of the {@link NetworkIdentity}.
+ *
+ * @return the built instance of {@link NetworkIdentity}.
+ */
+ @NonNull
+ public NetworkIdentity build() {
+ return new NetworkIdentity(mType, mRatType, mSubscriberId, mWifiNetworkKey,
+ mRoaming, mMetered, mDefaultNetwork, mOemManaged);
+ }
+ }
}
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentitySet.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentitySet.java
index abbebef..041f070 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentitySet.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkIdentitySet.java
@@ -18,6 +18,7 @@
import static android.net.ConnectivityManager.TYPE_MOBILE;
+import android.annotation.NonNull;
import android.service.NetworkIdentitySetProto;
import android.util.proto.ProtoOutputStream;
@@ -25,6 +26,7 @@
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashSet;
+import java.util.Objects;
/**
* Identity of a {@code iface}, defined by the set of {@link NetworkIdentity}
@@ -32,6 +34,7 @@
*
* @hide
*/
+// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkIdentitySet extends HashSet<NetworkIdentity> implements
Comparable<NetworkIdentitySet> {
private static final int VERSION_INIT = 1;
@@ -41,9 +44,14 @@
private static final int VERSION_ADD_DEFAULT_NETWORK = 5;
private static final int VERSION_ADD_OEM_MANAGED_NETWORK = 6;
+ /**
+ * Construct a {@link NetworkIdentitySet} object.
+ */
public NetworkIdentitySet() {
+ super();
}
+ /** @hide */
public NetworkIdentitySet(DataInput in) throws IOException {
final int version = in.readInt();
final int size = in.readInt();
@@ -52,7 +60,7 @@
final int ignored = in.readInt();
}
final int type = in.readInt();
- final int subType = in.readInt();
+ final int ratType = in.readInt();
final String subscriberId = readOptionalString(in);
final String networkId;
if (version >= VERSION_ADD_NETWORK_ID) {
@@ -91,63 +99,73 @@
oemNetCapabilities = NetworkIdentity.OEM_NONE;
}
- add(new NetworkIdentity(type, subType, subscriberId, networkId, roaming, metered,
+ add(new NetworkIdentity(type, ratType, subscriberId, networkId, roaming, metered,
defaultNetwork, oemNetCapabilities));
}
}
/**
* Method to serialize this object into a {@code DataOutput}.
+ * @hide
*/
public void writeToStream(DataOutput out) throws IOException {
out.writeInt(VERSION_ADD_OEM_MANAGED_NETWORK);
out.writeInt(size());
for (NetworkIdentity ident : this) {
out.writeInt(ident.getType());
- out.writeInt(ident.getSubType());
+ out.writeInt(ident.getRatType());
writeOptionalString(out, ident.getSubscriberId());
- writeOptionalString(out, ident.getNetworkId());
- out.writeBoolean(ident.getRoaming());
- out.writeBoolean(ident.getMetered());
- out.writeBoolean(ident.getDefaultNetwork());
+ writeOptionalString(out, ident.getWifiNetworkKey());
+ out.writeBoolean(ident.isRoaming());
+ out.writeBoolean(ident.isMetered());
+ out.writeBoolean(ident.isDefaultNetwork());
out.writeInt(ident.getOemManaged());
}
}
- /** @return whether any {@link NetworkIdentity} in this set is considered metered. */
+ /**
+ * @return whether any {@link NetworkIdentity} in this set is considered metered.
+ * @hide
+ */
public boolean isAnyMemberMetered() {
if (isEmpty()) {
return false;
}
for (NetworkIdentity ident : this) {
- if (ident.getMetered()) {
+ if (ident.isMetered()) {
return true;
}
}
return false;
}
- /** @return whether any {@link NetworkIdentity} in this set is considered roaming. */
+ /**
+ * @return whether any {@link NetworkIdentity} in this set is considered roaming.
+ * @hide
+ */
public boolean isAnyMemberRoaming() {
if (isEmpty()) {
return false;
}
for (NetworkIdentity ident : this) {
- if (ident.getRoaming()) {
+ if (ident.isRoaming()) {
return true;
}
}
return false;
}
- /** @return whether any {@link NetworkIdentity} in this set is considered on the default
- network. */
+ /**
+ * @return whether any {@link NetworkIdentity} in this set is considered on the default
+ * network.
+ * @hide
+ */
public boolean areAllMembersOnDefaultNetwork() {
if (isEmpty()) {
return true;
}
for (NetworkIdentity ident : this) {
- if (!ident.getDefaultNetwork()) {
+ if (!ident.isDefaultNetwork()) {
return false;
}
}
@@ -172,7 +190,8 @@
}
@Override
- public int compareTo(NetworkIdentitySet another) {
+ public int compareTo(@NonNull NetworkIdentitySet another) {
+ Objects.requireNonNull(another);
if (isEmpty()) return -1;
if (another.isEmpty()) return 1;
@@ -183,6 +202,7 @@
/**
* Method to dump this object into proto debug file.
+ * @hide
*/
public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag);
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java
index 9d532e7..9175809 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java
@@ -41,6 +41,7 @@
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -57,7 +58,7 @@
*/
// @NotThreadSafe
@SystemApi
-public final class NetworkStats implements Parcelable {
+public final class NetworkStats implements Parcelable, Iterable<NetworkStats.Entry> {
private static final String TAG = "NetworkStats";
/**
@@ -678,6 +679,35 @@
}
/**
+ * Iterate over Entry objects.
+ *
+ * Return an iterator of this object that will iterate through all contained Entry objects.
+ *
+ * This iterator does not support concurrent modification and makes no guarantee of fail-fast
+ * behavior. If any method that can mutate the contents of this object is called while
+ * iteration is in progress, either inside the loop or in another thread, then behavior is
+ * undefined.
+ * The remove() method is not implemented and will throw UnsupportedOperationException.
+ * @hide
+ */
+ @SystemApi
+ @NonNull public Iterator<Entry> iterator() {
+ return new Iterator<Entry>() {
+ int mIndex = 0;
+
+ @Override
+ public boolean hasNext() {
+ return mIndex < size;
+ }
+
+ @Override
+ public Entry next() {
+ return getValues(mIndex++, null);
+ }
+ };
+ }
+
+ /**
* Return specific stats entry.
* @hide
*/
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsCollection.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsCollection.java
index 9f9d73f..f169fed 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsCollection.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsCollection.java
@@ -32,6 +32,8 @@
import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.os.Binder;
import android.service.NetworkStatsCollectionKeyProto;
import android.service.NetworkStatsCollectionProto;
@@ -77,6 +79,7 @@
*
* @hide
*/
+// @SystemApi(client = MODULE_LIBRARIES)
public class NetworkStatsCollection implements FileRotator.Reader, FileRotator.Writer {
private static final String TAG = NetworkStatsCollection.class.getSimpleName();
/** File header magic number: "ANET" */
@@ -100,15 +103,23 @@
private long mTotalBytes;
private boolean mDirty;
+ /**
+ * Construct a {@link NetworkStatsCollection} object.
+ *
+ * @param bucketDuration duration of the buckets in this object, in milliseconds.
+ * @hide
+ */
public NetworkStatsCollection(long bucketDuration) {
mBucketDuration = bucketDuration;
reset();
}
+ /** @hide */
public void clear() {
reset();
}
+ /** @hide */
public void reset() {
mStats.clear();
mStartMillis = Long.MAX_VALUE;
@@ -117,6 +128,7 @@
mDirty = false;
}
+ /** @hide */
public long getStartMillis() {
return mStartMillis;
}
@@ -124,6 +136,7 @@
/**
* Return first atomic bucket in this collection, which is more conservative
* than {@link #mStartMillis}.
+ * @hide
*/
public long getFirstAtomicBucketMillis() {
if (mStartMillis == Long.MAX_VALUE) {
@@ -133,26 +146,32 @@
}
}
+ /** @hide */
public long getEndMillis() {
return mEndMillis;
}
+ /** @hide */
public long getTotalBytes() {
return mTotalBytes;
}
+ /** @hide */
public boolean isDirty() {
return mDirty;
}
+ /** @hide */
public void clearDirty() {
mDirty = false;
}
+ /** @hide */
public boolean isEmpty() {
return mStartMillis == Long.MAX_VALUE && mEndMillis == Long.MIN_VALUE;
}
+ /** @hide */
@VisibleForTesting
public long roundUp(long time) {
if (time == Long.MIN_VALUE || time == Long.MAX_VALUE
@@ -168,6 +187,7 @@
}
}
+ /** @hide */
@VisibleForTesting
public long roundDown(long time) {
if (time == Long.MIN_VALUE || time == Long.MAX_VALUE
@@ -182,10 +202,12 @@
}
}
+ /** @hide */
public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel) {
return getRelevantUids(accessLevel, Binder.getCallingUid());
}
+ /** @hide */
public int[] getRelevantUids(@NetworkStatsAccess.Level int accessLevel,
final int callerUid) {
final ArrayList<Integer> uids = new ArrayList<>();
@@ -206,6 +228,7 @@
/**
* Combine all {@link NetworkStatsHistory} in this collection which match
* the requested parameters.
+ * @hide
*/
public NetworkStatsHistory getHistory(NetworkTemplate template, SubscriptionPlan augmentPlan,
int uid, int set, int tag, int fields, long start, long end,
@@ -331,6 +354,7 @@
* @param end - end of the range, timestamp in milliseconds since the epoch.
* @param accessLevel - caller access level.
* @param callerUid - caller UID.
+ * @hide
*/
public NetworkStats getSummary(NetworkTemplate template, long start, long end,
@NetworkStatsAccess.Level int accessLevel, int callerUid) {
@@ -377,6 +401,7 @@
/**
* Record given {@link android.net.NetworkStats.Entry} into this collection.
+ * @hide
*/
public void recordData(NetworkIdentitySet ident, int uid, int set, int tag, long start,
long end, NetworkStats.Entry entry) {
@@ -387,8 +412,12 @@
/**
* Record given {@link NetworkStatsHistory} into this collection.
+ *
+ * @hide
*/
- private void recordHistory(Key key, NetworkStatsHistory history) {
+ public void recordHistory(@NonNull Key key, @NonNull NetworkStatsHistory history) {
+ Objects.requireNonNull(key);
+ Objects.requireNonNull(history);
if (history.size() == 0) return;
noteRecordedHistory(history.getStart(), history.getEnd(), history.getTotalBytes());
@@ -403,8 +432,11 @@
/**
* Record all {@link NetworkStatsHistory} contained in the given collection
* into this collection.
+ *
+ * @hide
*/
- public void recordCollection(NetworkStatsCollection another) {
+ public void recordCollection(@NonNull NetworkStatsCollection another) {
+ Objects.requireNonNull(another);
for (int i = 0; i < another.mStats.size(); i++) {
final Key key = another.mStats.keyAt(i);
final NetworkStatsHistory value = another.mStats.valueAt(i);
@@ -433,6 +465,7 @@
}
}
+ /** @hide */
@Override
public void read(InputStream in) throws IOException {
read((DataInput) new DataInputStream(in));
@@ -472,6 +505,7 @@
}
}
+ /** @hide */
@Override
public void write(OutputStream out) throws IOException {
write((DataOutput) new DataOutputStream(out));
@@ -514,6 +548,7 @@
* See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}.
*
* @deprecated
+ * @hide
*/
@Deprecated
public void readLegacyNetwork(File file) throws IOException {
@@ -559,6 +594,7 @@
* See {@code NetworkStatsService#maybeUpgradeLegacyStatsLocked}.
*
* @deprecated
+ * @hide
*/
@Deprecated
public void readLegacyUid(File file, boolean onlyTags) throws IOException {
@@ -629,6 +665,7 @@
* Remove any {@link NetworkStatsHistory} attributed to the requested UID,
* moving any {@link NetworkStats#TAG_NONE} series to
* {@link TrafficStats#UID_REMOVED}.
+ * @hide
*/
public void removeUids(int[] uids) {
final ArrayList<Key> knownKeys = new ArrayList<>();
@@ -669,6 +706,7 @@
return keys;
}
+ /** @hide */
public void dump(IndentingPrintWriter pw) {
for (Key key : getSortedKeys()) {
pw.print("ident="); pw.print(key.ident.toString());
@@ -683,6 +721,7 @@
}
}
+ /** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag);
@@ -706,6 +745,7 @@
proto.end(start);
}
+ /** @hide */
public void dumpCheckin(PrintWriter pw, long start, long end) {
dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateMobileWildcard(), "cell");
dumpCheckin(pw, start, end, NetworkTemplate.buildTemplateWifiWildcard(), "wifi");
@@ -768,16 +808,32 @@
return false;
}
- private static class Key implements Comparable<Key> {
+ /**
+ * the identifier that associate with the {@link NetworkStatsHistory} object to identify
+ * a certain record in the {@link NetworkStatsCollection} object.
+ */
+ public static class Key implements Comparable<Key> {
+ /** @hide */
public final NetworkIdentitySet ident;
+ /** @hide */
public final int uid;
+ /** @hide */
public final int set;
+ /** @hide */
public final int tag;
private final int mHashCode;
- Key(NetworkIdentitySet ident, int uid, int set, int tag) {
- this.ident = ident;
+ /**
+ * Construct a {@link Key} object.
+ *
+ * @param ident a Set of {@link NetworkIdentity} that associated with the record.
+ * @param uid Uid of the record.
+ * @param set Set of the record, see {@code NetworkStats#SET_*}.
+ * @param tag Tag of the record, see {@link TrafficStats#setThreadStatsTag(int)}.
+ */
+ public Key(@NonNull NetworkIdentitySet ident, int uid, int set, int tag) {
+ this.ident = Objects.requireNonNull(ident);
this.uid = uid;
this.set = set;
this.tag = tag;
@@ -790,7 +846,7 @@
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof Key) {
final Key key = (Key) obj;
return uid == key.uid && set == key.set && tag == key.tag
@@ -800,7 +856,8 @@
}
@Override
- public int compareTo(Key another) {
+ public int compareTo(@NonNull Key another) {
+ Objects.requireNonNull(another);
int res = 0;
if (ident != null && another.ident != null) {
res = ident.compareTo(another.ident);
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsHistory.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsHistory.java
index 428bc6d..90054c6 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsHistory.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkStatsHistory.java
@@ -30,6 +30,7 @@
import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational;
+import android.annotation.NonNull;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
@@ -64,18 +65,25 @@
*
* @hide
*/
-public class NetworkStatsHistory implements Parcelable {
+// @SystemApi(client = MODULE_LIBRARIES)
+public final class NetworkStatsHistory implements Parcelable {
private static final int VERSION_INIT = 1;
private static final int VERSION_ADD_PACKETS = 2;
private static final int VERSION_ADD_ACTIVE = 3;
+ /** @hide */
public static final int FIELD_ACTIVE_TIME = 0x01;
+ /** @hide */
public static final int FIELD_RX_BYTES = 0x02;
+ /** @hide */
public static final int FIELD_RX_PACKETS = 0x04;
+ /** @hide */
public static final int FIELD_TX_BYTES = 0x08;
+ /** @hide */
public static final int FIELD_TX_PACKETS = 0x10;
+ /** @hide */
public static final int FIELD_OPERATIONS = 0x20;
-
+ /** @hide */
public static final int FIELD_ALL = 0xFFFFFFFF;
private long bucketDuration;
@@ -108,15 +116,18 @@
public long operations;
}
+ /** @hide */
@UnsupportedAppUsage
public NetworkStatsHistory(long bucketDuration) {
this(bucketDuration, 10, FIELD_ALL);
}
+ /** @hide */
public NetworkStatsHistory(long bucketDuration, int initialSize) {
this(bucketDuration, initialSize, FIELD_ALL);
}
+ /** @hide */
public NetworkStatsHistory(long bucketDuration, int initialSize, int fields) {
this.bucketDuration = bucketDuration;
bucketStart = new long[initialSize];
@@ -130,11 +141,13 @@
totalBytes = 0;
}
+ /** @hide */
public NetworkStatsHistory(NetworkStatsHistory existing, long bucketDuration) {
this(bucketDuration, existing.estimateResizeBuckets(bucketDuration));
recordEntireHistory(existing);
}
+ /** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public NetworkStatsHistory(Parcel in) {
bucketDuration = in.readLong();
@@ -150,7 +163,7 @@
}
@Override
- public void writeToParcel(Parcel out, int flags) {
+ public void writeToParcel(@NonNull Parcel out, int flags) {
out.writeLong(bucketDuration);
writeLongArray(out, bucketStart, bucketCount);
writeLongArray(out, activeTime, bucketCount);
@@ -162,6 +175,7 @@
out.writeLong(totalBytes);
}
+ /** @hide */
public NetworkStatsHistory(DataInput in) throws IOException {
final int version = in.readInt();
switch (version) {
@@ -204,6 +218,7 @@
}
}
+ /** @hide */
public void writeToStream(DataOutput out) throws IOException {
out.writeInt(VERSION_ADD_ACTIVE);
out.writeLong(bucketDuration);
@@ -221,15 +236,18 @@
return 0;
}
+ /** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int size() {
return bucketCount;
}
+ /** @hide */
public long getBucketDuration() {
return bucketDuration;
}
+ /** @hide */
@UnsupportedAppUsage
public long getStart() {
if (bucketCount > 0) {
@@ -239,6 +257,7 @@
}
}
+ /** @hide */
@UnsupportedAppUsage
public long getEnd() {
if (bucketCount > 0) {
@@ -250,6 +269,7 @@
/**
* Return total bytes represented by this history.
+ * @hide
*/
public long getTotalBytes() {
return totalBytes;
@@ -258,6 +278,7 @@
/**
* Return index of bucket that contains or is immediately before the
* requested time.
+ * @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public int getIndexBefore(long time) {
@@ -273,6 +294,7 @@
/**
* Return index of bucket that contains or is immediately after the
* requested time.
+ * @hide
*/
public int getIndexAfter(long time) {
int index = Arrays.binarySearch(bucketStart, 0, bucketCount, time);
@@ -286,6 +308,7 @@
/**
* Return specific stats entry.
+ * @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public Entry getValues(int i, Entry recycle) {
@@ -301,6 +324,7 @@
return entry;
}
+ /** @hide */
public void setValues(int i, Entry entry) {
// Unwind old values
if (rxBytes != null) totalBytes -= rxBytes[i];
@@ -322,6 +346,7 @@
/**
* Record that data traffic occurred in the given time range. Will
* distribute across internal buckets, creating new buckets as needed.
+ * @hide
*/
@Deprecated
public void recordData(long start, long end, long rxBytes, long txBytes) {
@@ -332,6 +357,7 @@
/**
* Record that data traffic occurred in the given time range. Will
* distribute across internal buckets, creating new buckets as needed.
+ * @hide
*/
public void recordData(long start, long end, NetworkStats.Entry entry) {
long rxBytes = entry.rxBytes;
@@ -392,6 +418,7 @@
/**
* Record an entire {@link NetworkStatsHistory} into this history. Usually
* for combining together stats for external reporting.
+ * @hide
*/
@UnsupportedAppUsage
public void recordEntireHistory(NetworkStatsHistory input) {
@@ -402,6 +429,7 @@
* Record given {@link NetworkStatsHistory} into this history, copying only
* buckets that atomically occur in the inclusive time range. Doesn't
* interpolate across partial buckets.
+ * @hide
*/
public void recordHistory(NetworkStatsHistory input, long start, long end) {
final NetworkStats.Entry entry = new NetworkStats.Entry(
@@ -483,6 +511,7 @@
/**
* Clear all data stored in this object.
+ * @hide
*/
public void clear() {
bucketStart = EmptyArray.LONG;
@@ -498,9 +527,10 @@
/**
* Remove buckets older than requested cutoff.
+ * @hide
*/
- @Deprecated
public void removeBucketsBefore(long cutoff) {
+ // TODO: Consider use getIndexBefore.
int i;
for (i = 0; i < bucketCount; i++) {
final long curStart = bucketStart[i];
@@ -522,7 +552,9 @@
if (operations != null) operations = Arrays.copyOfRange(operations, i, length);
bucketCount -= i;
- // TODO: subtract removed values from totalBytes
+ totalBytes = 0;
+ if (rxBytes != null) totalBytes += CollectionUtils.total(rxBytes);
+ if (txBytes != null) totalBytes += CollectionUtils.total(txBytes);
}
}
@@ -536,6 +568,7 @@
* @param start - start of the range, timestamp in milliseconds since the epoch.
* @param end - end of the range, timestamp in milliseconds since the epoch.
* @param recycle - entry instance for performance, could be null.
+ * @hide
*/
@UnsupportedAppUsage
public Entry getValues(long start, long end, Entry recycle) {
@@ -550,6 +583,7 @@
* @param end - end of the range, timestamp in milliseconds since the epoch.
* @param now - current timestamp in milliseconds since the epoch (wall clock).
* @param recycle - entry instance for performance, could be null.
+ * @hide
*/
@UnsupportedAppUsage
public Entry getValues(long start, long end, long now, Entry recycle) {
@@ -613,6 +647,7 @@
/**
* @deprecated only for temporary testing
+ * @hide
*/
@Deprecated
public void generateRandom(long start, long end, long bytes) {
@@ -631,6 +666,7 @@
/**
* @deprecated only for temporary testing
+ * @hide
*/
@Deprecated
public void generateRandom(long start, long end, long rxBytes, long rxPackets, long txBytes,
@@ -660,12 +696,14 @@
}
}
+ /** @hide */
public static long randomLong(Random r, long start, long end) {
return (long) (start + (r.nextFloat() * (end - start)));
}
/**
* Quickly determine if this history intersects with given window.
+ * @hide
*/
public boolean intersects(long start, long end) {
final long dataStart = getStart();
@@ -677,6 +715,7 @@
return false;
}
+ /** @hide */
public void dump(IndentingPrintWriter pw, boolean fullHistory) {
pw.print("NetworkStatsHistory: bucketDuration=");
pw.println(bucketDuration / SECOND_IN_MILLIS);
@@ -700,6 +739,7 @@
pw.decreaseIndent();
}
+ /** @hide */
public void dumpCheckin(PrintWriter pw) {
pw.print("d,");
pw.print(bucketDuration / SECOND_IN_MILLIS);
@@ -717,6 +757,7 @@
}
}
+ /** @hide */
public void dumpDebug(ProtoOutputStream proto, long tag) {
final long start = proto.start(tag);
@@ -776,6 +817,7 @@
if (array != null) array[i] += value;
}
+ /** @hide */
public int estimateResizeBuckets(long newBucketDuration) {
return (int) (size() * getBucketDuration() / newBucketDuration);
}
@@ -783,6 +825,7 @@
/**
* Utility methods for interacting with {@link DataInputStream} and
* {@link DataOutputStream}, mostly dealing with writing partial arrays.
+ * @hide
*/
public static class DataStreamUtils {
@Deprecated
@@ -857,6 +900,7 @@
/**
* Utility methods for interacting with {@link Parcel} structures, mostly
* dealing with writing partial arrays.
+ * @hide
*/
public static class ParcelUtils {
public static long[] readLongArray(Parcel in) {
diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkTemplate.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkTemplate.java
index e9084b0..a7e48d4 100644
--- a/packages/ConnectivityT/framework-t/src/android/net/NetworkTemplate.java
+++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkTemplate.java
@@ -364,7 +364,7 @@
private final int mMetered;
private final int mRoaming;
private final int mDefaultNetwork;
- private final int mSubType;
+ private final int mRatType;
/**
* The subscriber Id match rule defines how the template should match networks with
* specific subscriberId(s). See NetworkTemplate#SUBSCRIBER_ID_MATCH_RULE_* for more detail.
@@ -413,18 +413,18 @@
/** @hide */
// TODO: Remove it after updating all of the caller.
public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds,
- String wifiNetworkKey, int metered, int roaming, int defaultNetwork, int subType,
+ String wifiNetworkKey, int metered, int roaming, int defaultNetwork, int ratType,
int oemManaged) {
this(matchRule, subscriberId, matchSubscriberIds,
wifiNetworkKey != null ? new String[] { wifiNetworkKey } : new String[0],
- metered, roaming, defaultNetwork, subType, oemManaged,
+ metered, roaming, defaultNetwork, ratType, oemManaged,
NetworkStatsUtils.SUBSCRIBER_ID_MATCH_RULE_EXACT);
}
/** @hide */
public NetworkTemplate(int matchRule, String subscriberId, String[] matchSubscriberIds,
String[] matchWifiNetworkKeys, int metered, int roaming,
- int defaultNetwork, int subType, int oemManaged, int subscriberIdMatchRule) {
+ int defaultNetwork, int ratType, int oemManaged, int subscriberIdMatchRule) {
Objects.requireNonNull(matchWifiNetworkKeys);
mMatchRule = matchRule;
mSubscriberId = subscriberId;
@@ -435,7 +435,7 @@
mMetered = metered;
mRoaming = roaming;
mDefaultNetwork = defaultNetwork;
- mSubType = subType;
+ mRatType = ratType;
mOemManaged = oemManaged;
mSubscriberIdMatchRule = subscriberIdMatchRule;
checkValidSubscriberIdMatchRule(matchRule, subscriberIdMatchRule);
@@ -453,7 +453,7 @@
mMetered = in.readInt();
mRoaming = in.readInt();
mDefaultNetwork = in.readInt();
- mSubType = in.readInt();
+ mRatType = in.readInt();
mOemManaged = in.readInt();
mSubscriberIdMatchRule = in.readInt();
}
@@ -467,7 +467,7 @@
dest.writeInt(mMetered);
dest.writeInt(mRoaming);
dest.writeInt(mDefaultNetwork);
- dest.writeInt(mSubType);
+ dest.writeInt(mRatType);
dest.writeInt(mOemManaged);
dest.writeInt(mSubscriberIdMatchRule);
}
@@ -500,8 +500,8 @@
builder.append(", defaultNetwork=").append(NetworkStats.defaultNetworkToString(
mDefaultNetwork));
}
- if (mSubType != NETWORK_TYPE_ALL) {
- builder.append(", subType=").append(mSubType);
+ if (mRatType != NETWORK_TYPE_ALL) {
+ builder.append(", ratType=").append(mRatType);
}
if (mOemManaged != OEM_MANAGED_ALL) {
builder.append(", oemManaged=").append(getOemManagedNames(mOemManaged));
@@ -514,7 +514,7 @@
@Override
public int hashCode() {
return Objects.hash(mMatchRule, mSubscriberId, Arrays.hashCode(mMatchWifiNetworkKeys),
- mMetered, mRoaming, mDefaultNetwork, mSubType, mOemManaged, mSubscriberIdMatchRule);
+ mMetered, mRoaming, mDefaultNetwork, mRatType, mOemManaged, mSubscriberIdMatchRule);
}
@Override
@@ -526,7 +526,7 @@
&& mMetered == other.mMetered
&& mRoaming == other.mRoaming
&& mDefaultNetwork == other.mDefaultNetwork
- && mSubType == other.mSubType
+ && mRatType == other.mRatType
&& mOemManaged == other.mOemManaged
&& mSubscriberIdMatchRule == other.mSubscriberIdMatchRule
&& Arrays.equals(mMatchWifiNetworkKeys, other.mMatchWifiNetworkKeys);
@@ -635,7 +635,7 @@
* Get the Radio Access Technology(RAT) type filter of the template.
*/
public int getRatType() {
- return mSubType;
+ return mRatType;
}
/**
@@ -708,8 +708,8 @@
}
private boolean matchesCollapsedRatType(NetworkIdentity ident) {
- return mSubType == NETWORK_TYPE_ALL
- || getCollapsedRatType(mSubType) == getCollapsedRatType(ident.mSubType);
+ return mRatType == NETWORK_TYPE_ALL
+ || getCollapsedRatType(mRatType) == getCollapsedRatType(ident.mRatType);
}
/**
@@ -837,7 +837,7 @@
switch (ident.mType) {
case TYPE_WIFI:
return matchesSubscriberId(ident.mSubscriberId)
- && matchesWifiNetworkKey(ident.mNetworkId);
+ && matchesWifiNetworkKey(ident.mWifiNetworkKey);
default:
return false;
}
diff --git a/packages/ConnectivityT/service/Android.bp b/packages/ConnectivityT/service/Android.bp
index 97dfb64..b261e16 100644
--- a/packages/ConnectivityT/service/Android.bp
+++ b/packages/ConnectivityT/service/Android.bp
@@ -82,8 +82,18 @@
":services.connectivity-ethernet-sources",
":services.connectivity-ipsec-sources",
":services.connectivity-netstats-sources",
- ":services.connectivity-nsd-sources",
],
path: "src",
visibility: ["//frameworks/base/services/core"],
}
+
+filegroup {
+ name: "services.connectivity-tiramisu-updatable-sources",
+ srcs: [
+ ":services.connectivity-nsd-sources",
+ ],
+ path: "src",
+ visibility: [
+ "//packages/modules/Connectivity:__subpackages__",
+ ],
+}
diff --git a/packages/ConnectivityT/service/src/com/android/server/net/NetworkStatsService.java b/packages/ConnectivityT/service/src/com/android/server/net/NetworkStatsService.java
index 0abc523..9b90f3b 100644
--- a/packages/ConnectivityT/service/src/com/android/server/net/NetworkStatsService.java
+++ b/packages/ConnectivityT/service/src/com/android/server/net/NetworkStatsService.java
@@ -19,12 +19,16 @@
import static android.Manifest.permission.NETWORK_STATS_PROVIDER;
import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
import static android.Manifest.permission.UPDATE_DEVICE_STATS;
+import static android.app.usage.NetworkStatsManager.PREFIX_DEV;
+import static android.app.usage.NetworkStatsManager.PREFIX_UID;
+import static android.app.usage.NetworkStatsManager.PREFIX_UID_TAG;
+import static android.app.usage.NetworkStatsManager.PREFIX_XT;
import static android.content.Intent.ACTION_SHUTDOWN;
import static android.content.Intent.ACTION_UID_REMOVED;
import static android.content.Intent.ACTION_USER_REMOVED;
import static android.content.Intent.EXTRA_UID;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static android.net.NetworkIdentity.SUBTYPE_COMBINED;
+import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
import static android.net.NetworkStats.DEFAULT_NETWORK_ALL;
import static android.net.NetworkStats.IFACE_ALL;
import static android.net.NetworkStats.IFACE_VT;
@@ -47,23 +51,6 @@
import static android.net.TrafficStats.UID_TETHERING;
import static android.net.TrafficStats.UNSUPPORTED;
import static android.os.Trace.TRACE_TAG_NETWORK;
-import static android.provider.Settings.Global.NETSTATS_AUGMENT_ENABLED;
-import static android.provider.Settings.Global.NETSTATS_COMBINE_SUBTYPE_ENABLED;
-import static android.provider.Settings.Global.NETSTATS_DEV_BUCKET_DURATION;
-import static android.provider.Settings.Global.NETSTATS_DEV_DELETE_AGE;
-import static android.provider.Settings.Global.NETSTATS_DEV_PERSIST_BYTES;
-import static android.provider.Settings.Global.NETSTATS_DEV_ROTATE_AGE;
-import static android.provider.Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES;
-import static android.provider.Settings.Global.NETSTATS_POLL_INTERVAL;
-import static android.provider.Settings.Global.NETSTATS_SAMPLE_ENABLED;
-import static android.provider.Settings.Global.NETSTATS_UID_BUCKET_DURATION;
-import static android.provider.Settings.Global.NETSTATS_UID_DELETE_AGE;
-import static android.provider.Settings.Global.NETSTATS_UID_PERSIST_BYTES;
-import static android.provider.Settings.Global.NETSTATS_UID_ROTATE_AGE;
-import static android.provider.Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION;
-import static android.provider.Settings.Global.NETSTATS_UID_TAG_DELETE_AGE;
-import static android.provider.Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES;
-import static android.provider.Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static android.text.format.DateUtils.DAY_IN_MILLIS;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
@@ -154,6 +141,7 @@
import com.android.net.module.util.BestClock;
import com.android.net.module.util.BinderUtils;
import com.android.net.module.util.CollectionUtils;
+import com.android.net.module.util.LocationPermissionChecker;
import com.android.net.module.util.NetworkStatsUtils;
import com.android.net.module.util.PermissionUtils;
@@ -216,6 +204,10 @@
private static final int LOG_TAG_NETSTATS_MOBILE_SAMPLE = 51100;
private static final int LOG_TAG_NETSTATS_WIFI_SAMPLE = 51101;
+ // TODO: Replace the hardcoded string and move it into ConnectivitySettingsManager.
+ private static final String NETSTATS_COMBINE_SUBTYPE_ENABLED =
+ "netstats_combine_subtype_enabled";
+
private final Context mContext;
private final NetworkStatsFactory mStatsFactory;
private final AlarmManager mAlarmManager;
@@ -242,11 +234,6 @@
private PendingIntent mPollIntent;
- private static final String PREFIX_DEV = "dev";
- private static final String PREFIX_XT = "xt";
- private static final String PREFIX_UID = "uid";
- private static final String PREFIX_UID_TAG = "uid_tag";
-
/**
* Settings that can be changed externally.
*/
@@ -256,9 +243,9 @@
boolean getSampleEnabled();
boolean getAugmentEnabled();
/**
- * When enabled, all mobile data is reported under {@link NetworkIdentity#SUBTYPE_COMBINED}.
- * When disabled, mobile data is broken down by a granular subtype representative of the
- * actual subtype. {@see NetworkTemplate#getCollapsedRatType}.
+ * When enabled, all mobile data is reported under {@link NetworkTemplate#NETWORK_TYPE_ALL}.
+ * When disabled, mobile data is broken down by a granular ratType representative of the
+ * actual ratType. {@see NetworkTemplate#getCollapsedRatType}.
* Enabling this decreases the level of detail but saves performance, disk space and
* amount of data logged.
*/
@@ -305,6 +292,9 @@
/** Set of any ifaces associated with mobile networks since boot. */
private volatile String[] mMobileIfaces = new String[0];
+ /** Set of any ifaces associated with wifi networks since boot. */
+ private volatile String[] mWifiIfaces = new String[0];
+
/** Set of all ifaces currently used by traffic that does not explicitly specify a Network. */
@GuardedBy("mStatsLock")
private Network[] mDefaultNetworks = new Network[0];
@@ -365,6 +355,9 @@
@NonNull
private final NetworkStatsSubscriptionsMonitor mNetworkStatsSubscriptionsMonitor;
+ @NonNull
+ private final LocationPermissionChecker mLocationPermissionChecker;
+
private static @NonNull File getDefaultSystemDir() {
return new File(Environment.getDataDirectory(), "system");
}
@@ -427,7 +420,7 @@
final NetworkStatsService service = new NetworkStatsService(context,
INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
alarmManager, wakeLock, getDefaultClock(),
- new DefaultNetworkStatsSettings(context), new NetworkStatsFactory(netd),
+ new DefaultNetworkStatsSettings(), new NetworkStatsFactory(netd),
new NetworkStatsObservers(), getDefaultSystemDir(), getDefaultBaseDir(),
new Dependencies());
@@ -461,6 +454,7 @@
mContentResolver = mContext.getContentResolver();
mContentObserver = mDeps.makeContentObserver(mHandler, mSettings,
mNetworkStatsSubscriptionsMonitor);
+ mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
}
/**
@@ -508,6 +502,13 @@
}
};
}
+
+ /**
+ * @see LocationPermissionChecker
+ */
+ public LocationPermissionChecker makeLocationPermissionChecker(final Context context) {
+ return new LocationPermissionChecker(context);
+ }
}
/**
@@ -590,13 +591,13 @@
mSettings.getPollInterval(), pollIntent);
mContentResolver.registerContentObserver(Settings.Global
- .getUriFor(Settings.Global.NETSTATS_COMBINE_SUBTYPE_ENABLED),
+ .getUriFor(NETSTATS_COMBINE_SUBTYPE_ENABLED),
false /* notifyForDescendants */, mContentObserver);
// Post a runnable on handler thread to call onChange(). It's for getting current value of
// NETSTATS_COMBINE_SUBTYPE_ENABLED to decide start or stop monitoring RAT type changes.
mHandler.post(() -> mContentObserver.onChange(false, Settings.Global
- .getUriFor(Settings.Global.NETSTATS_COMBINE_SUBTYPE_ENABLED)));
+ .getUriFor(NETSTATS_COMBINE_SUBTYPE_ENABLED)));
registerGlobalAlert();
}
@@ -773,6 +774,7 @@
@Override
public NetworkStats getDeviceSummaryForNetwork(
NetworkTemplate template, long start, long end) {
+ enforceTemplatePermissions(template, callingPackage);
return internalGetSummaryForNetwork(template, restrictedFlags, start, end,
mAccessLevel, mCallingUid);
}
@@ -780,19 +782,33 @@
@Override
public NetworkStats getSummaryForNetwork(
NetworkTemplate template, long start, long end) {
+ enforceTemplatePermissions(template, callingPackage);
return internalGetSummaryForNetwork(template, restrictedFlags, start, end,
mAccessLevel, mCallingUid);
}
+ // TODO: Remove this after all callers are removed.
@Override
public NetworkStatsHistory getHistoryForNetwork(NetworkTemplate template, int fields) {
+ enforceTemplatePermissions(template, callingPackage);
return internalGetHistoryForNetwork(template, restrictedFlags, fields,
- mAccessLevel, mCallingUid);
+ mAccessLevel, mCallingUid, Long.MIN_VALUE, Long.MAX_VALUE);
+ }
+
+ @Override
+ public NetworkStatsHistory getHistoryIntervalForNetwork(NetworkTemplate template,
+ int fields, long start, long end) {
+ enforceTemplatePermissions(template, callingPackage);
+ // TODO(b/200768422): Redact returned history if the template is location
+ // sensitive but the caller is not privileged.
+ return internalGetHistoryForNetwork(template, restrictedFlags, fields,
+ mAccessLevel, mCallingUid, start, end);
}
@Override
public NetworkStats getSummaryForAllUid(
NetworkTemplate template, long start, long end, boolean includeTags) {
+ enforceTemplatePermissions(template, callingPackage);
try {
final NetworkStats stats = getUidComplete()
.getSummary(template, start, end, mAccessLevel, mCallingUid);
@@ -810,6 +826,7 @@
@Override
public NetworkStats getTaggedSummaryForAllUid(
NetworkTemplate template, long start, long end) {
+ enforceTemplatePermissions(template, callingPackage);
try {
final NetworkStats tagStats = getUidTagComplete()
.getSummary(template, start, end, mAccessLevel, mCallingUid);
@@ -822,6 +839,7 @@
@Override
public NetworkStatsHistory getHistoryForUid(
NetworkTemplate template, int uid, int set, int tag, int fields) {
+ enforceTemplatePermissions(template, callingPackage);
// NOTE: We don't augment UID-level statistics
if (tag == TAG_NONE) {
return getUidComplete().getHistory(template, null, uid, set, tag, fields,
@@ -836,6 +854,9 @@
public NetworkStatsHistory getHistoryIntervalForUid(
NetworkTemplate template, int uid, int set, int tag, int fields,
long start, long end) {
+ enforceTemplatePermissions(template, callingPackage);
+ // TODO(b/200768422): Redact returned history if the template is location
+ // sensitive but the caller is not privileged.
// NOTE: We don't augment UID-level statistics
if (tag == TAG_NONE) {
return getUidComplete().getHistory(template, null, uid, set, tag, fields,
@@ -857,6 +878,26 @@
};
}
+ private void enforceTemplatePermissions(@NonNull NetworkTemplate template,
+ @NonNull String callingPackage) {
+ // For a template with wifi network keys, it is possible for a malicious
+ // client to track the user locations via querying data usage. Thus, enforce
+ // fine location permission check.
+ if (!template.getWifiNetworkKeys().isEmpty()) {
+ final boolean canAccessFineLocation = mLocationPermissionChecker
+ .checkCallersLocationPermission(callingPackage,
+ null /* featureId */,
+ Binder.getCallingUid(),
+ false /* coarseForTargetSdkLessThanQ */,
+ null /* message */);
+ if (!canAccessFineLocation) {
+ throw new SecurityException("Access fine location is required when querying"
+ + " with wifi network keys, make sure the app has the necessary"
+ + "permissions and the location toggle is on.");
+ }
+ }
+ }
+
private @NetworkStatsAccess.Level int checkAccessLevel(String callingPackage) {
return NetworkStatsAccess.checkAccessLevel(
mContext, Binder.getCallingPid(), Binder.getCallingUid(), callingPackage);
@@ -893,7 +934,7 @@
// We've been using pure XT stats long enough that we no longer need to
// splice DEV and XT together.
final NetworkStatsHistory history = internalGetHistoryForNetwork(template, flags, FIELD_ALL,
- accessLevel, callingUid);
+ accessLevel, callingUid, start, end);
final long now = System.currentTimeMillis();
final NetworkStatsHistory.Entry entry = history.getValues(start, end, now, null);
@@ -910,14 +951,14 @@
* appropriate.
*/
private NetworkStatsHistory internalGetHistoryForNetwork(NetworkTemplate template,
- int flags, int fields, @NetworkStatsAccess.Level int accessLevel, int callingUid) {
+ int flags, int fields, @NetworkStatsAccess.Level int accessLevel, int callingUid,
+ long start, long end) {
// We've been using pure XT stats long enough that we no longer need to
// splice DEV and XT together.
final SubscriptionPlan augmentPlan = resolveSubscriptionPlan(template, flags);
synchronized (mStatsLock) {
return mXtStatsCached.getHistory(template, augmentPlan,
- UID_ALL, SET_ALL, TAG_NONE, fields, Long.MIN_VALUE, Long.MAX_VALUE,
- accessLevel, callingUid);
+ UID_ALL, SET_ALL, TAG_NONE, fields, start, end, accessLevel, callingUid);
}
}
@@ -968,11 +1009,15 @@
}
@Override
- public NetworkStats getDetailedUidStats(String[] requiredIfaces) {
+ public NetworkStats getUidStatsForTransport(int transport) {
enforceAnyPermissionOf(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
try {
+ final String[] relevantIfaces =
+ transport == TRANSPORT_WIFI ? mWifiIfaces : mMobileIfaces;
+ // TODO(b/215633405) : mMobileIfaces and mWifiIfaces already contain the stacked
+ // interfaces, so this is not useful, remove it.
final String[] ifacesToQuery =
- mStatsFactory.augmentWithStackedInterfaces(requiredIfaces);
+ mStatsFactory.augmentWithStackedInterfaces(relevantIfaces);
return getNetworkStatsUidDetail(ifacesToQuery);
} catch (RemoteException e) {
Log.wtf(TAG, "Error compiling UID stats", e);
@@ -1331,16 +1376,18 @@
final boolean combineSubtypeEnabled = mSettings.getCombineSubtypeEnabled();
final ArraySet<String> mobileIfaces = new ArraySet<>();
+ final ArraySet<String> wifiIfaces = new ArraySet<>();
for (NetworkStateSnapshot snapshot : snapshots) {
final int displayTransport =
getDisplayTransport(snapshot.getNetworkCapabilities().getTransportTypes());
final boolean isMobile = (NetworkCapabilities.TRANSPORT_CELLULAR == displayTransport);
+ final boolean isWifi = (NetworkCapabilities.TRANSPORT_WIFI == displayTransport);
final boolean isDefault = CollectionUtils.contains(
mDefaultNetworks, snapshot.getNetwork());
- final int subType = combineSubtypeEnabled ? SUBTYPE_COMBINED
- : getSubTypeForStateSnapshot(snapshot);
+ final int ratType = combineSubtypeEnabled ? NetworkTemplate.NETWORK_TYPE_ALL
+ : getRatTypeForStateSnapshot(snapshot);
final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, snapshot,
- isDefault, subType);
+ isDefault, ratType);
// Traffic occurring on the base interface is always counted for
// both total usage and UID details.
@@ -1355,12 +1402,12 @@
// VT is considered always metered in framework's layer. If VT is not metered
// per carrier's policy, modem will report 0 usage for VT calls.
if (snapshot.getNetworkCapabilities().hasCapability(
- NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.getMetered()) {
+ NetworkCapabilities.NET_CAPABILITY_IMS) && !ident.isMetered()) {
// Copy the identify from IMS one but mark it as metered.
NetworkIdentity vtIdent = new NetworkIdentity(ident.getType(),
- ident.getSubType(), ident.getSubscriberId(), ident.getNetworkId(),
- ident.getRoaming(), true /* metered */,
+ ident.getRatType(), ident.getSubscriberId(), ident.getWifiNetworkKey(),
+ ident.isRoaming(), true /* metered */,
true /* onDefaultNetwork */, ident.getOemManaged());
final String ifaceVt = IFACE_VT + getSubIdForMobile(snapshot);
findOrCreateNetworkIdentitySet(mActiveIfaces, ifaceVt).add(vtIdent);
@@ -1370,6 +1417,9 @@
if (isMobile) {
mobileIfaces.add(baseIface);
}
+ if (isWifi) {
+ wifiIfaces.add(baseIface);
+ }
}
// Traffic occurring on stacked interfaces is usually clatd.
@@ -1411,6 +1461,9 @@
if (isMobile) {
mobileIfaces.add(iface);
}
+ if (isWifi) {
+ wifiIfaces.add(iface);
+ }
mStatsFactory.noteStackedIface(iface, baseIface);
}
@@ -1418,11 +1471,16 @@
}
mMobileIfaces = mobileIfaces.toArray(new String[0]);
+ mWifiIfaces = wifiIfaces.toArray(new String[0]);
// TODO (b/192758557): Remove debug log.
if (CollectionUtils.contains(mMobileIfaces, null)) {
throw new NullPointerException(
"null element in mMobileIfaces: " + Arrays.toString(mMobileIfaces));
}
+ if (CollectionUtils.contains(mWifiIfaces, null)) {
+ throw new NullPointerException(
+ "null element in mWifiIfaces: " + Arrays.toString(mWifiIfaces));
+ }
}
private static int getSubIdForMobile(@NonNull NetworkStateSnapshot state) {
@@ -1440,11 +1498,11 @@
}
/**
- * For networks with {@code TRANSPORT_CELLULAR}, get subType that was obtained through
+ * For networks with {@code TRANSPORT_CELLULAR}, get ratType that was obtained through
* {@link PhoneStateListener}. Otherwise, return 0 given that other networks with different
* transport types do not actually fill this value.
*/
- private int getSubTypeForStateSnapshot(@NonNull NetworkStateSnapshot state) {
+ private int getRatTypeForStateSnapshot(@NonNull NetworkStateSnapshot state) {
if (!state.getNetworkCapabilities().hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return 0;
}
@@ -2191,24 +2249,11 @@
* {@link android.provider.Settings.Global}.
*/
private static class DefaultNetworkStatsSettings implements NetworkStatsSettings {
- private final ContentResolver mResolver;
-
- public DefaultNetworkStatsSettings(Context context) {
- mResolver = Objects.requireNonNull(context.getContentResolver());
- // TODO: adjust these timings for production builds
- }
-
- private long getGlobalLong(String name, long def) {
- return Settings.Global.getLong(mResolver, name, def);
- }
- private boolean getGlobalBoolean(String name, boolean def) {
- final int defInt = def ? 1 : 0;
- return Settings.Global.getInt(mResolver, name, defInt) != 0;
- }
+ DefaultNetworkStatsSettings() {}
@Override
public long getPollInterval() {
- return getGlobalLong(NETSTATS_POLL_INTERVAL, 30 * MINUTE_IN_MILLIS);
+ return 30 * MINUTE_IN_MILLIS;
}
@Override
public long getPollDelay() {
@@ -2216,25 +2261,23 @@
}
@Override
public long getGlobalAlertBytes(long def) {
- return getGlobalLong(NETSTATS_GLOBAL_ALERT_BYTES, def);
+ return def;
}
@Override
public boolean getSampleEnabled() {
- return getGlobalBoolean(NETSTATS_SAMPLE_ENABLED, true);
+ return true;
}
@Override
public boolean getAugmentEnabled() {
- return getGlobalBoolean(NETSTATS_AUGMENT_ENABLED, true);
+ return true;
}
@Override
public boolean getCombineSubtypeEnabled() {
- return getGlobalBoolean(NETSTATS_COMBINE_SUBTYPE_ENABLED, false);
+ return false;
}
@Override
public Config getDevConfig() {
- return new Config(getGlobalLong(NETSTATS_DEV_BUCKET_DURATION, HOUR_IN_MILLIS),
- getGlobalLong(NETSTATS_DEV_ROTATE_AGE, 15 * DAY_IN_MILLIS),
- getGlobalLong(NETSTATS_DEV_DELETE_AGE, 90 * DAY_IN_MILLIS));
+ return new Config(HOUR_IN_MILLIS, 15 * DAY_IN_MILLIS, 90 * DAY_IN_MILLIS);
}
@Override
public Config getXtConfig() {
@@ -2242,31 +2285,27 @@
}
@Override
public Config getUidConfig() {
- return new Config(getGlobalLong(NETSTATS_UID_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
- getGlobalLong(NETSTATS_UID_ROTATE_AGE, 15 * DAY_IN_MILLIS),
- getGlobalLong(NETSTATS_UID_DELETE_AGE, 90 * DAY_IN_MILLIS));
+ return new Config(2 * HOUR_IN_MILLIS, 15 * DAY_IN_MILLIS, 90 * DAY_IN_MILLIS);
}
@Override
public Config getUidTagConfig() {
- return new Config(getGlobalLong(NETSTATS_UID_TAG_BUCKET_DURATION, 2 * HOUR_IN_MILLIS),
- getGlobalLong(NETSTATS_UID_TAG_ROTATE_AGE, 5 * DAY_IN_MILLIS),
- getGlobalLong(NETSTATS_UID_TAG_DELETE_AGE, 15 * DAY_IN_MILLIS));
+ return new Config(2 * HOUR_IN_MILLIS, 5 * DAY_IN_MILLIS, 15 * DAY_IN_MILLIS);
}
@Override
public long getDevPersistBytes(long def) {
- return getGlobalLong(NETSTATS_DEV_PERSIST_BYTES, def);
+ return def;
}
@Override
public long getXtPersistBytes(long def) {
- return getDevPersistBytes(def);
+ return def;
}
@Override
public long getUidPersistBytes(long def) {
- return getGlobalLong(NETSTATS_UID_PERSIST_BYTES, def);
+ return def;
}
@Override
public long getUidTagPersistBytes(long def) {
- return getGlobalLong(NETSTATS_UID_TAG_PERSIST_BYTES, def);
+ return def;
}
}
diff --git a/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java b/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
index a3eb0ecc..ce58ff6 100644
--- a/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
+++ b/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
@@ -236,7 +236,8 @@
root.flags |= Root.FLAG_REMOVABLE_USB;
}
- if (volume.getType() != VolumeInfo.TYPE_EMULATED) {
+ if (volume.getType() != VolumeInfo.TYPE_EMULATED
+ && volume.getType() != VolumeInfo.TYPE_STUB) {
root.flags |= Root.FLAG_SUPPORTS_EJECT;
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java b/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
index 3e95b01..5e9ac5a 100644
--- a/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
+++ b/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
@@ -16,23 +16,16 @@
package com.android.settingslib.net;
-import static android.net.NetworkStatsHistory.FIELD_RX_BYTES;
-import static android.net.NetworkStatsHistory.FIELD_TX_BYTES;
-
+import android.annotation.NonNull;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
-import android.net.INetworkStatsService;
-import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
-import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
-import android.net.TrafficStats;
-import android.os.RemoteException;
-import android.os.ServiceManager;
import android.text.format.DateUtils;
import android.util.Pair;
+import android.util.Range;
import androidx.annotation.VisibleForTesting;
import androidx.loader.content.AsyncTaskLoader;
@@ -52,8 +45,6 @@
protected final NetworkTemplate mNetworkTemplate;
private final NetworkPolicy mPolicy;
private final ArrayList<Long> mCycles;
- @VisibleForTesting
- final INetworkStatsService mNetworkStatsService;
protected NetworkCycleDataLoader(Builder<?> builder) {
super(builder.mContext);
@@ -61,8 +52,6 @@
mCycles = builder.mCycles;
mNetworkStatsManager = (NetworkStatsManager)
builder.mContext.getSystemService(Context.NETWORK_STATS_SERVICE);
- mNetworkStatsService = INetworkStatsService.Stub.asInterface(
- ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
final NetworkPolicyEditor policyEditor =
new NetworkPolicyEditor(NetworkPolicyManager.from(builder.mContext));
policyEditor.read();
@@ -112,23 +101,20 @@
@VisibleForTesting
void loadFourWeeksData() {
+ if (mNetworkTemplate == null) return;
+ final NetworkStats stats = mNetworkStatsManager.queryDetailsForDevice(
+ mNetworkTemplate, Long.MIN_VALUE, Long.MAX_VALUE);
try {
- final INetworkStatsSession networkSession = mNetworkStatsService.openSession();
- final NetworkStatsHistory networkHistory = networkSession.getHistoryForNetwork(
- mNetworkTemplate, FIELD_RX_BYTES | FIELD_TX_BYTES);
- final long historyStart = networkHistory.getStart();
- final long historyEnd = networkHistory.getEnd();
+ final Range<Long> historyTimeRange = getTimeRangeOf(stats);
- long cycleEnd = historyEnd;
- while (cycleEnd > historyStart) {
+ long cycleEnd = historyTimeRange.getUpper();
+ while (cycleEnd > historyTimeRange.getLower()) {
final long cycleStart = cycleEnd - (DateUtils.WEEK_IN_MILLIS * 4);
recordUsage(cycleStart, cycleEnd);
cycleEnd = cycleStart;
}
-
- TrafficStats.closeQuietly(networkSession);
- } catch (RemoteException e) {
- throw new RuntimeException(e);
+ } catch (IllegalArgumentException e) {
+ // Empty history, ignore.
}
}
@@ -169,6 +155,32 @@
return bytes;
}
+ @NonNull
+ @VisibleForTesting
+ Range getTimeRangeOf(@NonNull NetworkStats stats) {
+ long start = Long.MAX_VALUE;
+ long end = Long.MIN_VALUE;
+ while (hasNextBucket(stats)) {
+ final NetworkStats.Bucket bucket = getNextBucket(stats);
+ start = Math.min(start, bucket.getStartTimeStamp());
+ end = Math.max(end, bucket.getEndTimeStamp());
+ }
+ return new Range(start, end);
+ }
+
+ @VisibleForTesting
+ boolean hasNextBucket(@NonNull NetworkStats stats) {
+ return stats.hasNextBucket();
+ }
+
+ @NonNull
+ @VisibleForTesting
+ NetworkStats.Bucket getNextBucket(@NonNull NetworkStats stats) {
+ NetworkStats.Bucket bucket = new NetworkStats.Bucket();
+ stats.getNextBucket(bucket);
+ return bucket;
+ }
+
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
public ArrayList<Long> getCycles() {
return mCycles;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
index 74b9151..c79440e 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
@@ -16,24 +16,24 @@
package com.android.settingslib.net;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.nullable;
+import static android.app.usage.NetworkStats.Bucket.UID_ALL;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.annotation.NonNull;
+import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.ConnectivityManager;
-import android.net.INetworkStatsService;
-import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
-import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
-import android.os.RemoteException;
import android.text.format.DateUtils;
import android.util.Range;
@@ -49,6 +49,8 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.LinkedBlockingQueue;
@RunWith(RobolectricTestRunner.class)
public class NetworkCycleDataLoaderTest {
@@ -63,8 +65,6 @@
private NetworkPolicy mPolicy;
@Mock
private Iterator<Range<ZonedDateTime>> mIterator;
- @Mock
- private INetworkStatsService mNetworkStatsService;
private NetworkCycleDataTestLoader mLoader;
@@ -132,20 +132,24 @@
verify(mLoader).recordUsage(nowInMs, nowInMs);
}
+ private NetworkStats.Bucket makeMockBucket(int uid, long rxBytes, long txBytes,
+ long start, long end) {
+ NetworkStats.Bucket ret = mock(NetworkStats.Bucket.class);
+ when(ret.getUid()).thenReturn(uid);
+ when(ret.getRxBytes()).thenReturn(rxBytes);
+ when(ret.getTxBytes()).thenReturn(txBytes);
+ when(ret.getStartTimeStamp()).thenReturn(start);
+ when(ret.getEndTimeStamp()).thenReturn(end);
+ return ret;
+ }
+
@Test
- public void loadFourWeeksData_shouldRecordUsageForLast4Weeks() throws RemoteException {
+ public void loadFourWeeksData_shouldRecordUsageForLast4Weeks() {
mLoader = spy(new NetworkCycleDataTestLoader(mContext));
- ReflectionHelpers.setField(mLoader, "mNetworkStatsService", mNetworkStatsService);
- final INetworkStatsSession networkSession = mock(INetworkStatsSession.class);
- when(mNetworkStatsService.openSession()).thenReturn(networkSession);
- final NetworkStatsHistory networkHistory = mock(NetworkStatsHistory.class);
- when(networkSession.getHistoryForNetwork(nullable(NetworkTemplate.class), anyInt()))
- .thenReturn(networkHistory);
final long now = System.currentTimeMillis();
final long fourWeeksAgo = now - (DateUtils.WEEK_IN_MILLIS * 4);
final long twoDaysAgo = now - (DateUtils.DAY_IN_MILLIS * 2);
- when(networkHistory.getStart()).thenReturn(twoDaysAgo);
- when(networkHistory.getEnd()).thenReturn(now);
+ mLoader.addBucket(makeMockBucket(UID_ALL, 123, 456, twoDaysAgo, now));
mLoader.loadFourWeeksData();
@@ -173,10 +177,31 @@
verify(mLoader).recordUsage(thirtyDaysAgo, twentyDaysAgo);
}
+ @Test
+ public void getTimeRangeOf() {
+ mLoader = spy(new NetworkCycleDataTestLoader(mContext));
+ // If empty, new Range(MAX_VALUE, MIN_VALUE) will be constructed. Hence, the function
+ // should throw.
+ assertThrows(IllegalArgumentException.class,
+ () -> mLoader.getTimeRangeOf(mock(NetworkStats.class)));
+
+ mLoader.addBucket(makeMockBucket(UID_ALL, 123, 456, 0, 10));
+ // Feed the function with unused NetworkStats. The actual data injection is
+ // done by addBucket.
+ assertEquals(new Range(0L, 10L), mLoader.getTimeRangeOf(mock(NetworkStats.class)));
+
+ mLoader.addBucket(makeMockBucket(UID_ALL, 123, 456, 0, 10));
+ mLoader.addBucket(makeMockBucket(UID_ALL, 123, 456, 30, 40));
+ mLoader.addBucket(makeMockBucket(UID_ALL, 123, 456, 10, 25));
+ assertEquals(new Range(0L, 40L), mLoader.getTimeRangeOf(mock(NetworkStats.class)));
+ }
+
public class NetworkCycleDataTestLoader extends NetworkCycleDataLoader<List<NetworkCycleData>> {
+ private final Queue<NetworkStats.Bucket> mMockedBuckets = new LinkedBlockingQueue<>();
private NetworkCycleDataTestLoader(Context context) {
- super(NetworkCycleDataLoader.builder(mContext));
+ super(NetworkCycleDataLoader.builder(mContext)
+ .setNetworkTemplate(mock(NetworkTemplate.class)));
mContext = context;
}
@@ -188,5 +213,19 @@
List<NetworkCycleData> getCycleUsage() {
return null;
}
+
+ public void addBucket(NetworkStats.Bucket bucket) {
+ mMockedBuckets.add(bucket);
+ }
+
+ @Override
+ public boolean hasNextBucket(@NonNull NetworkStats unused) {
+ return !mMockedBuckets.isEmpty();
+ }
+
+ @Override
+ public NetworkStats.Bucket getNextBucket(@NonNull NetworkStats unused) {
+ return mMockedBuckets.remove();
+ }
}
}
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 10ff05d..96310b8 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -245,6 +245,7 @@
<uses-permission android:name="android.permission.MANAGE_APP_PREDICTIONS" />
<uses-permission android:name="android.permission.MANAGE_SEARCH_UI" />
<uses-permission android:name="android.permission.MANAGE_SMARTSPACE" />
+ <uses-permission android:name="android.permission.MANAGE_WALLPAPER_EFFECTS_GENERATION" />
<uses-permission android:name="android.permission.MANAGE_UI_TRANSLATION" />
<uses-permission android:name="android.permission.NETWORK_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 2303495..554a7b1 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -1338,7 +1338,6 @@
VcnManagementService vcnManagement = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
- NsdService serviceDiscovery = null;
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
@@ -1941,16 +1940,6 @@
}
t.traceEnd();
- t.traceBegin("StartNsdService");
- try {
- serviceDiscovery = NsdService.create(context);
- ServiceManager.addService(
- Context.NSD_SERVICE, serviceDiscovery);
- } catch (Throwable e) {
- reportWtf("starting Service Discovery Service", e);
- }
- t.traceEnd();
-
t.traceBegin("StartSystemUpdateManagerService");
try {
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,