This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 505
/
Connectivity.android.cs
327 lines (274 loc) · 12.3 KB
/
Connectivity.android.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.Content;
using Android.Net;
using Android.OS;
using Debug = System.Diagnostics.Debug;
namespace Xamarin.Essentials
{
public partial class Connectivity
{
static ConnectivityBroadcastReceiver conectivityReceiver;
static Intent connectivityIntent = new Intent(Platform.EssentialsConnectivityChanged);
static EssentialsNetworkCallback networkCallback;
static void StartListeners()
{
Permissions.EnsureDeclared<Permissions.NetworkState>();
var filter = new IntentFilter();
if (Platform.HasApiLevelN)
{
RegisterNetworkCallback();
filter.AddAction(Platform.EssentialsConnectivityChanged);
}
else
{
#pragma warning disable CS0618 // Type or member is obsolete
filter.AddAction(ConnectivityManager.ConnectivityAction);
#pragma warning restore CS0618 // Type or member is obsolete
}
conectivityReceiver = new ConnectivityBroadcastReceiver(OnConnectivityChanged);
Platform.AppContext.RegisterReceiver(conectivityReceiver, filter);
}
static void StopListeners()
{
if (conectivityReceiver == null)
return;
try
{
UnregisterNetworkCallback();
}
catch
{
Debug.WriteLine("Connectivity receiver already unregistered. Disposing of it.");
}
try
{
Platform.AppContext.UnregisterReceiver(conectivityReceiver);
}
catch (Java.Lang.IllegalArgumentException)
{
Debug.WriteLine("Connectivity receiver already unregistered. Disposing of it.");
}
conectivityReceiver.Dispose();
conectivityReceiver = null;
}
static void RegisterNetworkCallback()
{
if (!Platform.HasApiLevelN)
return;
var manager = Platform.ConnectivityManager;
if (manager == null)
return;
var request = new NetworkRequest.Builder().Build();
networkCallback = new EssentialsNetworkCallback();
manager.RegisterNetworkCallback(request, networkCallback);
}
static void UnregisterNetworkCallback()
{
if (!Platform.HasApiLevelN)
return;
var manager = Platform.ConnectivityManager;
if (manager == null || networkCallback == null)
return;
manager.UnregisterNetworkCallback(networkCallback);
networkCallback?.Dispose();
networkCallback = null;
}
class EssentialsNetworkCallback : ConnectivityManager.NetworkCallback
{
public override void OnAvailable(Network network) => Platform.AppContext.SendBroadcast(connectivityIntent);
public override void OnLost(Network network) => Platform.AppContext.SendBroadcast(connectivityIntent);
public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) => Platform.AppContext.SendBroadcast(connectivityIntent);
public override void OnUnavailable() => Platform.AppContext.SendBroadcast(connectivityIntent);
public override void OnLinkPropertiesChanged(Network network, LinkProperties linkProperties) => Platform.AppContext.SendBroadcast(connectivityIntent);
public override void OnLosing(Network network, int maxMsToLive) => Platform.AppContext.SendBroadcast(connectivityIntent);
}
static NetworkAccess IsBetterAccess(NetworkAccess currentAccess, NetworkAccess newAccess) =>
newAccess > currentAccess ? newAccess : currentAccess;
static NetworkAccess PlatformNetworkAccess
{
get
{
Permissions.EnsureDeclared<Permissions.NetworkState>();
try
{
var currentAccess = NetworkAccess.None;
var manager = Platform.ConnectivityManager;
if (Platform.HasApiLevel(BuildVersionCodes.Lollipop))
{
#pragma warning disable CS0618 // Type or member is obsolete
var networks = manager.GetAllNetworks();
#pragma warning restore CS0618 // Type or member is obsolete
// some devices running 21 and 22 only use the older api.
if (networks.Length == 0 && (int)Build.VERSION.SdkInt < 23)
{
ProcessAllNetworkInfo();
return currentAccess;
}
foreach (var network in networks)
{
try
{
var capabilities = manager.GetNetworkCapabilities(network);
if (capabilities == null)
continue;
#pragma warning disable CS0618 // Type or member is obsolete
var info = manager.GetNetworkInfo(network);
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning disable CS0618 // Type or member is obsolete
if (info == null || !info.IsAvailable)
#pragma warning restore CS0618 // Type or member is obsolete
continue;
// Check to see if it has the internet capability
if (!capabilities.HasCapability(NetCapability.Internet))
{
// Doesn't have internet, but local is possible
currentAccess = IsBetterAccess(currentAccess, NetworkAccess.Local);
continue;
}
ProcessNetworkInfo(info);
}
catch
{
// there is a possibility, but don't worry
}
}
}
else
{
ProcessAllNetworkInfo();
}
void ProcessAllNetworkInfo()
{
#pragma warning disable CS0618 // Type or member is obsolete
foreach (var info in manager.GetAllNetworkInfo())
#pragma warning restore CS0618 // Type or member is obsolete
{
ProcessNetworkInfo(info);
}
}
#pragma warning disable CS0618 // Type or member is obsolete
void ProcessNetworkInfo(NetworkInfo info)
{
if (info == null || !info.IsAvailable)
return;
if (info.IsConnected)
currentAccess = IsBetterAccess(currentAccess, NetworkAccess.Internet);
else if (info.IsConnectedOrConnecting)
currentAccess = IsBetterAccess(currentAccess, NetworkAccess.ConstrainedInternet);
#pragma warning restore CS0618 // Type or member is obsolete
}
return currentAccess;
}
catch (Exception e)
{
Debug.WriteLine("Unable to get connected state - do you have ACCESS_NETWORK_STATE permission? - error: {0}", e);
return NetworkAccess.Unknown;
}
}
}
static IEnumerable<ConnectionProfile> PlatformConnectionProfiles
{
get
{
Permissions.EnsureDeclared<Permissions.NetworkState>();
var manager = Platform.ConnectivityManager;
if (Platform.HasApiLevel(BuildVersionCodes.Lollipop))
{
#pragma warning disable CS0618 // Type or member is obsolete
foreach (var network in manager.GetAllNetworks())
{
NetworkInfo info = null;
try
{
info = manager.GetNetworkInfo(network);
}
catch
{
// there is a possibility, but don't worry about it
}
#pragma warning restore CS0618 // Type or member is obsolete
var p = ProcessNetworkInfo(info);
if (p.HasValue)
yield return p.Value;
}
}
else
{
#pragma warning disable CS0618 // Type or member is obsolete
foreach (var info in manager.GetAllNetworkInfo())
#pragma warning restore CS0618 // Type or member is obsolete
{
var p = ProcessNetworkInfo(info);
if (p.HasValue)
yield return p.Value;
}
}
#pragma warning disable CS0618 // Type or member is obsolete
ConnectionProfile? ProcessNetworkInfo(NetworkInfo info)
{
if (info == null || !info.IsAvailable || !info.IsConnectedOrConnecting)
return null;
return GetConnectionType(info.Type, info.TypeName);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
}
internal static ConnectionProfile GetConnectionType(ConnectivityType connectivityType, string typeName)
{
switch (connectivityType)
{
case ConnectivityType.Ethernet:
return ConnectionProfile.Ethernet;
case ConnectivityType.Wifi:
return ConnectionProfile.WiFi;
case ConnectivityType.Bluetooth:
return ConnectionProfile.Bluetooth;
case ConnectivityType.Wimax:
case ConnectivityType.Mobile:
case ConnectivityType.MobileDun:
case ConnectivityType.MobileHipri:
case ConnectivityType.MobileMms:
return ConnectionProfile.Cellular;
case ConnectivityType.Dummy:
return ConnectionProfile.Unknown;
default:
if (string.IsNullOrWhiteSpace(typeName))
return ConnectionProfile.Unknown;
var typeNameLower = typeName.ToLowerInvariant();
if (typeNameLower.Contains("mobile"))
return ConnectionProfile.Cellular;
if (typeNameLower.Contains("wimax"))
return ConnectionProfile.Cellular;
if (typeNameLower.Contains("wifi"))
return ConnectionProfile.WiFi;
if (typeNameLower.Contains("ethernet"))
return ConnectionProfile.Ethernet;
if (typeNameLower.Contains("bluetooth"))
return ConnectionProfile.Bluetooth;
return ConnectionProfile.Unknown;
}
}
}
[BroadcastReceiver(Enabled = true, Exported = false, Label = "Essentials Connectivity Broadcast Receiver")]
class ConnectivityBroadcastReceiver : BroadcastReceiver
{
Action onChanged;
public ConnectivityBroadcastReceiver()
{
}
public ConnectivityBroadcastReceiver(Action onChanged) =>
this.onChanged = onChanged;
public override async void OnReceive(Context context, Intent intent)
{
#pragma warning disable CS0618 // Type or member is obsolete
if (intent.Action != ConnectivityManager.ConnectivityAction && intent.Action != Platform.EssentialsConnectivityChanged)
#pragma warning restore CS0618 // Type or member is obsolete
return;
// await 1500ms to ensure that the the connection manager updates
await Task.Delay(1500);
onChanged?.Invoke();
}
}
}