2019年9月22日 星期日

Flutter plugin 讀取電池電量範例

參考文章: https://flutter.dev/docs/development/platform-integration/platform-channels
1.在 vscode 開啟終端機執行以下命令, 用 kotlin 寫 android plugin 程式碼:
     flutter create -i swift -a kotlin batterylevel
2.在 vscode 開啟專案檔案夾 batterylevel, 將以下程式碼貼到 main.dart(位在lib/main.dart)
// main.dart
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override build(BuildContext context) => MaterialApp(

     theme: ThemeData.dark(), 
     home: MyHomePage()
  );
}
class MyHomePage extends StatefulWidget {
  @override createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>  {
  String _battery = '';
  final _plugin = MethodChannel('com.example.batterylevel/battery');
  void _batteryUpdate(_) =>  setState(() => _battery = '$_');
  void showLevel() => _plugin.invokeMethod('getBatteryLevel').then(_batteryUpdate);
  @override void initState() {
   super.initState();

   Timer.periodic(Duration(seconds: 5), (timer) =>
     _plugin.invokeMethod('getBatteryLevel').then(_batteryUpdate)
   );
  }
  @override build(BuildContext context) => Scaffold(
      appBar: AppBar(title: Text('電池電量: $_battery %')),
      body  : Text('電池按一下,更新電量顯示'),    
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.battery_unknown),
        onPressed: showLevel
      )
  );
}

3. 編輯位在專案夾內檔案 batterylevel/android/app/src/main/kotlin/com/example/batterylevel/MainActivity.kt, 將以下程式碼複製並貼上:
// MainActivity.kt:
package com.example.batterylevel
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
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 = "com.example.batterylevel/battery"
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)
    MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
      when(call.method) {
        "getBatteryLevel" -> {
          val batteryLevel = if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager

batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
          } else {
            val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
            intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
          }
          if (batteryLevel == -1) result.error("UNAVAILABLE", "電量無效.", null)
          else                    result.success(batteryLevel)        
        }
        else -> result.notImplemented()
      }
    }
  }
}

4. 編譯並上傳至手機:
   flutter run
 

沒有留言:

張貼留言

使用 pcie 轉接器連接 nvme SSD

之前 AM4 主機板使用 pcie ssd, 但主機板故障了沒辦法上網, 只好翻出以前買的 FM2 舊主機板, 想辦法讓老主機復活, 但舊主機板沒有 nvme 的界面, 因此上網買了 pcie 轉接器用來連接 nvme ssd, 遺憾的是 grub2 bootloader 無法識...