Reputation: 1446
I'm trying to send a notification from dart code, when incoming call is being received. I couldn't manage to make a bridge between android native code and flutter code. The thing is that I need this feature to work in the background. I would describe the cycle like this:
I managed to do part 3 and 4 but I need help with part 1 and 2.
I tried to figure out this given example, but it was to complicated
I found this method to detect the incoming call, but I couldn't attach it to mainActivity class and how do part 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);
}
}
The question is how to properly detect a call and how to call a dart class from android native code?
Upvotes: 2
Views: 1949
Reputation: 2457
You can create MethodChannel between native and dart. Here's sample code :
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);
In your dart file write this code,
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) {}
}
You can refer to this document as well
Upvotes: 1