mirror of
https://github.com/flutter/flutter.git
synced 2025-06-03 00:51:18 +00:00
Add support for earlier Android versions in platform_services example (#8621)
* Add support for earlier Android versions * Addressed comments
This commit is contained in:
parent
cabd58dbb2
commit
f0e71cb15c
@ -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 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
} 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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}'.";
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user