In this tutorial we make a small beat function that calls the original Kotlin code of the android to read the value of the battery level.
Flutter uses a flexible system that makes it possible to call platform-specific APIs that are available in both Kotlin and Java code on Android.
The built-in support of the Flutter API does not depend on code generation, but on a flexible message style.
Basically, the Flutter part of the application sends messages to the iOS or Android part of the application via a platform channel. The host listens to the platform’s channel, receives the message and calls up the platform API using its own programming language, and then sends the response back to the client (the floating part of the application).
For this to work, we have to do the following:
- Create a new Flutter project,
- Create a MethodChannel object,
- Set a function that recalls the original Android code,
- Prepare the user interface to display the result,
- Introduce a new feature in Swift that allows you to read the battery level.
Floating
The channel is used to communicate with the platform plug-ins via asynchronous method calls. Method calls are binary encoded before they are sent, and the resulting binary results are decoded into Dart values. The used MethodCodec must be compatible with the plugin of the platform.
1. Creating a new Flutter project
First we need to create a new Flutter project in Android Studio (or any other IDE you use). If you don’t know how to create a project, you can consult the Hello World App in Flutter tutorial.
2. Creation of a method channel
Then we’ll build a canal. We will use a MethodChannel method with a platform that returns the level of the host battery by declaring the following constant:
static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;
3. Create a Flutter function calling Android code.
Here is an example of a short code that uses the MethodChannel and shows how to write a function to get the battery level of the device.
Future _getBatteryLevel() async {
String batteryLevel ;
try {
final int result = wait platform.invokeMethod(‘getBatteryLevel’)) ;
batteryLevel = ‘Battery level in $result % . } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;} } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;}.
setState(() {
_battery level = battery level;
});
})
As you can see in the code, we have created a Future function called _getBatteryLevel() that waits for platform.invokeMethod(‘getBatteryLevel’), which we will discuss in more detail in the section on Android functions. The Flutter application first checks the platform. As soon as the platform is confirmed, the application listens to the platform channel and checks the called function.
4. Piston interface for displaying results
As you can see, we have declared a string variable _battery level and assigned the value of the battery level. Next, we explained the future empty function _getBattery level(), which is asynchronous. In the vacuum we declare an empty battery. If the method fails, we break off the conversation with the report of the attempted capture. In the test part of the rack, we test the original battery test method and perform it as a chain at battery level, after which we detect any faults. After the test statement, we simply set the _battery level status to the battery level value.
Column(
mainAxisAlignment : MainAxisAlignment.spacePotentially,
Children :
High button(
The baby: Text (Get Battery Level),
onPress: (_getBatteryLevel,
),
Text(_batteryLevel),
],
),
Example of a complete code in Flutter
Below you will find a complete code example in the Flutter section. We need to work in the MainActivity file in the android folder before we can launch the application.
import ‘dart:async’ ; import
‘pakket:flutter/materiaal.dart’ ; import
‘pakket:flutter/services.dart’ ; import
‘pakket:flutter/cupertino.dart’ ;
void main() {
runApp(MyApp());
}
The MyApp class extends the StatelessWidget {
@override
Widget build(BuildContext context) {
gives MaterialApp(
home : MyHomePage(),
);
}
}.
The MyHomePage class extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}.
The _MyHomePageState class extends the state {
static const platform = const MethodChannel (‘samples.flutter.dev/battery’) ;
String _batteryLevel =
‘Battery level’ ;
Future _getBatteryLevel() async {
String batteryLevel ;
try {
final int result = wait platform.invokeMethod(‘getBatteryLevel’)) ;
batteryLevel = ‘Battery level in $result % . } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;} } on PlatformException catch (e) {batteryLevel = Failed to get battery level : ‘${e.message}’ ;}.
setState(() {
_battery level = battery level;
});
})
@override
Widget build(BuildContext context) {
return material(
child) : Centre (
Child : Column(
mainAxisAlignment : MainAxisAlignment.spacePotentially,
Children :
High button(
The baby: Text (‘Get Battery Level’), onPress: _getBatteryLevel,),Text(_batteryLevel,],), }}.
Android Kotlin. create channelflutterMethodChannel
In the MainActivity file, overwrite the application:didFinishLaunchingWithOptions function and create a FlutterMethodChannel linking to the samples.flutter.dev/battery channel name. To find the MainActivity file, open the android folder of your Flutter project, open the app folder, then the root folder, and in the kotlin folder we will find the MainActivity file. You can find the position in the screenshot below:
Main activity class : FlutterActivity() {
private trap CHANNEL = samples.flutter.dev/battery
Override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// Note: This method is called on the main wire.
call, result ->
if (call.method == getBatteryLevel) {
fall batteryLevel = getBatteryLevel()
if (battery level != -1) {
result.success(battery level)
} otherwise {
result.error(UNAVAILABLE, battery level not available., null)
}
} otherwise {
result.notImplemented()
}
}
}
}
Kotlin Android. ReceiveBatteryLevel() function
We are now ready to create a Kotlin receiveBatteryLevel() function that reads out and returns the value of the oil level on the device. The native Android battery API is used for this. Add the following function at the bottom of the MainActivity class.
getting private pleasureBattery level() : In {
fall batteryLevel : In
as (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
fall batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
Reversing the charge status of the
battery }
Here is the complete MainActivity file for reference:
Package com.flutter_app_tutorials
import android.content.Context
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 androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.
import io.flutter.plugin.common.MethodChannel.
Main activity class : FlutterActivity() {
private trap CHANNEL = samples.flutter.dev/battery
Override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// Note: This method is called on the main wire.
call, result ->
if (call.method == getBatteryLevel) {
fall batteryLevel = getBatteryLevel()
if (battery level != -1) {
result.success(battery level)
} otherwise {
result.error(UNAVAILABLE, battery level not available., null)
}
} otherwise {
result.notImplemented()
}
}
}
getting private pleasureBattery level() : In {
fall batteryLevel : In
as (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
fall batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
Reversing the charge status of the
battery }
}
Then you can see the result in your application, after starting it it should look like this:
After pressing the Get Battery Level button, this should be your exit:
Pay attention: If you use an emulator, you are likely to get battery information.
I hope you found this lesson about Flutter useful. If you want to know more about Flutter, see the other Flutter tutorials on this page. Some of them contain video tutorials.
Related Tags:
pass message from native to flutter,flutter with java backend,flutter platformview,flutter eventchannel,configureflutterengine,flutter channel master,getflutterview not found,dart:jni,call dart from java,flutter event channel,convert java code to dart,flutter change from kotlin to java,java version for flutter,flutter native callback,how to convert java code to flutter,android pass data to flutter,event channels flutter,flutter methodchannel arguments,convert xcode to flutter,java to dart converter,strings xml in flutter,sp in flutter,how to build flutter module,convert existing android project to flutter,flutter native code,flutter method channel arguments,call flutter method from android,flutter native communication,flutter background service,flutter platform specific ui