xref: /aosp_15_r20/external/cronet/base/android/radio_utils.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/android/radio_utils.h"
6 
7 #include <optional>
8 
9 #include "base/base_jni/RadioUtils_jni.h"
10 
11 namespace base {
12 namespace android {
13 
14 namespace {
15 
16 RadioUtils::OverrideForTesting* g_overrider_for_tests = nullptr;
17 
InitializeIsSupported()18 bool InitializeIsSupported() {
19   JNIEnv* env = AttachCurrentThread();
20   return Java_RadioUtils_isSupported(env);
21 }
22 }  // namespace
23 
OverrideForTesting()24 RadioUtils::OverrideForTesting::OverrideForTesting() {
25   DCHECK(!g_overrider_for_tests);
26   g_overrider_for_tests = this;
27 }
28 
~OverrideForTesting()29 RadioUtils::OverrideForTesting::~OverrideForTesting() {
30   DCHECK(g_overrider_for_tests);
31   g_overrider_for_tests = nullptr;
32 }
33 
IsSupported()34 bool RadioUtils::IsSupported() {
35   static const bool kIsSupported = InitializeIsSupported();
36   return kIsSupported;
37 }
38 
GetConnectionType()39 RadioConnectionType RadioUtils::GetConnectionType() {
40   if (g_overrider_for_tests) {
41     // If GetConnectionType is being used in tests
42     return g_overrider_for_tests->GetConnectionType();
43   }
44   if (!IsSupported())
45     return RadioConnectionType::kUnknown;
46 
47   JNIEnv* env = AttachCurrentThread();
48   if (Java_RadioUtils_isWifiConnected(env)) {
49     return RadioConnectionType::kWifi;
50   } else {
51     return RadioConnectionType::kCell;
52   }
53 }
54 
GetCellSignalLevel()55 std::optional<RadioSignalLevel> RadioUtils::GetCellSignalLevel() {
56   if (!IsSupported())
57     return std::nullopt;
58 
59   JNIEnv* env = AttachCurrentThread();
60   int signal_level = Java_RadioUtils_getCellSignalLevel(env);
61   if (signal_level < 0) {
62     return std::nullopt;
63   } else {
64     return static_cast<RadioSignalLevel>(signal_level);
65   }
66 }
67 
GetCellDataActivity()68 std::optional<RadioDataActivity> RadioUtils::GetCellDataActivity() {
69   if (!IsSupported())
70     return std::nullopt;
71 
72   JNIEnv* env = AttachCurrentThread();
73   return static_cast<RadioDataActivity>(
74       Java_RadioUtils_getCellDataActivity(env));
75 }
76 
77 }  // namespace android
78 }  // namespace base
79