Commit f0e71cb1 authored by Sarah Zakarias's avatar Sarah Zakarias Committed by GitHub

Add support for earlier Android versions in platform_services example (#8621)

* Add support for earlier Android versions

* Addressed comments
parent cabd58db
...@@ -4,6 +4,9 @@ ...@@ -4,6 +4,9 @@
package com.example.flutter; package com.example.flutter;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager; import android.os.BatteryManager;
import android.os.Build.VERSION; import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES; import android.os.Build.VERSION_CODES;
...@@ -36,11 +39,21 @@ public class ExampleActivity extends FlutterActivity { ...@@ -36,11 +39,21 @@ public class ExampleActivity extends FlutterActivity {
} }
private void getBatteryLevel(Response response) { private void getBatteryLevel(Response response) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { 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 {
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 { } else {
response.error("Not available", "Battery level not available.", null); response.error("UNAVAILABLE", "Battery level not available.", null);
} }
} }
} }
...@@ -24,7 +24,7 @@ class _PlatformServicesState extends State<PlatformServices> { ...@@ -24,7 +24,7 @@ class _PlatformServicesState extends State<PlatformServices> {
} else { } else {
try { try {
final int result = await platform.invokeMethod('getBatteryLevel'); final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result. %'; batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e) { } on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'."; batteryLevel = "Failed to get battery level: '${e.message}'.";
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment