Skip to content

Commit 0a9ff06

Browse files
authored
feat(android): Add cellular network technology to connection type (#6146)
* feat(android): Add cellular network technology to connection type Refine device.connection_type from cellular to cellular_4g or cellular_5g when the network technology is known. From Android 12 the generation comes from the display info listener, which needs no permission. On older versions it is read from TelephonyManager only when the hosting app already holds READ_PHONE_STATE or READ_BASIC_PHONE_STATE, which the SDK does not declare itself. Fixes #3886 * changelog * fix(android): Tie telephony listener to the network callback The display info listener was started before the network callback was registered. Unregistering is skipped while there is no network callback, so a failed registration left the listener running for the rest of the process, including in the background. Start it only after the network callback registered, and guard the check-then-act in register and unregister with a lock so concurrent callers cannot register a second listener that is never stored. * ref(android): Report the network technology as its own attribute device.connection_type is deprecated in favour of network.connection.type, and the conventions already have network.connection.effective_type for the generation, so the technology is no longer folded into the connection type. Device gains connection_effective_type with 2g, 3g, 4g or 5g, mirroring how connection_type aliases network.connection.type. * fix(android): Read the connection type and technology together Reading the connection type and the network technology separately let a connectivity change land between them, so an event could report a wifi connection with a cellular technology. Both now come from one accessor that derives them from a single cache read. * fix(android): Report 5G mmWave and keep the callback on failure The NSA mmWave override network type fell through to the network type, which is LTE for NSA, so a 5G mmWave connection reported 4g. Unregistering also dropped the callback reference before it was unregistered, orphaning a still-registered callback when the telephony manager was gone. * fix(android): Keep the last cellular technology after backgrounding Monitoring stops when the app goes to the background, and from API 31 on the display info listener is the only source, so clearing the cached generation left every background event without a technology while the connection type still resolved. * fix(android): Don't throw from the telephony executor The SDK executor rejects work once it is shut down, and its queue check doesn't cover that, so a display info change arriving after Sentry.close threw RejectedExecutionException on a thread owned by the telephony framework. * test(android): Restore the executor before teardown The rejecting executor is shared through the options, and teardown closes the provider through it, so leaving it rejecting skipped clearing the static connectivity manager for later tests. * ref(android): Address the review of the cellular technology * `CellularNetworkTechnologyProvider` guards its registration with `synchronized` instead of `AutoClosableReentrantLock`. That lock only exists for a JVM bug, and this code is Android only. * The provider takes the executor service and builds the executor the telephony framework calls, with the guard against a rejection. The constructor of `AndroidConnectionStatusProvider` no longer sets up that exception handling. * `Connection` moves out of `AndroidConnectionStatusProvider`, which is already a large class, into a top level `NetworkConnection`. The name is not `ConnectionType`, because the class holds the connection type and the effective type. * The test for the rejected executor is removed, together with its executor double. * fix(android): Run the telephony callback on its own thread The provider submitted the display info update to the SDK executor it got at construction. That reference goes stale twice over. The options hold a no-op executor until `SentryOptions.activate` replaces it, and `AndroidOptionsInitializer` builds this provider from the options configuration callback, which `Sentry.init` runs before `activate`. A second `SentryAndroid.init` then shuts the previous executor down while the provider keeps the dead one. Either way the submitted work never runs, and from API 31 on the listener is the only source of the value. Pass `Runnable::run` instead. The callback maps the display info to a generation and stores it, so the binder thread the framework calls it on is the right place for it. The executor, its field and the `RejectedExecutionException` guard all go away. * chore: Move the changelog entry to Unreleased
1 parent aeae22a commit 0a9ff06

9 files changed

Lines changed: 788 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
### Features
6+
7+
- Report the cellular network technology generation in `device.connection_effective_type`, for example `4g` or `5g` ([#6146](https://github.com/getsentry/sentry-java/pull/6146))
8+
39
## 8.59.0
410

511
### Breaking Changes

‎sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,13 @@
1515
import android.os.SystemClock;
1616
import android.util.DisplayMetrics;
1717
import io.sentry.DateUtils;
18+
import io.sentry.IConnectionStatusProvider;
1819
import io.sentry.SentryLevel;
1920
import io.sentry.SentryOptions;
21+
import io.sentry.android.core.internal.util.AndroidConnectionStatusProvider;
2022
import io.sentry.android.core.internal.util.CpuInfoUtils;
2123
import io.sentry.android.core.internal.util.DeviceOrientations;
24+
import io.sentry.android.core.internal.util.NetworkConnection;
2225
import io.sentry.android.core.internal.util.RootChecker;
2326
import io.sentry.protocol.Device;
2427
import io.sentry.protocol.OperatingSystem;
@@ -228,8 +231,19 @@ private void setDeviceIO(
228231
}
229232

230233
if (device.getConnectionType() == null) {
231-
// wifi, ethernet or cellular, null if none
232-
device.setConnectionType(options.getConnectionStatusProvider().getConnectionType());
234+
final @NotNull IConnectionStatusProvider connectionStatusProvider =
235+
options.getConnectionStatusProvider();
236+
if (connectionStatusProvider instanceof AndroidConnectionStatusProvider) {
237+
// Reading both at once keeps the type and the technology describing the same network.
238+
final NetworkConnection connection =
239+
((AndroidConnectionStatusProvider) connectionStatusProvider).getConnection();
240+
// wifi, ethernet or cellular, null if none
241+
device.setConnectionType(connection.type);
242+
// 2g, 3g, 4g or 5g, null unless the device is on a known cellular technology
243+
device.setConnectionEffectiveType(connection.effectiveType);
244+
} else {
245+
device.setConnectionType(connectionStatusProvider.getConnectionType());
246+
}
233247
}
234248
}
235249

‎sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ public final class AndroidConnectionStatusProvider
4545
private final @NotNull BuildInfoProvider buildInfoProvider;
4646
private final @NotNull MonotonicTicker ticker;
4747
private final @NotNull List<IConnectionStatusObserver> connectionStatusObservers;
48+
private final @NotNull CellularNetworkTechnologyProvider cellularNetworkTechnologyProvider;
4849
private final @Nullable Handler handler;
4950
private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock();
5051
private volatile @Nullable NetworkCallback networkCallback;
@@ -94,6 +95,8 @@ public AndroidConnectionStatusProvider(
9495
this.cacheFreshUntil = Deadline.passed(ticker);
9596
this.handler = handler;
9697
this.connectionStatusObservers = new ArrayList<>();
98+
this.cellularNetworkTechnologyProvider =
99+
new CellularNetworkTechnologyProvider(this.context, options.getLogger(), buildInfoProvider);
97100

98101
capabilities[0] = NetworkCapabilities.NET_CAPABILITY_INTERNET;
99102
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.M) {
@@ -170,6 +173,24 @@ private boolean isNetworkEffectivelyConnected(
170173
return getConnectionType(context, options.getLogger(), buildInfoProvider);
171174
}
172175

176+
/**
177+
* The connection type and, for cellular connections, the generation of the network technology.
178+
*
179+
* <p>Both are derived from one cache read, so they always describe the same network instead of
180+
* straddling a connectivity change.
181+
*/
182+
public @NotNull NetworkConnection getConnection() {
183+
if (!isCacheValid()) {
184+
updateCache(null);
185+
}
186+
final @Nullable String connectionType = getConnectionTypeFromCache();
187+
if (!"cellular".equals(connectionType)) {
188+
return new NetworkConnection(connectionType, null);
189+
}
190+
return new NetworkConnection(
191+
connectionType, cellularNetworkTechnologyProvider.getCellularNetworkTechnology());
192+
}
193+
173194
private void ensureNetworkCallbackRegistered() {
174195
if (!ContextUtils.isForegroundImportance()) {
175196
return;
@@ -344,6 +365,9 @@ private boolean hasSignificantTransportChanges(
344365
if (registerNetworkCallback(
345366
context, options.getLogger(), buildInfoProvider, handler, callback)) {
346367
networkCallback = callback;
368+
// Only start listening once the network callback is registered, because unregistering is
369+
// skipped while there is no network callback, which would leave the listener running.
370+
cellularNetworkTechnologyProvider.register();
347371
options.getLogger().log(SentryLevel.DEBUG, "Network callback registered successfully");
348372
} else {
349373
options.getLogger().log(SentryLevel.WARNING, "Failed to register network callback");
@@ -459,6 +483,7 @@ private void unregisterNetworkCallback(final boolean clearObservers) {
459483
if (callbackRef != null) {
460484
unregisterNetworkCallback(context, options.getLogger(), callbackRef);
461485
}
486+
cellularNetworkTechnologyProvider.unregister();
462487
// Clear cached state
463488
cachedNetworkCapabilities = null;
464489
currentNetwork = null;
Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
package io.sentry.android.core.internal.util;
2+
3+
import android.Manifest;
4+
import android.annotation.SuppressLint;
5+
import android.content.Context;
6+
import android.os.Build;
7+
import android.telephony.TelephonyCallback;
8+
import android.telephony.TelephonyDisplayInfo;
9+
import android.telephony.TelephonyManager;
10+
import androidx.annotation.NonNull;
11+
import androidx.annotation.RequiresApi;
12+
import io.sentry.ILogger;
13+
import io.sentry.SentryLevel;
14+
import io.sentry.android.core.BuildInfoProvider;
15+
import io.sentry.android.core.ContextUtils;
16+
import org.jetbrains.annotations.ApiStatus;
17+
import org.jetbrains.annotations.NotNull;
18+
import org.jetbrains.annotations.Nullable;
19+
20+
/**
21+
* Reports the generation of the cellular network technology the device currently uses for data, for
22+
* example {@code 4g} or {@code 5g}.
23+
*
24+
* <p>From Android 12 (API 31) the value comes from {@link TelephonyCallback.DisplayInfoListener},
25+
* which requires no permission and reports what the device shows to the user. On older versions it
26+
* is read from {@link TelephonyManager#getDataNetworkType()}, which the SDK only calls when the
27+
* hosting app already holds one of the required permissions. The SDK never declares those
28+
* permissions itself, so apps without them simply get no technology reported.
29+
*/
30+
@ApiStatus.Internal
31+
public final class CellularNetworkTechnologyProvider {
32+
33+
public static final @NotNull String GENERATION_2G = "2g";
34+
public static final @NotNull String GENERATION_3G = "3g";
35+
public static final @NotNull String GENERATION_4G = "4g";
36+
public static final @NotNull String GENERATION_5G = "5g";
37+
38+
private final @NotNull Context context;
39+
private final @NotNull ILogger logger;
40+
private final @NotNull BuildInfoProvider buildInfoProvider;
41+
42+
/** Guards the registration of the display info listener. */
43+
private final @NotNull Object registrationLock = new Object();
44+
45+
/**
46+
* Set from {@link TelephonyCallback.DisplayInfoListener} on API 31 and above. Declared as {@link
47+
* Object} so that loading this class on older devices never has to resolve a type that does not
48+
* exist there.
49+
*/
50+
private volatile @Nullable Object displayInfoCallback;
51+
52+
private volatile @Nullable String displayInfoTechnology;
53+
54+
public CellularNetworkTechnologyProvider(
55+
final @NotNull Context context,
56+
final @NotNull ILogger logger,
57+
final @NotNull BuildInfoProvider buildInfoProvider) {
58+
this.context = ContextUtils.getApplicationContext(context);
59+
this.logger = logger;
60+
this.buildInfoProvider = buildInfoProvider;
61+
}
62+
63+
/**
64+
* The generation of the cellular network technology currently used for data, or {@code null} when
65+
* it is unknown.
66+
*/
67+
public @Nullable String getCellularNetworkTechnology() {
68+
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.S) {
69+
return displayInfoTechnology;
70+
}
71+
return getDataNetworkTechnology();
72+
}
73+
74+
/**
75+
* Starts listening for display info changes on API 31 and above. Does nothing on older versions,
76+
* where the technology is read on demand instead.
77+
*/
78+
@SuppressLint("NewApi")
79+
public void register() {
80+
if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.S) {
81+
return;
82+
}
83+
// Checking and storing the callback has to be atomic, otherwise concurrent callers can each
84+
// register a listener while only the last one is kept and can ever be unregistered.
85+
synchronized (registrationLock) {
86+
if (displayInfoCallback != null) {
87+
return;
88+
}
89+
final @Nullable TelephonyManager telephonyManager = getTelephonyManager();
90+
if (telephonyManager == null) {
91+
return;
92+
}
93+
try {
94+
final @NotNull DisplayInfoCallback callback = new DisplayInfoCallback(this);
95+
// The callback maps the display info to a generation and stores it, so it runs on the
96+
// binder thread the telephony framework calls it on. An executor of the SDK would add a
97+
// reference that goes stale: the options hold a no-op executor until
98+
// SentryOptions.activate replaces it, and a second SentryAndroid.init shuts the previous
99+
// one down.
100+
telephonyManager.registerTelephonyCallback(Runnable::run, callback);
101+
displayInfoCallback = callback;
102+
logger.log(SentryLevel.DEBUG, "Started listening for cellular network technology changes.");
103+
} catch (SecurityException | IllegalStateException | UnsupportedOperationException e) {
104+
// Devices without telephony support and processes that are not allowed to listen throw
105+
// here, and the technology is optional data.
106+
logger.log(
107+
SentryLevel.INFO, "Could not listen for cellular network technology changes.", e);
108+
}
109+
}
110+
}
111+
112+
/**
113+
* Stops listening for display info changes.
114+
*
115+
* <p>The last reported technology is kept. Monitoring stops when the app goes to the background,
116+
* and from API 31 on the listener is the only source, so discarding it would leave every
117+
* background event without a technology even though the connection type still resolves. It is
118+
* only ever paired with a connection that is cellular at the time the event is captured.
119+
*/
120+
@SuppressLint("NewApi")
121+
public void unregister() {
122+
synchronized (registrationLock) {
123+
final @Nullable Object callback = displayInfoCallback;
124+
if (callback == null) {
125+
return;
126+
}
127+
final @Nullable TelephonyManager telephonyManager = getTelephonyManager();
128+
if (telephonyManager == null) {
129+
// Keep the reference so a later unregister can still reach the registered callback.
130+
return;
131+
}
132+
try {
133+
telephonyManager.unregisterTelephonyCallback((TelephonyCallback) callback);
134+
displayInfoCallback = null;
135+
logger.log(SentryLevel.DEBUG, "Stopped listening for cellular network technology changes.");
136+
} catch (SecurityException | IllegalStateException | UnsupportedOperationException e) {
137+
logger.log(
138+
SentryLevel.INFO,
139+
"Could not stop listening for cellular network technology changes.",
140+
e);
141+
}
142+
}
143+
}
144+
145+
@SuppressLint({"MissingPermission", "InlinedApi", "NewApi"})
146+
private @Nullable String getDataNetworkTechnology() {
147+
if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.N) {
148+
// getDataNetworkType was added in API 24.
149+
return null;
150+
}
151+
// The SDK doesn't declare these permissions, so the technology is only available to apps that
152+
// already request one of them. READ_BASIC_PHONE_STATE only exists from API 31 on, where the
153+
// display info listener is used instead, but checking it is harmless.
154+
if (!Permissions.hasPermission(context, Manifest.permission.READ_PHONE_STATE)
155+
&& !Permissions.hasPermission(context, Manifest.permission.READ_BASIC_PHONE_STATE)) {
156+
return null;
157+
}
158+
final @Nullable TelephonyManager telephonyManager = getTelephonyManager();
159+
if (telephonyManager == null) {
160+
return null;
161+
}
162+
try {
163+
return networkTypeToGeneration(telephonyManager.getDataNetworkType());
164+
} catch (SecurityException | UnsupportedOperationException e) {
165+
// The permission can be revoked between the check above and the call, and devices without
166+
// telephony hardware throw UnsupportedOperationException from API 36 on.
167+
logger.log(SentryLevel.INFO, "Could not retrieve the cellular network technology.", e);
168+
return null;
169+
}
170+
}
171+
172+
private @Nullable TelephonyManager getTelephonyManager() {
173+
final @Nullable Object service = context.getSystemService(Context.TELEPHONY_SERVICE);
174+
if (!(service instanceof TelephonyManager)) {
175+
logger.log(SentryLevel.INFO, "TelephonyManager is not available.");
176+
return null;
177+
}
178+
return (TelephonyManager) service;
179+
}
180+
181+
/**
182+
* Maps a {@link TelephonyDisplayInfo} to a generation, preferring the override type so that a
183+
* device showing 5G to the user is also reported as 5G.
184+
*/
185+
@RequiresApi(api = Build.VERSION_CODES.S)
186+
@SuppressWarnings("deprecation")
187+
static @Nullable String toGeneration(final @NotNull TelephonyDisplayInfo displayInfo) {
188+
switch (displayInfo.getOverrideNetworkType()) {
189+
case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA:
190+
case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED:
191+
// Deprecated in favour of NR_ADVANCED, but still reported on Android 11. Its underlying
192+
// network type is LTE, so without this case a 5G mmWave connection reports 4g.
193+
case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA_MMWAVE:
194+
return GENERATION_5G;
195+
case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA:
196+
case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO:
197+
return GENERATION_4G;
198+
default:
199+
return networkTypeToGeneration(displayInfo.getNetworkType());
200+
}
201+
}
202+
203+
/** Maps a {@code TelephonyManager.NETWORK_TYPE_*} constant to a generation. */
204+
@SuppressWarnings("deprecation")
205+
static @Nullable String networkTypeToGeneration(final int networkType) {
206+
switch (networkType) {
207+
case TelephonyManager.NETWORK_TYPE_GPRS:
208+
case TelephonyManager.NETWORK_TYPE_EDGE:
209+
case TelephonyManager.NETWORK_TYPE_CDMA:
210+
case TelephonyManager.NETWORK_TYPE_1xRTT:
211+
case TelephonyManager.NETWORK_TYPE_IDEN:
212+
case TelephonyManager.NETWORK_TYPE_GSM:
213+
return GENERATION_2G;
214+
case TelephonyManager.NETWORK_TYPE_UMTS:
215+
case TelephonyManager.NETWORK_TYPE_EVDO_0:
216+
case TelephonyManager.NETWORK_TYPE_EVDO_A:
217+
case TelephonyManager.NETWORK_TYPE_EVDO_B:
218+
case TelephonyManager.NETWORK_TYPE_EHRPD:
219+
case TelephonyManager.NETWORK_TYPE_HSDPA:
220+
case TelephonyManager.NETWORK_TYPE_HSUPA:
221+
case TelephonyManager.NETWORK_TYPE_HSPA:
222+
case TelephonyManager.NETWORK_TYPE_HSPAP:
223+
case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
224+
return GENERATION_3G;
225+
case TelephonyManager.NETWORK_TYPE_LTE:
226+
case TelephonyManager.NETWORK_TYPE_IWLAN:
227+
return GENERATION_4G;
228+
case TelephonyManager.NETWORK_TYPE_NR:
229+
return GENERATION_5G;
230+
default:
231+
return null;
232+
}
233+
}
234+
235+
/** Caches the display info so that reading the technology never blocks on telephony. */
236+
@RequiresApi(api = Build.VERSION_CODES.S)
237+
private static final class DisplayInfoCallback extends TelephonyCallback
238+
implements TelephonyCallback.DisplayInfoListener {
239+
240+
private final @NotNull CellularNetworkTechnologyProvider provider;
241+
242+
DisplayInfoCallback(final @NotNull CellularNetworkTechnologyProvider provider) {
243+
this.provider = provider;
244+
}
245+
246+
@Override
247+
public void onDisplayInfoChanged(final @NonNull TelephonyDisplayInfo telephonyDisplayInfo) {
248+
provider.displayInfoTechnology = toGeneration(telephonyDisplayInfo);
249+
}
250+
}
251+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package io.sentry.android.core.internal.util;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.Nullable;
5+
6+
/** The connection type and the generation of the cellular network technology, if any. */
7+
@ApiStatus.Internal
8+
public final class NetworkConnection {
9+
/** Maps to the {@code network.connection.type} attribute, {@code null} when unknown. */
10+
public final @Nullable String type;
11+
12+
/**
13+
* Maps to the {@code network.connection.effective_type} attribute, for example {@code 5g}. {@code
14+
* null} when the connection is not cellular or the technology is unknown.
15+
*/
16+
public final @Nullable String effectiveType;
17+
18+
NetworkConnection(final @Nullable String type, final @Nullable String effectiveType) {
19+
this.type = type;
20+
this.effectiveType = effectiveType;
21+
}
22+
}

0 commit comments

Comments
 (0)