0

I'm trying to write platform specific code in Flutter. First of all, created a method to obtain battery temperature inside MainActivity.kt

This is my full code in MainActivity.kt file:

package com.xyz.zyx

  import android.os.BatteryManager;

  import androidx.annotation.NonNull
  import io.flutter.embedding.android.FlutterActivity
  import io.flutter.embedding.engine.FlutterEngine
  import android.content.Context
  import android.content.Intent
  import android.content.IntentFilter
  import io.flutter.embedding.android.FlutterFragmentActivity
  import io.flutter.plugin.common.BinaryMessenger
  import io.flutter.plugin.common.EventChannel
  import io.flutter.plugin.common.MethodCall
  import io.flutter.plugin.common.MethodChannel
  import io.flutter.plugin.common.MethodChannel.MethodCallHandler
  import io.flutter.plugin.common.MethodChannel.Result
  import io.flutter.plugin.common.PluginRegistry.Registrar

  class MainActivity: FlutterFragmentActivity() {
      // ...
            private var batteryManager: BatteryManager? = null
            private var methodChannel: MethodChannel? = null
            private var temperatureChannel: EventChannel? = null

       override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "battery").setMethodCallHandler {
      call, result ->
      if (call.method == "getBatteryTemperature") {
        val batteryTemperature = getBatteryTemperature()

        if (batteryTemperature != -1) {
          result.success(batteryTemperature)
        } else {
          result.error("UNAVAILABLE", "Battery temperature not available.", null)
        }
      } else {
        result.notImplemented()
      }
    }
  }
          private fun getBatteryTemperature(): Int {
              val batteryStatus: Intent? =
                  IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
                      this.registerReceiver(null, ifilter)
                      val batteryTemperature: Int
                      val batteryManager =
                          getSystemService(Context.BATTERY_SERVICE) as BatteryManager
                      batteryTemperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -99)
                      return batteryTemperature
                  }
          }
  }

This is how I call my platform specific code from Flutter side:

  static const platform = MethodChannel('battery');


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


Lastly, this is the error on Flutter app running on an Android device. It throws an MissingPluginException even though there is a method called getBatteryTemperature, it says there isn't.

E/flutter (25427): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryTemperature on channel battery)
E/flutter (25427): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:294:7)

Is there something did I miss to implement in my code? Why does it not work?

Zahid Tekbaş
  • 809
  • 2
  • 12
  • 27
  • see this https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-kotlin-tab – Dev Oct 26 '22 at 05:43
  • You'll fid it a lot easier to write platform specific code in a plugin project. By creating a Flutter plugin project you get a template that you can (a) confirm runs without changes and (b) allows you to make changes to the boilerplate to add your functionality. – Richard Heap Oct 27 '22 at 17:06

0 Answers0