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

* Add support for earlier Android versions

* Addressed comments
This commit is contained in:
Sarah Zakarias 2017-03-09 10:41:39 +01:00 committed by GitHub
parent cabd58dbb2
commit f0e71cb15c
2 changed files with 17 additions and 4 deletions

View file

@ -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);
}
}
}

View file

@ -24,7 +24,7 @@ class _PlatformServicesState extends State<PlatformServices> {
} 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}'.";
}