Android native projects access the Flutter Module

1. Add the Flutter Module to settings.gradle

setBinding(new Binding([gradle: this]))
evaluate(new File(
        settingsDir.parentFile,
        '.. /Flutter/flutter_module/.android/include_flutter.groovy'
))
Copy the code

2. In build. Gradle of app

// Integrate the Flutter project
implementation project(':flutter')
Copy the code

3. Create the FLUTTER engine

/ * * *@Description: Start engine, send message, and receive message utility classes *@Version: 1.0
 * @Author: samson
 * @Date: 2021/7/23 10:52 * /
public class FlutterTools {

    public static final String ENGINE_ID = "default_engine_id";

    private static final String              METHOD_CHANNEL = "com.basic.message.channel";
    / / flutter engine
    private static       FlutterEngine       sFlutterEngine;
    // Message channel
    private static       BasicMessageChannel basicMessageChannel;

    /** * Load the Flutter engine **@param context
     */
    public static void preWarmFlutterEngine(Context context) {
        if (null == sFlutterEngine) {
            sFlutterEngine = new FlutterEngine(context);
            sFlutterEngine.getDartExecutor().executeDartEntrypoint(
                    DartExecutor.DartEntrypoint.createDefault()
            );
            basicMessageChannel = new BasicMessageChannel(sFlutterEngine.getDartExecutor(), METHOD_CHANNEL, StandardMessageCodec.INSTANCE);
            FlutterEngineCache.getInstance().put(ENGINE_ID, sFlutterEngine);
            // Accept flutter message listening
            basicMessageChannel.setMessageHandler((message, reply) -> {
                // Accept a flutter message to jump to the native page, depending on the message
                 String messageStr = (String) message;
                if(message ! =null) { NativeFlutterEntity flutterEntity = JsonUtil.getBeanFromJsonStr(messageStr, NativeFlutterEntity.class); dealFlutterMessage(context,flutterEntity,reply); }}); }}/** * Processes messages sent by flutter *@param context
     * @param flutterEntity
     */
    private static void dealFlutterMessage(Context context, NativeFlutterEntity flutterEntity, BasicMessageChannel.Reply reply){
        if("settingId".equals(flutterEntity.pageId)) {
            / / to set
            Intent intent = newIntent(context, SetActivity.class); context.startActivity(intent); }}/** * Send data to flutter **@param json
     */
    public static void setDataToFlutter(String json) {
        basicMessageChannel.send(json);
    }


    public static void clearEngine(a){
        if(sFlutterEngine ! =null) {
            sFlutterEngine = null; }}/**
     * 销毁引擎
     */
    public static void destroyEngine(a) {
        if(sFlutterEngine ! =null) {
            sFlutterEngine.destroy();
            sFlutterEngine = null; }}}Copy the code

4. Create FlutterActivity

/** * The status of the flutter initialization page will not be refreshed */
public class AndroidFlutterActivity extends FlutterActivity {

    static final  String   EXTRA_CACHED_ENGINE_ID = "cached_engine_id";
    static final  String   EXTRA_ROUTE = "extra_route";
    static final  String   EXTRA_DESTROY_ENGINE_WITH_ACTIVITY = "destroy_engine_with_activity";
    public static Activity mActivity;
    private BroadcastReceiver broadcastReceiver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
    }

    /** * Open the flutter jump page *@param context
     * @param route
     */
    public static void open(Context context, String route) {
        Intent intent = new Intent(context, AndroidFlutterActivity.class)
                .putExtra(EXTRA_CACHED_ENGINE_ID, "default_engine_id")
                .putExtra(EXTRA_ROUTE, route)
                // Keep the FlutterEngine when the Activity is destroyed
                .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, false);
        context.startActivity(intent);
    }

    /** * Load flutterView */
    @Override
    public void onFlutterUiDisplayed(a) {
        super.onFlutterUiDisplayed();
        // Set the entry of the Flutter interface. Be careful not to call it in the onCreate method, otherwise
        // The entry of the Flutter will not update.
        String route = getIntent().getStringExtra(EXTRA_ROUTE);
        // Send routing messages to the FLUTTER page
        FlutterTools.setDataToFlutter(route);
    }

    @Override
    public void onFlutterUiNoLongerDisplayed(a) {
        super.onFlutterUiNoLongerDisplayed(); }}Copy the code
<! -- Android jump flutter -->
<activity
    android:name="io.flutter.embedding.android.FlutterActivity"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:theme="@style/FlutterPageTheme"
    android:windowSoftInputMode="adjustResize"/>
<activity
    android:name=".flutter.AndroidFlutterActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:screenOrientation="portrait"
    android:theme="@style/FlutterPageTheme"
    tools:ignore="LockedOrientationActivity" />
Copy the code

5. In flutter Module

// Message channel
  static late BasicMessageChannel messageChannel;

  ///Initialize the
  static init() {
    messageChannel = const BasicMessageChannel(
        "com.basic.message.channel", StandardMessageCodec());
  }

 /// Send data to native
  static Future<dynamic> sendData(
      {required String  data}) async {
 // It is best to pass data in JSON format
    return await sendMessage(data);
  }

  @override
  void initState() {
    super.initState();
    // Set MethodCallHandler to receive messages from Android
    FlutterToNative.receiveData((message) async {
      _handleInitRouteMethodCall(message);
    });
  }

// Open different pages depending on the incoming URL
 void _handleInitRouteMethodCall(String routeUrl) async {
    switch (routeUrl) {
      case '/authorityPage':
        _initRoute = AuthorityPage();
        break;
      case '/HomePage':
        _initRoute = HomePage();
        break;
      default:
        _initRoute = WelcomePage();
        break;
    }

    /// Update the interface
    setState(() {});
  }
Copy the code