text
stringlengths
1
474
Project view.Next, create a MethodChannel and set a MethodCallHandler
inside the configureFlutterEngine() method.
Make sure to use the same channel name as was used on the
Flutter client side.
<code_start>import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// This method is invoked on the main thread.
// TODO
}
);
}
}<code_end>
Add the Android Java code that uses the Android battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native Android app.First, add the needed imports at the top of the file:
<code_start>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;
import android.os.Bundle;<code_end>
Then add the following as a new method in the activity class,
below the configureFlutterEngine() method:
<code_start>private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
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);
}
return batteryLevel;
}<code_end>
Finally, complete the setMethodCallHandler() method added earlier.
You need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. The implementation of
this platform method calls the Android code written
in the previous step, and returns a response for both
the success and error cases using the result argument.
If an unknown method is called, report that instead.Remove the following code:
<code_start>(call, result) -> {
// This method is invoked on the main thread.
// TODO
}<code_end>
And replace with the following:
<code_start>(call, result) -> {
// This method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}<code_end>
You should now be able to run the app on Android. If using the Android
Emulator, set the battery level in the Extended Controls panel
accessible from the … button in the toolbar.<topic_end>
<topic_start>
Step 4: Add an iOS platform-specific implementation
Start by opening the iOS host portion of your Flutter app in Xcode:Start Xcode.Select the menu item File > Open….Navigate to the directory holding your Flutter app, and select the ios
folder inside it. Click OK.Add support for Swift in the standard template setup that uses Objective-C:Expand Runner > Runner in the Project navigator.Open the file AppDelegate.swift located under Runner > Runner
in the Project navigator.Override the application:didFinishLaunchingWithOptions: function and create
a FlutterMethodChannel tied to the channel name
samples.flutter.dev/battery:
<code_start>@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",
binaryMessenger: controller.binaryMessenger)
batteryChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
// This method is invoked on the UI thread.
// Handle battery messages.
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}<code_end>
Next, add the iOS Swift code that uses the iOS battery APIs to retrieve