本节我们接着上一节”获取电池电量”插件的示例,来完成Android端API的实现

使用Java添加Android平台特定的实现

首先在Android Studio中打开您的Flutter应用的Android部分:

  1. 启动 Android Studio
  2. 选择 File > Open…
  3. 定位到您 Flutter app目录, 然后选择里面的 android文件夹,点击 OK
  4. 在java目录下打开MainActivity.java
  5. 在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 } }); } }

  1. 6. 将下面的新方法添加到activity类中的,位于onCreate 方法下方:
  2. ```java
  3. private int getBatteryLevel() {
  4. int batteryLevel = -1;
  5. if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
  6. BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
  7. batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
  8. } else {
  9. Intent intent = new ContextWrapper(getApplicationContext()).
  10. registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  11. batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
  12. intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
  13. }
  14. return batteryLevel;
  15. }
  1. 我们完成之前添加的onMethodCall方法。我们需要处理平台方法名为getBatteryLevel的调用消息,所以我们需要先在call参数判断调用的方法是否为getBatteryLevel。 这个平台方法的实现只需调用我们在前一步中编写的Android代码,并通过result参数返回成功或错误情况的响应信息。如果调用了未定义的API,我们也会通知返回:
    1. @Override
    2. public void onMethodCall(MethodCall call, Result result) {
    3. if (call.method.equals("getBatteryLevel")) {
    4. int batteryLevel = getBatteryLevel();
    5. if (batteryLevel != -1) {
    6. result.success(batteryLevel);
    7. } else {
    8. result.error("UNAVAILABLE", "Battery level not available.", null);
    9. }
    10. } else {
    11. result.notImplemented();
    12. }
    13. }
    现在就可以在Android上运行该应用程序了,如果使用的是Android模拟器,则可以通过工具栏中的”…”按钮访问Extended Controls面板中的电池电量。

    完整代码

    ```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; } }

  1. <a name="b5BBw"></a>
  2. ###
  3. <a name="hyiSU"></a>
  4. ### 使用Kotlin添加Android平台特定的实现
  5. 使用Kotlin和使用Java的步骤类似,首先在Android Studio中打开您的Flutter应用的Android部分:
  6. 1. 启动 Android Studio。
  7. 1. 选择 the menu item "File > Open…"。
  8. 1. 定位到 Flutter app目录, 然后选择里面的 android文件夹,点击 OK。
  9. 1. 在kotlin目录中打开MainActivity.kt。
  10. 接下来,在onCreate里创建MethodChannel并设置一个MethodCallHandler。确保使用与在Flutter客户端使用的通道名称相同。
  11. ```kotlin
  12. import android.os.Bundle
  13. import io.flutter.app.FlutterActivity
  14. import io.flutter.plugin.common.MethodChannel
  15. import io.flutter.plugins.GeneratedPluginRegistrant
  16. class MainActivity() : FlutterActivity() {
  17. private val CHANNEL = "samples.flutter.io/battery"
  18. override fun onCreate(savedInstanceState: Bundle?) {
  19. super.onCreate(savedInstanceState)
  20. GeneratedPluginRegistrant.registerWith(this)
  21. MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
  22. // TODO
  23. }
  24. }
  25. }

接下来,我们添加Kotlin代码,使用Android电池API来获取电池电量,这和原生开发是一样的。
首先,添加需要导入的依赖。

  1. import android.content.Context
  2. import android.content.ContextWrapper
  3. import android.content.Intent
  4. import android.content.IntentFilter
  5. import android.os.BatteryManager
  6. import android.os.Build.VERSION
  7. import android.os.Build.VERSION_CODES

然后,将下面的新方法添加到activity类中的,位于onCreate 方法下方:

  1. private fun getBatteryLevel(): Int {
  2. val batteryLevel: Int
  3. if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
  4. val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
  5. batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  6. } else {
  7. val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
  8. batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
  9. }
  10. return batteryLevel
  11. }

最后,我们完成之前添加的onMethodCall方法。我们需要处理平台方法名为getBatteryLevel的调用消息,所以我们需要先在call参数判断调用的方法是否为getBatteryLevel。 这个平台方法的实现只需调用我们在前一步中编写的Android代码,并通过result参数返回成功或错误情况的响应信息。如果调用了未定义的API,我们也会通知返回:

  1. MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
  2. if (call.method == "getBatteryLevel") {
  3. val batteryLevel = getBatteryLevel()
  4. if (batteryLevel != -1) {
  5. result.success(batteryLevel)
  6. } else {
  7. result.error("UNAVAILABLE", "Battery level not available.", null)
  8. }
  9. } else {
  10. result.notImplemented()
  11. }
  12. }

您现在就可以在Android上运行该应用程序。如果您使用的是Android模拟器,则可以通过工具栏中的”…”按钮访问Extended Controls面板中的电池电量。

完整代码

  1. package com.example.batterylevel
  2. import androidx.annotation.NonNull;
  3. import io.flutter.embedding.android.FlutterActivity
  4. import io.flutter.embedding.engine.FlutterEngine
  5. import io.flutter.plugins.GeneratedPluginRegistrant
  6. import android.os.Bundle
  7. import io.flutter.app.FlutterActivity
  8. import io.flutter.plugin.common.MethodChannel
  9. import android.content.Context
  10. import android.content.ContextWrapper
  11. import android.content.Intent
  12. import android.content.IntentFilter
  13. import android.os.BatteryManager
  14. import android.os.Build.VERSION
  15. import android.os.Build.VERSION_CODES
  16. class MainActivity: FlutterActivity() {
  17. override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
  18. GeneratedPluginRegistrant.registerWith(flutterEngine);
  19. }
  20. private val CHANNEL = "samples.flutter.io/battery"
  21. override fun onCreate(savedInstanceState: Bundle?) {
  22. super.onCreate(savedInstanceState)
  23. GeneratedPluginRegistrant.registerWith(this)
  24. MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
  25. if (call.method == "getBatteryLevel") {
  26. val batteryLevel = getBatteryLevel()
  27. if (batteryLevel != -1) {
  28. result.success(batteryLevel)
  29. } else {
  30. result.error("UNAVAILABLE", "Battery level not available.", null)
  31. }
  32. } else {
  33. result.notImplemented()
  34. }
  35. }
  36. }
  37. private fun getBatteryLevel(): Int {
  38. val batteryLevel: Int
  39. if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
  40. val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
  41. batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  42. } else {
  43. val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
  44. batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
  45. }
  46. return batteryLevel
  47. }
  48. }