본문 바로가기
프로그래밍/Flutter-Dart

[Flutter] native code 호출하기

by 채연2 2021. 3. 26.

 

 

 

 

 

flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab

 

Writing custom platform-specific code

Learn how to write custom platform-specific code in your app.

flutter.dev

 

 

native code를 어떻게 호출하는지와, java와 kotiln을 혼용해도 잘 동작하는지 테스트!

 

 

android/app/src/main/kotlin/your_package_name/MainActivity.kt

package net.koolsign.flutter_app0324

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
import android.util.Log

import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "samples.flutter.dev/battery"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // Note: this method is invoked on the main thread.
            call, result ->
            if (call.method == "getBatteryLevel") {
                val batteryLevel = getBatteryLevel()

                if (batteryLevel != -1) {
                    result.success(batteryLevel)
                } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null)
                }
            } else if(call.method == "getTestCode") {
                val tjc = TestJavaClass()
                result.success(tjc.testResult);
            } else {
                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
    }
}

 

 

320x100

 

android/app/src/main/java/your_package_name/TestJavaClass.java

package net.koolsign.flutter_app0324;

public class TestJavaClass {
    TestJavaClass() {}

    public String getTestResult() {
        return "Test Result!!!";
    }
}

 

 

 

ios/Runner/AppDelegate.swift

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",
                                              binaryMessenger: controller.binaryMessenger)
    batteryChannel.setMethodCallHandler({
      [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
      // Note: this method is invoked on the UI thread.
      guard call.method == "getBatteryLevel" else {
        result(FlutterMethodNotImplemented)
        return
      }
      self?.receiveBatteryLevel(result: result)
    })

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  private func receiveBatteryLevel(result: FlutterResult) {
    let device = UIDevice.current
    device.isBatteryMonitoringEnabled = true
    if device.batteryState == UIDevice.BatteryState.unknown {
      result(FlutterError(code: "UNAVAILABLE",
                          message: "Battery info unavailable",
                          details: nil))
    } else {
      result(Int(device.batteryLevel * 100))
    }
  }
}

 

 

 

main.dart

// @dart=2.9
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

void main() {
  runApp(GetMaterialApp(home: _MyHomePage()));
}

class _MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _MyHomePageState();
  }
}

class _MyHomePageState  extends State<_MyHomePage> {
  static const platform = const MethodChannel('samples.flutter.dev/battery');
  String _batteryLevel = 'Unknown battery level.';
  String _test = 'Unknown test result.';

  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;
    });
  }

  Future<void> _getTest() async {
    String str;
    try {
      final String result = await platform.invokeMethod('getTestCode');
      str = 'Get $result';
    } on PlatformException catch (e) {
      str = "Failed to get test result: '${e.message}'.";
    }

    setState(() {
      _test = str;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ElevatedButton(
              child: Text('Get Battery Level'),
              onPressed: _getBatteryLevel,
            ),
            ElevatedButton(
              child: Text('Get Test Code'),
              onPressed: _getTest,
            ),
            Text(_batteryLevel),
            Text(_test),
          ],
        ),
      ),
    );
  }
}

한 채널에 여러 메소드를 등록해도 잘 동작한다.!

 

 

 

 

 

320x100

'프로그래밍 > Flutter-Dart' 카테고리의 다른 글

[Flutter] Row, Column  (0) 2022.02.16
[Flutter] Login App (3)  (0) 2021.03.29
[Flutter] Card  (0) 2021.03.25
[Flutter] Unsound null safety 관련  (0) 2021.03.25
[Flutter] Dice App  (0) 2021.03.25

댓글