Commit 3dfe225c authored by Sarah Zakarias's avatar Sarah Zakarias Committed by GitHub

Add charging status to Swift version of Platform Channel example (#9436)

parent b52d6594
...@@ -11,5 +11,6 @@ ...@@ -11,5 +11,6 @@
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" /> <orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" /> <orderEntry type="library" name="Dart Packages" level="project" />
<orderEntry type="library" name="Dart SDK" level="application" />
</component> </component>
</module> </module>
\ No newline at end of file
...@@ -6,7 +6,8 @@ import UIKit ...@@ -6,7 +6,8 @@ import UIKit
import Flutter import Flutter
@UIApplicationMain @UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate { @objc class AppDelegate: FlutterAppDelegate, FlutterStreamHandler {
private var eventReceiver: FlutterEventReceiver?;
override func application( override func application(
_ application: UIApplication, _ application: UIApplication,
...@@ -17,17 +18,20 @@ import Flutter ...@@ -17,17 +18,20 @@ import Flutter
batteryChannel.setMethodCallHandler({ batteryChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: FlutterResultReceiver) -> Void in (call: FlutterMethodCall, result: FlutterResultReceiver) -> Void in
if ("getBatteryLevel" == call.method) { if ("getBatteryLevel" == call.method) {
receiveBatteryLevel(result: result); self.receiveBatteryLevel(result: result);
} else { } else {
result(FlutterMethodNotImplemented); result(FlutterMethodNotImplemented);
} }
} }
); );
let chargingChannel = FlutterEventChannel.init(name: "samples.flutter.io/charging",
binaryMessenger: controller);
chargingChannel.setStreamHandler(self);
return true return true
} }
}
private func receiveBatteryLevel(result: FlutterResultReceiver) { private func receiveBatteryLevel(result: FlutterResultReceiver) {
let device = UIDevice.current; let device = UIDevice.current;
device.isBatteryMonitoringEnabled = true; device.isBatteryMonitoringEnabled = true;
if (device.batteryState == UIDeviceBatteryState.unknown) { if (device.batteryState == UIDeviceBatteryState.unknown) {
...@@ -37,4 +41,47 @@ private func receiveBatteryLevel(result: FlutterResultReceiver) { ...@@ -37,4 +41,47 @@ private func receiveBatteryLevel(result: FlutterResultReceiver) {
} else { } else {
result(Int(device.batteryLevel * 100)); result(Int(device.batteryLevel * 100));
} }
}
public func onListen(withArguments arguments: Any?,
eventReceiver: @escaping FlutterEventReceiver) -> FlutterError? {
self.eventReceiver = eventReceiver;
UIDevice.current.isBatteryMonitoringEnabled = true;
NotificationCenter.default.addObserver(
self,
selector: #selector(onBatteryStateDidChange),
name: NSNotification.Name.UIDeviceBatteryStateDidChange,
object: nil)
return nil;
}
@objc private func onBatteryStateDidChange(notification: NSNotification) {
if (eventReceiver == nil) {
return;
}
let state = UIDevice.current.batteryState;
switch state {
case UIDeviceBatteryState.full:
eventReceiver!("charging");
break;
case UIDeviceBatteryState.charging:
eventReceiver!("charging");
break;
case UIDeviceBatteryState.unplugged:
eventReceiver!("discharging");
break;
default:
eventReceiver!(FlutterError.init(code: "UNAVAILABLE",
message: "Charging status unavailable",
details: nil));
break;
}
}
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
NotificationCenter.default.removeObserver(self);
eventReceiver = nil;
return nil;
}
} }
...@@ -13,36 +13,67 @@ class PlatformChannel extends StatefulWidget { ...@@ -13,36 +13,67 @@ class PlatformChannel extends StatefulWidget {
} }
class _PlatformChannelState extends State<PlatformChannel> { class _PlatformChannelState extends State<PlatformChannel> {
static const PlatformMethodChannel platform = const PlatformMethodChannel('samples.flutter.io/battery'); static const PlatformMethodChannel methodChannel =
String _batteryLevel = ''; const PlatformMethodChannel('samples.flutter.io/battery');
static const PlatformEventChannel eventChannel =
const PlatformEventChannel('samples.flutter.io/charging');
String _batteryLevel = 'Battery level: unknown.';
String _chargingStatus = 'Battery status: unknown.';
Future<Null> _getBatteryLevel() async { Future<Null> _getBatteryLevel() async {
String batteryLevel; String batteryLevel;
try { try {
final int result = await platform.invokeMethod('getBatteryLevel'); final int result = await methodChannel.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result % .'; batteryLevel = 'Battery level: $result%.';
} on PlatformException catch (e) { } on PlatformException {
batteryLevel = "Failed to get battery level: '${e.message}'."; batteryLevel = "Failed to get battery level.";
} }
setState(() { setState(() {
_batteryLevel = batteryLevel; _batteryLevel = batteryLevel;
}); });
} }
@override
void initState() {
super.initState();
eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
}
void _onEvent(String event) {
setState(() {
_chargingStatus =
"Battery status: ${event == 'charging' ? '' : 'dis'}charging.";
});
}
void _onError(PlatformException error) {
setState(() {
_chargingStatus = "Battery status: unknown.";
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new Material( return new Material(
child: new Center(
child: new Column( child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[ children: <Widget>[
new RaisedButton( new Column(
child: const Text('Get Battery Level'), mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(_batteryLevel, key: const Key('Battery level label')),
new Padding(
padding: const EdgeInsets.all(16.0),
child: new RaisedButton(
child: const Text('Refresh'),
onPressed: _getBatteryLevel, onPressed: _getBatteryLevel,
), ),
new Text(_batteryLevel, key: const Key('Battery level label')), ),
], ],
), ),
new Text(_chargingStatus),
],
), ),
); );
} }
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
</content> </content>
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" /> <orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart SDK" level="application" />
<orderEntry type="library" name="Dart Packages" level="project" /> <orderEntry type="library" name="Dart Packages" level="project" />
</component> </component>
</module> </module>
\ No newline at end of file
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