问题描述
当接收到来电时,我正在尝试从飞镖代码发送通知。我无法在android本机代码和flutter代码之间架起一座桥梁。问题是我需要此功能才能在后台工作。我将这样描述周期:
- Flutter android本机代码必须在后台检测呼叫
- 本机代码必须从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本机代码调用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