Skip to content

Commit

Permalink
[Android Connectivity] Set app package on Intent used to invoke conte…
Browse files Browse the repository at this point in the history
…xt receiver for network callback (#20651)

* No need to export app specific broadcast receivers

We are the only ones invoking these, so there's no need to export.  The export made things 'work' on android 14 because of changes to that api level, but that wasn't the most correct fix.

* Set package on connectivity intent

With changes in android 14, we need to scope the connectivity intent we use to trigger our own internal broadcast receiver to the current app package (which we get from the application context).
  • Loading branch information
Redth authored and rmarinho committed Feb 22, 2024
1 parent 75be7fa commit 49bba62
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 11 deletions.
10 changes: 5 additions & 5 deletions src/Essentials/src/Battery/Battery.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ partial class BatteryImplementation : IBattery
void StartEnergySaverListeners()
{
powerReceiver = new EnergySaverBroadcastReceiver(OnEnergySaverChanged);
PlatformUtils.RegisterBroadcastReceiver(powerReceiver, new IntentFilter(PowerManager.ActionPowerSaveModeChanged), false);
PlatformUtils.RegisterBroadcastReceiver(powerReceiver, new IntentFilter(PowerManager.ActionPowerSaveModeChanged));
}

void StopEnergySaverListeners()
Expand Down Expand Up @@ -52,7 +52,7 @@ void StartBatteryListeners()
Permissions.EnsureDeclared<Permissions.Battery>();

batteryReceiver = new BatteryBroadcastReceiver(OnBatteryInfoChanged);
PlatformUtils.RegisterBroadcastReceiver(batteryReceiver, new IntentFilter(Intent.ActionBatteryChanged), false);
PlatformUtils.RegisterBroadcastReceiver(batteryReceiver, new IntentFilter(Intent.ActionBatteryChanged));
}

void StopBatteryListeners()
Expand All @@ -76,7 +76,7 @@ public double ChargeLevel
Permissions.EnsureDeclared<Permissions.Battery>();

using (var filter = new IntentFilter(Intent.ActionBatteryChanged))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter, false))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter))
{
if (battery is null)
return -1; // Unknown
Expand All @@ -99,7 +99,7 @@ public BatteryState State
Permissions.EnsureDeclared<Permissions.Battery>();

using (var filter = new IntentFilter(Intent.ActionBatteryChanged))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter, false))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter))
{
if (battery is null)
return BatteryState.Unknown;
Expand Down Expand Up @@ -129,7 +129,7 @@ public BatteryPowerSource PowerSource
Permissions.EnsureDeclared<Permissions.Battery>();

using (var filter = new IntentFilter(Intent.ActionBatteryChanged))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter, false))
using (var battery = PlatformUtils.RegisterBroadcastReceiver(null, filter))
{
if (battery is null)
return BatteryPowerSource.Unknown;
Expand Down
51 changes: 48 additions & 3 deletions src/Essentials/src/Connectivity/Connectivity.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ partial class ConnectivityImplementation : IConnectivity
/// Unique identifier for the connectivity changed action on Android.
/// </summary>
public const string ConnectivityChangedAction = "com.maui.essentials.ESSENTIALS_CONNECTIVITY_CHANGED";
static Intent connectivityIntent = new Intent(ConnectivityChangedAction);


static ConnectivityManager connectivityManager;

static ConnectivityManager ConnectivityManager =>
Expand Down Expand Up @@ -45,13 +44,15 @@ void StartListeners()

conectivityReceiver = new ConnectivityBroadcastReceiver(OnConnectivityChanged);

PlatformUtils.RegisterBroadcastReceiver(conectivityReceiver, filter, true);
PlatformUtils.RegisterBroadcastReceiver(conectivityReceiver, filter);
}

void StopListeners()
{
if (conectivityReceiver == null)
{
return;
}

try
{
Expand All @@ -77,11 +78,15 @@ void StopListeners()
void RegisterNetworkCallback()
{
if (!OperatingSystem.IsAndroidVersionAtLeast(24))
{
return;
}

var manager = ConnectivityManager;
if (manager == null)
{
return;
}

var request = new NetworkRequest.Builder().Build();
networkCallback = new EssentialsNetworkCallback();
Expand All @@ -91,11 +96,15 @@ void RegisterNetworkCallback()
void UnregisterNetworkCallback()
{
if (!OperatingSystem.IsAndroidVersionAtLeast(24))
{
return;
}

var manager = ConnectivityManager;
if (manager == null || networkCallback == null)
{
return;
}

manager.UnregisterNetworkCallback(networkCallback);

Expand All @@ -104,6 +113,14 @@ void UnregisterNetworkCallback()

class EssentialsNetworkCallback : ConnectivityManager.NetworkCallback
{
readonly Intent connectivityIntent;

public EssentialsNetworkCallback()
{
connectivityIntent = new Intent(ConnectivityChangedAction);
connectivityIntent.SetPackage(Application.Context.PackageName);
}

public override void OnAvailable(Network network) =>
Application.Context.SendBroadcast(connectivityIntent);

Expand Down Expand Up @@ -159,15 +176,19 @@ public NetworkAccess NetworkAccess
var capabilities = manager.GetNetworkCapabilities(network);

if (capabilities == null)
{
continue;
}

#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning disable CA1416 // Validate platform compatibility
#pragma warning disable CA1422 // Validate platform compatibility
var info = manager.GetNetworkInfo(network);

if (info == null || !info.IsAvailable)
{
continue;
}
#pragma warning restore CS0618 // Type or member is obsolete

// Check to see if it has the internet capability
Expand Down Expand Up @@ -200,12 +221,18 @@ void ProcessAllNetworkInfo()
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 CA1422 // Validate platform compatibility
#pragma warning restore CA1416 // Validate platform compatibility
#pragma warning restore CS0618 // Type or member is obsolete
Expand Down Expand Up @@ -250,15 +277,19 @@ public IEnumerable<ConnectionProfile> ConnectionProfiles

var p = ProcessNetworkInfo(info);
if (p.HasValue)
{
yield return p.Value;
}
}

#pragma warning disable CS0618 // Type or member is obsolete
static ConnectionProfile? ProcessNetworkInfo(NetworkInfo info)
{

if (info == null || !info.IsAvailable || !info.IsConnectedOrConnecting)
{
return null;
}


return GetConnectionType(info.Type, info.TypeName);
Expand Down Expand Up @@ -289,22 +320,34 @@ internal static ConnectionProfile GetConnectionType(ConnectivityType connectivit
return ConnectionProfile.Unknown;
default:
if (string.IsNullOrWhiteSpace(typeName))
{
return ConnectionProfile.Unknown;
}

if (typeName.Contains("mobile", StringComparison.OrdinalIgnoreCase))
{
return ConnectionProfile.Cellular;
}

if (typeName.Contains("wimax", StringComparison.OrdinalIgnoreCase))
{
return ConnectionProfile.Cellular;
}

if (typeName.Contains("wifi", StringComparison.OrdinalIgnoreCase))
{
return ConnectionProfile.WiFi;
}

if (typeName.Contains("ethernet", StringComparison.OrdinalIgnoreCase))
{
return ConnectionProfile.Ethernet;
}

if (typeName.Contains("bluetooth", StringComparison.OrdinalIgnoreCase))
{
return ConnectionProfile.Bluetooth;
}

return ConnectionProfile.Unknown;
}
Expand Down Expand Up @@ -335,7 +378,9 @@ 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 != ConnectivityImplementation.ConnectivityChangedAction)
#pragma warning restore CS0618 // Type or member is obsolete
{
return;
}

// await 1500ms to ensure that the the connection manager updates
await Task.Delay(1500);
Expand Down
5 changes: 2 additions & 3 deletions src/Essentials/src/Platform/PlatformUtils.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ internal static int NextRequestCode()
return requestCode;
}

internal static Intent? RegisterBroadcastReceiver(BroadcastReceiver? receiver, IntentFilter filter, bool exported)
internal static Intent? RegisterBroadcastReceiver(BroadcastReceiver? receiver, IntentFilter filter)
{
#if ANDROID34_0_OR_GREATER
if (OperatingSystem.IsAndroidVersionAtLeast(34))
{
var flags = exported ? ReceiverFlags.Exported : ReceiverFlags.NotExported;
return Application.Context.RegisterReceiver(receiver, filter, flags);
return Application.Context.RegisterReceiver(receiver, filter, ReceiverFlags.NotExported);
}
#endif
return Application.Context.RegisterReceiver(receiver, filter);
Expand Down

0 comments on commit 49bba62

Please sign in to comment.