# 插件開發:Android端API實現
本節我們接著上一節"獲取電池電量"插件的示例,來完成Android端API的實現。以下步驟是使用Java的示例,如果您更喜歡Kotlin,可以直接跳到后面Kotlin部分。
首先在Android Studio中打開您的Flutter應用的Android部分:
1. 啟動 Android Studio
2. 選擇 File > Open…
3. 定位到您 Flutter app目錄, 然后選擇里面的 `android`文件夾,點擊 OK
4. 在`java`目錄下打開 `MainActivity.java`
接下來,在`onCreate`里創建MethodChannel并設置一個`MethodCallHandler`。確保使用和Flutter客戶端中使用的通道名稱相同的名稱。
```
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
}
});
}
}
```
接下來,我們添加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;
```
然后,將下面的新方法添加到activity類中的,位于onCreate 方法下方:
```
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;
}
```
最后,我們完成之前添加的`onMethodCall`方法。我們需要處理平臺方法名為`getBatteryLevel`的調用消息,所以我們需要先在call參數判斷調用的方法是否為`getBatteryLevel`。 這個平臺方法的實現只需調用我們在前一步中編寫的Android代碼,并通過result參數返回成功或錯誤情況的響應信息。如果調用了未定義的API,我們也會通知返回:
```
@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();
}
}
```
現在就可以在Android上運行該應用程序了,如果使用的是Android模擬器,則可以通過工具欄中的"..."按鈕訪問Extended Controls面板中的電池電量。
### 使用Kotlin添加Android平臺特定的實現
使用Kotlin和使用Java的步驟類似,首先在Android Studio中打開您的Flutter應用的Android部分:
1. 啟動 Android Studio。
2. 選擇 the menu item "File > Open…"。
3. 定位到 Flutter app目錄, 然后選擇里面的 `android`文件夾,點擊 OK。
4. 在`kotlin`目錄中打開`MainActivity.kt`。
接下來,在`onCreate`里創建MethodChannel并設置一個`MethodCallHandler`。確保使用與在Flutter客戶端使用的通道名稱相同。
```
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
class 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.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
```
然后,將下面的新方法添加到activity類中的,位于onCreate 方法下方:
```
private fun getBatteryLevel(): Int {
val batteryLevel: Int
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val 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)
}
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面板中的電池電量。
- 緣起
- 起步
- 移動開發技術簡介
- Flutter簡介
- 搭建Flutter開發環境
- 常見配置問題
- Dart語言簡介
- 第一個Flutter應用
- 計數器示例
- 路由管理
- 包管理
- 資源管理
- 調試Flutter APP
- Dart線程模型及異常捕獲
- 基礎Widgets
- Widget簡介
- 文本、字體樣式
- 按鈕
- 圖片和Icon
- 單選框和復選框
- 輸入框和表單
- 布局類Widgets
- 布局類Widgets簡介
- 線性布局Row、Column
- 彈性布局Flex
- 流式布局Wrap、Flow
- 層疊布局Stack、Positioned
- 容器類Widgets
- Padding
- 布局限制類容器ConstrainedBox、SizeBox
- 裝飾容器DecoratedBox
- 變換Transform
- Container容器
- Scaffold、TabBar、底部導航
- 可滾動Widgets
- 可滾動Widgets簡介
- SingleChildScrollView
- ListView
- GridView
- CustomScrollView
- 滾動監聽及控制ScrollController
- 功能型Widgets
- 導航返回攔截-WillPopScope
- 數據共享-InheritedWidget
- 主題-Theme
- 事件處理與通知
- 原始指針事件處理
- 手勢識別
- 全局事件總線
- 通知Notification
- 動畫
- Flutter動畫簡介
- 動畫結構
- 自定義路由過渡動畫
- Hero動畫
- 交錯動畫
- 自定義Widget
- 自定義Widget方法簡介
- 通過組合現有Widget實現
- 實例:TurnBox
- CustomPaint與Canvas
- 實例:圓形漸變進度條(自繪)
- 文件操作與網絡請求
- 文件操作
- Http請求-HttpClient
- Http請求-Dio package
- 實例:Http分塊下載
- WebSocket
- 使用Socket API
- Json轉Model
- 包與插件
- 開發package
- 插件開發:平臺通道簡介
- 插件開發:實現Android端API
- 插件開發:實現IOS端API
- 系統能力調用
- 國際化
- 讓App支持多語言
- 實現Localizations
- 使用Intl包
- Flutter核心原理
- Flutter UI系統
- Element和BuildContext
- RenderObject與RenderBox
- Flutter從啟動到顯示