Flutter MethodChannel 使用範例

官網有一個讀取電池現在使用量的範例
但是沒有具體的說明路徑讓我看得霧煞煞好幾天….在此補充說明幫助其他需要的人

原始範例

step1: 建立電池量應用

打開 Terminal
輸入 flutter create batterylevel

step2: MainActivity設定

在 configureFlutterEngine() 方法中創建一個 MethodChannel 並調用 setMethodCallHandler()
路徑 android/app/src/main/kotlin/com/example/app_name
將MainActivity.kt變更為

package com.example.app_name

import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

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

class MainActivity: FlutterActivity() {
    private val CHANNEL = "samples.flutter.dev/battery"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
         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
        }
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // Note: this method is invoked on the main thread.
            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()
            }
        }
    }
}

step3: 畫面顯示

回到頁面MyHomePageState先加入依賴的資料

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class _MyHomePageState extends State<MyHomePage> {
  static const platform = MethodChannel('samples.flutter.dev/battery');
  // Get battery level.

String _batteryLevel = 'Unknown battery level.';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

然後在畫面中添加可以觸發的按鈕就完成了

Column(
 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
 children: [
  ElevatedButton(
  child: const Text('Get Battery Level'),
   onPressed: _getBatteryLevel,
  ),
  Text(_batteryLevel),
 ],
),

以上就完成點按鈕獲得電量的通道設定了

關於站主

Shiro

因為興趣無限擴張,一直很猶豫要不要寫一個很雜的Blog,後來還是這麼做了。

聯絡:shiro050102✦gmail.com  ✦請自行更換成@