Feed Buzzard

Cooking content that keeps your audience buzzing

  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact
No Result
View All Result
  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact
No Result
View All Result
Feed Buzzard
No Result
View All Result
Home World Tech

Calling Android Native Code in Flutter

Gordon James by Gordon James
December 23, 2020
in World Tech
0
0
SHARES
6
VIEWS
Share on FacebookShare on Twitter

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:

  1. Create a new Flutter project,
  2. Create a MethodChannel object,
  3. Set a function that recalls the original Android code,
  4. Prepare the user interface to display the result,
  5. 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:

http://server.digimetriq.com/wp-content/uploads/2020/12/Calling-Android-Native-Code-in-Flutter.png

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:

http://server.digimetriq.com/wp-content/uploads/2020/12/Calling-Android-Native-Code-in-Flutter.jpg

After pressing the Get Battery Level button, this should be your exit:

http://server.digimetriq.com/wp-content/uploads/2020/12/1608723048_707_Calling-Android-Native-Code-in-Flutter.jpg

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

Total
0
Shares
Share 0
Tweet 0
Pin it 0
Share 0
Gordon James

Gordon James

James Gordon is a content manager for the website Feedbuzzard. He loves spending time in nature, and his favorite pastime is watching dogs play. He also enjoys watching sunsets, as the colors are always so soothing to him. James loves learning about new technology, and he is excited to be working on a website that covers this topic.

Related Posts

World Tech

No Phone, No Problem: Receiving SMS Online Made Easy

March 24, 2025
Image2
World Tech

The Smart Shopper’s Guide to Finding Reliable Tech at the Price

February 24, 2025
Image1
World Tech

The Unique Appeal of Clash GG Case Battles

February 19, 2025
Next Post

How to Install Steam DLC on Windows 10 PC

Repair Battlefield 3 Waiting for Game to Exit Error on PC

How to Make Google Chrome Use Less RAM

No Result
View All Result

Recommended

Image3

Why Social Betting is Changing Online Gambling’s Future

6 hours ago
Image1

What $10 Purchase You in The Digital World: A 2025 Micro-Spending Roundup

2 days ago
Image1

Unlocking Wealth: Your Ultimate List of Investment Villas in Spain

3 days ago
Image3

What Are Financial Trading Indicators And How To Tune Them Up To Understand Financial Markets Better?

3 days ago

Categories

  • Businesses
  • Fitness Trackers
  • Gaming
  • General
  • General News
  • Latest
  • Latest Trends
  • Online Gaming
  • Pokemon
  • Tech
  • Technology and Computing
  • Wearable Tech
  • World Tech
  • World Tech Code

Our Address: 222 Haloria Crossing
Vrentis Point, HV 12345

Categories

  • Businesses
  • Fitness Trackers
  • Gaming
  • General
  • General News
  • Latest
  • Latest Trends
  • Online Gaming
  • Pokemon
  • Tech
  • Technology and Computing
  • Wearable Tech
  • World Tech
  • World Tech Code
No Result
View All Result
  • Image2
  • Image1
  • Image2
  • RyanMotorsOmaha
  • Tech News FeedCryptobuzz
  • Ujjukt [Hjv
  • www Feedbuzzard .com
  • Image3
  • Image3
  • Image1
  • Image3
  • Image2
  • Image2
  • Image3
  • Image1
  • Image2
  • Image2
  • pandagendut slot
  • faktor-faktor yang mendorong didirikannya voc adalah
  • sayur yang bisa ngeramal
  • buku mimpi 2d 3d 4d abjad
  • gerakan awal guling lenting yang benar diawali dengan gerak
  • ibanking bank jateng personal
  • canadadry.ca enter pin 2022
  • chord gitar wali kerudung merah
  • Reparasi Tas Terdekat
  • buku mimpi 2d 3d 4d abjad
  • no hp janda yang bisa dihubungi
  • pola138
  • photoacampamente
  • bo togel hadiah 2d 200rb
  • www feedbuzzard .com
  • feedcryptobuzz cryptocurrency updates from feedbuzzard
  • feedbuzzard com
  • Ca Khia
  • 5 letter words starting with ca
  • Mobile. de
  • Mendarat Yang Baik Dalam Lompat Jauh Dilakukan Dengan.....
  • jual ayam potong terdekat
  • how to play crypto games in 2023 feedgamebuzz
  • latest gadjets for gaming zardgadjets
  • latest hacks buzzardcoding
  • what are new technologies in 2023 feedworldtech
  • Image1
  • remaxhd.com
  • tv.hotstar.com
  • rajbet.com
  • venus.happyreturns.com
  • Image2
  • ibooma.com
  • fapwife.com
  • Image1
  • Image1
  • Image3
  • Image2
  • the budget process involves doing all of the following except
  • rice purity test for 14 year olds
  • during operations outside declared hostilities, you may delay contact with local authorities.
  • rick and morty season 6 online
  • active shooter is one or more subjects who participate in a shooting
  • which of the following is most likely to be considered plagiarism
  • which of the following could be a replacement behavior for cutting in line
  • effective scrum master apply which coaching behavior
  • a decrease in blood protein concentration would tend to
  • hair removal cream for private parts male
  • what escape planning factors can facilitate
  • the adversary is collecting information regarding your organization's mission from the trash
  • identify two meanings for the japanese word inu
  • an immediate annuity has been purchased with a single premium
  • justify the following statement: “diversity should exist in the workplace.”
  • fc barcelona vs viktoria plzeň lineups
  • which of the following is tax-deductible to the firm?
  • latest feedbuzzard com
  • treasure of wisdom a new plan
  • which data types are typically found in the human resources department?
  • what supports the arms and hands medical term
  • which of the following is true about nonforfeiture values?
  • match each type of anxiety disorder with its description.
  • what does wtm mean on snapchat
  • daniel is a middle-income medicare beneficiary
  • which facility is shown in the image
  • how can you report potential insider threats to the js in to select all that apply
  • what does wtv mean in text
  • jane assessment answers
  • employee records must meet all of the following criteria except
  • a major challenge of nationalism is .
  • a covered entity (ce) must have an established complaint process. true false
  • fema is 100 hcb answers
  • identify the true and false statements about culture.
  • in which word does the grapheme representing /k/ indicate that the word is probably from greek?
  • mr. wingate is a newly enrolled
  • gear patrol the spirit of adventure
  • ms insurance company denied a reinstatement
  • which option below is a preventive measure against id fraud or theft?
  • preferred stock is advantageous in that it ______. (check all that apply.)
  • which sentence from the novel best reflects the story's gothic nature
  • m and t bank near me

© 2022 FeedBuzzard.com

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
No Result
View All Result
  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact

© 2024 JNews - Premium WordPress news & magazine theme by Jegtheme.