本节我们接着上一节”获取电池电量”插件的示例,来完成Android端API的实现
使用Java添加Android平台特定的实现
首先在Android Studio中打开您的Flutter应用的Android部分:
- 启动 Android Studio
- 选择 File > Open…
- 定位到您 Flutter app目录, 然后选择里面的 android文件夹,点击 OK
- 在java目录下打开MainActivity.java
- 在onCreate里创建MethodChannel并设置一个MethodCallHandler。确保使用和Flutter客户端中使用的通道名称相同的名称。 ```java //添加Java代码,使用Android电池API来获取电池电量。此代码和在原生Android应用中编写的代码完全相同。添加需要导入的依赖 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;
import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result;
public class MainActivity extends FlutterActivity { private static final String CHANNEL = “samples.flutter.io/battery”; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodCallHandler() { @Override public void onMethodCall(MethodCall call, Result result) { // TODO } }); } }
6. 将下面的新方法添加到activity类中的,位于onCreate 方法下方:```javaprivate 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;}
- 我们完成之前添加的onMethodCall方法。我们需要处理平台方法名为getBatteryLevel的调用消息,所以我们需要先在call参数判断调用的方法是否为getBatteryLevel。 这个平台方法的实现只需调用我们在前一步中编写的Android代码,并通过result参数返回成功或错误情况的响应信息。如果调用了未定义的API,我们也会通知返回:
现在就可以在Android上运行该应用程序了,如果使用的是Android模拟器,则可以通过工具栏中的”…”按钮访问Extended Controls面板中的电池电量。@Overridepublic void onMethodCall(MethodCall call, Result result) {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();}}
完整代码
```java package com.example.batterylevel;
import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugins.GeneratedPluginRegistrant; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result;
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;
public class MainActivity extends FlutterActivity { private static final String CHANNEL = “samples.flutter.io/battery”;
@Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodCallHandler() { @Override public void onMethodCall(MethodCall call, Result result) { 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(); } } }); }
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; } }
<a name="b5BBw"></a>###<a name="hyiSU"></a>### 使用Kotlin添加Android平台特定的实现使用Kotlin和使用Java的步骤类似,首先在Android Studio中打开您的Flutter应用的Android部分:1. 启动 Android Studio。1. 选择 the menu item "File > Open…"。1. 定位到 Flutter app目录, 然后选择里面的 android文件夹,点击 OK。1. 在kotlin目录中打开MainActivity.kt。接下来,在onCreate里创建MethodChannel并设置一个MethodCallHandler。确保使用与在Flutter客户端使用的通道名称相同。```kotlinimport android.os.Bundleimport io.flutter.app.FlutterActivityimport io.flutter.plugin.common.MethodChannelimport io.flutter.plugins.GeneratedPluginRegistrantclass MainActivity() : FlutterActivity() {private val CHANNEL = "samples.flutter.io/battery"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)GeneratedPluginRegistrant.registerWith(this)MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->// TODO}}}
接下来,我们添加Kotlin代码,使用Android电池API来获取电池电量,这和原生开发是一样的。
首先,添加需要导入的依赖。
import android.content.Contextimport android.content.ContextWrapperimport android.content.Intentimport android.content.IntentFilterimport android.os.BatteryManagerimport android.os.Build.VERSIONimport android.os.Build.VERSION_CODES
然后,将下面的新方法添加到activity类中的,位于onCreate 方法下方:
private fun getBatteryLevel(): Int {val batteryLevel: Intif (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManagerbatteryLevel = 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)}return batteryLevel}
最后,我们完成之前添加的onMethodCall方法。我们需要处理平台方法名为getBatteryLevel的调用消息,所以我们需要先在call参数判断调用的方法是否为getBatteryLevel。 这个平台方法的实现只需调用我们在前一步中编写的Android代码,并通过result参数返回成功或错误情况的响应信息。如果调用了未定义的API,我们也会通知返回:
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->if (call.method == "getBatteryLevel") {val batteryLevel = getBatteryLevel()if (batteryLevel != -1) {result.success(batteryLevel)} else {result.error("UNAVAILABLE", "Battery level not available.", null)}} else {result.notImplemented()}}
您现在就可以在Android上运行该应用程序。如果您使用的是Android模拟器,则可以通过工具栏中的”…”按钮访问Extended Controls面板中的电池电量。
完整代码
package com.example.batterylevelimport androidx.annotation.NonNull;import io.flutter.embedding.android.FlutterActivityimport io.flutter.embedding.engine.FlutterEngineimport io.flutter.plugins.GeneratedPluginRegistrantimport android.os.Bundleimport io.flutter.app.FlutterActivityimport io.flutter.plugin.common.MethodChannelimport android.content.Contextimport android.content.ContextWrapperimport android.content.Intentimport android.content.IntentFilterimport android.os.BatteryManagerimport android.os.Build.VERSIONimport android.os.Build.VERSION_CODESclass MainActivity: FlutterActivity() {override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {GeneratedPluginRegistrant.registerWith(flutterEngine);}private val CHANNEL = "samples.flutter.io/battery"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)GeneratedPluginRegistrant.registerWith(this)MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->if (call.method == "getBatteryLevel") {val batteryLevel = getBatteryLevel()if (batteryLevel != -1) {result.success(batteryLevel)} else {result.error("UNAVAILABLE", "Battery level not available.", null)}} else {result.notImplemented()}}}private fun getBatteryLevel(): Int {val batteryLevel: Intif (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManagerbatteryLevel = 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)}return batteryLevel}}
