gpt4 book ai didi

android - 如何在后台检测调用并在原生代码和 dart 代码之间架起一座桥梁

转载 作者:行者123 更新时间:2023-12-03 03:31:06 24 4
gpt4 key购买 nike

当收到来电时,我正在尝试从 Dart 代码发送通知。我无法在 android native 代码和 flutter 代码之间架起一座桥梁。问题是我需要这个功能在后台工作。我会这样描述这个循环:

  • Flutter android 原生代码必须在后台检测调用
  • native 代码必须从 Flutter dart 代码中调用某个类
  • 此类在数据库中查找有关调用者
  • 的某些信息
  • 找到它后,它必须弹出一个包含某些详细信息的通知。

  • 我设法完成了第 3 部分和第 4 部分,但我需要第 1 部分和第 2 部分的帮助。
    我试图弄清楚 this给出的例子,但它是复杂的
    我找到了这个方法来检测来电,但我无法将它附加到 mainActivity 类以及如何第 2 部分
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.PhoneStateListener;
    import android.widget.Toast;
    import android.telephony.TelephonyManager;

    public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
    telephony.listen(new PhoneStateListener(){
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {

    // I think this is the part, where I should call my dart class.

    }
    },PhoneStateListener.LISTEN_CALL_STATE);
    }
    }
    问题是如何正确检测调用以及如何从 android native 代码调用 dart 类?

    最佳答案

    您可以在 native 和 dart 之间创建 MethodChannel。这是示例代码:

        String channel = "my.data";
    MethodChannel methodChannel = new MethodChannel(Objects.requireNonNull(getFlutterEngine()).getDartExecutor().getBinaryMessenger(), channel);
    final HashMap<String, String> map = new HashMap<>();
    map.put("yourvar", "myvar");

    methodChannel.setMethodCallHandler(
    new MethodChannel.MethodCallHandler() {
    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
    if (call.method.equals("onFinish")) {
    finish();
    }
    }
    });
    methodChannel.invokeMethod("callMyFunction", map);
    在你的 dart 文件中写下这段代码,
    static const platform = const MethodChannel('my.data"');

    _MyPageState() {
    platform.setMethodCallHandler(_receiveFromNative);
    }

    Future<void> _receiveFromNative(MethodCall call) async {
    try {
    print(call.method);
    if (call.method == "callMyFunction") {
    print(call.arguments['yourvar']);
    //write your code here
    }
    } on PlatformException catch (e) {}
    }
    您可以引用 this document以及

    关于android - 如何在后台检测调用并在原生代码和 dart 代码之间架起一座桥梁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63825284/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com