Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ public void testNullIntent() {
assertEquals(1, state.getBatteryVelocity());
}

public void testTooManyReceivers() {
Context mockContext = mock(Context.class);
when(mockContext.registerReceiver(isNull(), any()))
.thenThrow(new IllegalStateException("Too many receivers"));

BatteryState state = BatteryState.get(mockContext);

assertNull(state.getBatteryLevel());
assertFalse(state.isPowerConnected());
assertEquals(1, state.getBatteryVelocity());
}

public void testEmptyIntent() {
final Context mockContext = mock(Context.class);
when(mockContext.registerReceiver(isNull(), any())).thenReturn(new Intent());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import com.google.firebase.crashlytics.internal.Logger;

/** A utility class representing the state of the battery. */
class BatteryState {
Expand Down Expand Up @@ -66,11 +67,16 @@ public static BatteryState get(Context context) {
boolean powerConnected = false;
Float level = null;

final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
final Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
if (batteryStatusIntent != null) {
powerConnected = isPowerConnected(batteryStatusIntent);
level = getLevel(batteryStatusIntent);
try {
final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
final Intent batteryStatusIntent = context.registerReceiver(/*receiver=*/ null, ifilter);
if (batteryStatusIntent != null) {
powerConnected = isPowerConnected(batteryStatusIntent);
level = getLevel(batteryStatusIntent);
}
} catch (IllegalStateException ex) {
// This happens on some devices when the app registers too many receivers.
Logger.getLogger().e("An error occurred getting battery state.", ex);
}

return new BatteryState(level, powerConnected);
Expand Down