diff --git a/examples/platform_services/android/app/src/main/java/com/example/flutter/ExampleActivity.java b/examples/platform_services/android/app/src/main/java/com/example/flutter/ExampleActivity.java index c223da80219..7f2f288718a 100644 --- a/examples/platform_services/android/app/src/main/java/com/example/flutter/ExampleActivity.java +++ b/examples/platform_services/android/app/src/main/java/com/example/flutter/ExampleActivity.java @@ -4,6 +4,9 @@ package com.example.flutter; +import android.content.ContextWrapper; +import android.content.Intent; +import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; @@ -36,11 +39,21 @@ public class ExampleActivity extends FlutterActivity { } private void getBatteryLevel(Response response) { - BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); + int batteryLevel = -1; if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { - response.success(batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)); + BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); + batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); } else { - response.error("Not available", "Battery level not available.", null); + Intent intent = new ContextWrapper(getApplicationContext()). + registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) / + intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); + } + + if (batteryLevel != -1) { + response.success(batteryLevel); + } else { + response.error("UNAVAILABLE", "Battery level not available.", null); } } } diff --git a/examples/platform_services/lib/main.dart b/examples/platform_services/lib/main.dart index f1a7ab032b7..6bf7ff84633 100644 --- a/examples/platform_services/lib/main.dart +++ b/examples/platform_services/lib/main.dart @@ -24,7 +24,7 @@ class _PlatformServicesState extends State { } else { try { final int result = await platform.invokeMethod('getBatteryLevel'); - batteryLevel = 'Battery level at $result. %'; + batteryLevel = 'Battery level at $result % .'; } on PlatformException catch (e) { batteryLevel = "Failed to get battery level: '${e.message}'."; }