0

所以我遵循了“https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab”中的所有内容,但是当我单击设备中的浮动按钮时,会显示此错误.

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery)

E/flutter ( 4580): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
E/flutter ( 4580): <asynchronous suspension>
E/flutter ( 4580): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 4580): #2      _batteryState._getBatteryLevel (package:flutter_app/main.dart:45:37)
E/flutter ( 4580): #3      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 4580): #4      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 4580): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 4580): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 4580): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 4580): #8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter ( 4580): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter ( 4580): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter ( 4580): #11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter ( 4580): #12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4580): #13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter ( 4580): #14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter ( 4580): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter ( 4580): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 4580): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 4580): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 4580): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 4580): #20     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4580): #21     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4580): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4580): #23     _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4580): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4580): 

主要飞镖: -

import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main(){
  runApp(
      MaterialApp(
        home: battery()



    )
  );
}

class battery extends StatefulWidget {

  @override
  _batteryState createState() => _batteryState();
}

class _batteryState extends State<battery> {
  static const platform = const MethodChannel('battery');
  String _batteryLevel = 'error';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BatteryDetails'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            FloatingActionButton.extended(onPressed: _getBatteryLevel, label: Text('Get battery info')),
            Text(_batteryLevel),
          ],
        )        
      )
    );
  }
  Future<void> _getBatteryLevel() async{
  String BatteryLevel;
  try {
  final int result = await platform.invokeMethod('getBatteryLevel');
  BatteryLevel = 'battery Level is $result %.';
  }on PlatformException catch (e){
  BatteryLevel = "failed to get battery level: '&{e.message}'";
  }
  setState(() {
    _batteryLevel = BatteryLevel;
  });
  }
}

MainActivity.java:-

package com.example.flutter_app;
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.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;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "battery";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            // Note: this method is invoked on the main thread.
                            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();
                            }
                        }
                );
    }
    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;
    }
}

我是新来的,你能帮我吗也有人能解释一下我发生了什么

public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) 

这部分代码。谢谢你。

4

0 回答 0