Как отправить данные во Flutter из нативного (Android) - PullRequest
3 голосов
/ 27 мая 2020

Мне нужно передать данные из класса ниже в мое приложение flutter, где данные доступны только при возникновении события входящего вызова. мне нужно передать эти данные (mobileNumber) для flutter (если возможно, мне нужно передать данные, даже если приложение flutter завершено)

BroadcastReciever. java

package com.ashbu.flutterappbackground;
...

public class MyBroadcastReceiver extends BroadcastReceiver {
    String phoneNumber;

        @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) {
                    super.onCallStateChanged(state, incomingNumber);
                    phoneNumber = incomingNumber;
                    Toast.makeText(context, "TeleDuce Customer "+ incomingNumber,
                Toast.LENGTH_LONG).show();
                }
            },PhoneStateListener.LISTEN_CALL_STATE);
        }


   public  String getData() {
    String number = null;
    if (phoneNumber != null) {
        number = phoneNumber;
    }else {
        number = "noData";
    }
    return number;
    }

} из приведенного выше кода, мне нужно передать incomingNumber для flutter. если возможно - поделитесь данными, даже если приложение закрыто.

MainActivity. java

public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/getNumber";

AlarmManager alarmManager;
PendingIntent pendingIntent;

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    super.configureFlutterEngine(flutterEngine);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, MyService.class);
    pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
            .setMethodCallHandler(
                    (call, result) -> {

                        // Note: this method is invoked on the main thread.
                        if (call.method.equals("getMobileNumber")) {
                            startAlarm();
                            MyBroadcastReceiver dataGEt = new MyBroadcastReceiver();
                            System.out.println(dataGEt.getData());
                            result.success(dataGEt.getData());
                        } else {
                            cancelAlarm();
                        }
                    }
            );
}

private void startAlarm() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
    }
}

private void cancelAlarm() {
    alarmManager.cancel(pendingIntent);
    Toast.makeText(getApplicationContext(), "Alarm Cancelled", Toast.LENGTH_LONG).show();
}
}

В настоящее время указанный выше код будет работать, даже если приложение закрыто. Но я не знаю, примет ли флаттер данные после завершения работы приложения

1 Ответ

0 голосов
/ 27 мая 2020

Вы должны реализовать methodHandler во Flutterside, и вы должны сделать stati c объект methodchannel

Например

class MethodChannelHelper {
  static const MethodChannel channel = const MethodChannel('method_channal_name');
}
class MethodChannelCall{
        static initMethodChannel({Function onCallBack}) async {
            MethodChannelHelper.channel.setMethodCallHandler((MethodCall call) async {
              switch (call.method) {
                case 'callback_from_native':
                  print("This method will be called when native fire")
              }
            });
     await MethodChannelHelper.channel.invokeMethod('call_native');
          }
}

В main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MethodChannelCall.initMethodChannel(onCallBack: (payload) {

  });
  runApp(MyApp());
}

Сейчас в Android сторона

 override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
 when (call.method) {
            "call_native" -> {
            methodChannel?.invokeMethod("callback_from_native","")

}
}
...