私はここで例を試しています https://flutter.dev/docs/development/platform-integration/platform-channels#step-1-create-a-new-app-project
しかし、まったく同じコードを入力しても機能しません。 (私はKotlinを使用しています)
やってみると
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL)
エラーは言った
タイプの不一致:推定されたタイプはMainActivityですが、FlutterEngineが予期されていました
未解決の参照:flutterView
だから私は以下を試しました
GeneratedPluginRegistrant.registerWith(FlutterEngine(this))
MethodChannel(FlutterView(this), CHANNEL)
エラーは消えますが、他の問題が現れます
[ERROR:flutter/lib/ui/ui_ui_Dart_state.cc(157)]未処理の例外:MissingPluginException(チャネルsamples.flutter.ioのメソッドgetBatteryLevelの実装が見つかりません/バッテリー)
getBatteryLevel()メソッドは存在しますが
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
}
動作しないgetFlutterView()も試しました。
これが私が知りたいポイントです。
ここに完全なコードとエラーがあります
main.Dart
import 'package:flutter/material.Dart';
import 'package:flutter/services.Dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const platform = const MethodChannel('samples.flutter.io/battery');
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;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('Get Battery Level'),
onPressed: _getBatteryLevel,
),
Text(
_batteryLevel,
),
],
),
),
);
}
}
MainActivity.kt
package com.example.native_test
import Android.content.Context
import Android.content.ContextWrapper
import Android.content.Intent
import Android.content.IntentFilter
import Android.os.BatteryManager
import Android.os.Bundle
import io.flutter.Log
import io.flutter.embedding.Android.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterView
import Android.os.Build.VERSION
import Android.os.Build.VERSION_CODES
class MainActivity: FlutterActivity() {
//private val CHANNEL = "plugins.flutter.io/battery"
private val CHANNEL = "samples.flutter.io/battery"
//private val CHANNEL = "com.example.batterylevel/battery"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i("user_debug", "MainActivity: onCreate")
GeneratedPluginRegistrant.registerWith(FlutterEngine(this))
MethodChannel(FlutterView(this), CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel : Int = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
Log.e("user_debug", "getBatteryLevel is not method of called")
result.notImplemented()
}
}
}
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
}
}
Launching lib/main.Dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
E/flutter (23141): [ERROR:flutter/Shell/common/Shell.cc(197)] Dart Error: Unhandled exception:
E/flutter (23141): NoSuchMethodError: No top-level getter '' declared.
E/flutter (23141): Receiver: top-level
E/flutter (23141): Tried calling:
E/flutter (23141): #0 NoSuchMethodError._throwNew (Dart:core-patch/errors_patch.Dart:202:5)
E/flutter (23141): [ERROR:flutter/runtime/Dart_isolate.cc(461)] Could not resolve main entrypoint function.
E/flutter (23141): [ERROR:flutter/Shell/common/engine.cc(205)] Could not run the isolate.
E/flutter (23141): [ERROR:flutter/Shell/common/engine.cc(137)] Engine not prepare and launch isolate.
E/flutter (23141): [ERROR:flutter/Shell/common/Shell.cc(197)] Dart Error: Unhandled exception:
E/flutter (23141): NoSuchMethodError: No top-level getter '' declared.
E/flutter (23141): Receiver: top-level
E/flutter (23141): Tried calling:
E/flutter (23141): #0 NoSuchMethodError._throwNew (Dart:core-patch/errors_patch.Dart:202:5)
E/flutter (23141): [ERROR:flutter/runtime/Dart_isolate.cc(461)] Could not resolve main entrypoint function.
E/flutter (23141): [ERROR:flutter/Shell/common/engine.cc(205)] Could not run the isolate.
E/flutter (23141): [ERROR:flutter/Shell/common/engine.cc(137)] Engine not prepare and launch isolate.
...
E/flutter (23861): [ERROR:flutter/lib/ui/ui_Dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)
E/flutter (23861): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.Dart:319:7)
E/flutter (23861): <asynchronous suspension>
E/flutter (23861): #1 _MyHomePageState._getBatteryLevel (package:native_test/main.Dart:55:41)
E/flutter (23861): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.Dart:706:14)
E/flutter (23861): #3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.Dart:789:36)
E/flutter (23861): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.Dart:182:24)
E/flutter (23861): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.Dart:486:11)
E/flutter (23861): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.Dart:264:5)
E/flutter (23861): #7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.Dart:199:7)
E/flutter (23861): #8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.Dart:467:9)
E/flutter (23861): #9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.Dart:76:12)
E/flutter (23861): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.Dart:117:9)
E/flutter (23861): #11 _LinkedHashMapMixin.forEach (Dart:collection-patch/compact_hash.Dart:379:8)
E/flutter (23861): #12 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.Dart:115:18)
E/flutter (23861): #13 PointerRouter.route (package:flutter/src/gestures/pointer_router.Dart:101:7)
E/flutter (23861): #14 GestureBinding.handleEvent (package:flutter/src/gestures/binding.Dart:218:19)
E/flutter (23861): #15 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.Dart:198:22)
E/flutter (23861): #16 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.Dart:156:7)
E/flutter (23861): #17 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.Dart:102:7)
E/flutter (23861): #18 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.Dart:86:7)
E/flutter (23861): #19 _rootRunUnary (Dart:async/zone.Dart:1138:13)
E/flutter (23861): #20 _CustomZone.runUnary (Dart:async/zone.Dart:1031:19)
E/flutter (23861): #21 _CustomZone.runUnaryGuarded (Dart:async/zone.Dart:933:7)
E/flutter (23861): #22 _invoke1 (Dart:ui/hooks.Dart:273:10)
E/flutter (23861): #23 _dispatchPointerDataPacket (Dart:ui/hooks.Dart:182:5)
E/flutter (23861):
E/flutter (23861): [ERROR:flutter/lib/ui/ui_Dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)
...
E/flutter ( 770): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.Dart:319:7)
E/flutter ( 770): <asynchronous suspension>
E/flutter ( 770): #1 _MyHomePageState._getBatteryLevel (package:native_test/main.Dart:56:41)
E/flutter ( 770): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.Dart:706:14)
E/flutter ( 770): #3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.Dart:789:36)
E/flutter ( 770): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.Dart:182:24)
E/flutter ( 770): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.Dart:486:11)
E/flutter ( 770): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.Dart:264:5)
E/flutter ( 770): #7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.Dart:199:7)
E/flutter ( 770): #8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.Dart:467:9)
E/flutter ( 770): #9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.Dart:76:12)
E/flutter ( 770): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.Dart:117:9)
E/flutter ( 770): #11 _LinkedHashMapMixin.forEach (Dart:collection-patch/compact_hash.Dart:379:8)
E/flutter ( 770): #12 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.Dart:115:18)
E/flutter ( 770): #13 PointerRouter.route (package:flutter/src/gestures/pointer_router.Dart:101:7)
E/flutter ( 770): #14 GestureBinding.handleEvent (package:flutter/src/gestures/binding.Dart:218:19)
E/flutter ( 770): #15 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.Dart:198:22)
E/flutter ( 770): #16 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.Dart:156:7)
E/flutter ( 770): #17 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.Dart:102:7)
E/flutter ( 770): #18 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.Dart:86:7)
E/flutter ( 770): #19 _rootRunUnary (Dart:async/zone.Dart:1138:13)
E/flutter ( 770): #20 _CustomZone.runUnary (Dart:async/zone.Dart:1031:19)
E/flutter ( 770): #21 _CustomZone.runUnaryGuarded (Dart:async/zone.Dart:933:7)
E/flutter ( 770): #22 _invoke1 (Dart:ui/hooks.Dart:273:10)
E/flutter ( 770): #23 _dispatchPointerDataPacket (Dart:ui/hooks.Dart:182:5)
E/flutter ( 770):
✓ Built build/app/outputs/apk/debug/app-debug.apk.
Installing build/app/outputs/apk/app.apk...
Syncing files to device Android SDK built for x86...
正直なところ、このエラーのために私はとても怒っていました...
私のやり方が正しいかどうかはわかりませんが、...機能させるには、次のように変更する必要があります。
_GeneratedPluginRegistrant.registerWith(new FlutterEngine(this));
_
また、await platform.invokeListMethod('getBatteryLevel');
はFuture <List <dynamic >>を待機します
したがって、リストを返すようにJavaコードを変更する必要がありました。
インポートを追加
_import Java.util.List;
_
コードの行を次のように変更しました:
_List<Integer> batteryLevel = getBatteryLevel();
_
そのメソッド呼び出しで、コードを次のように変更しました。
_ private List<Integer> getBatteryLevel() {
List<Integer> result = new ArrayList<>();
int batteryLevel = -1;
...
result.add(batteryLevel);
return result;
}
_
Dart側でもコードを変更します。Javaは整数のリストを返すためです。
_try {
final batteryLevel = await platform.invokeListMethod('getBatteryLevel');
setState(() {
_batteryLevel = batteryLevel[0];
});
_