參考文章: 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
沒有留言:
張貼留言