1. How to embed the Flutter Module in an existing Android project
  2. How does an Activity jump to a Flutter page and transfer values
  3. How does a Flutter jump to an Activity and transfer values
  4. The Android module interacts with the Flutter module

All source code has been uploadedgithub

There are two ways to Flutter jump Activity:

  1. Notify the Android layer to jump through a Channel
  2. Embed the Flutter page directly into the Android View

How does a Flutter jump to an Activity and transfer values

Let’s modify the previous MainActivity and add our sample code this time

The Android code

MainActivity.kt

package com.liuhc.myapplication

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import io.flutter.view.FlutterMain
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.startActivity

Liuhc, liuhc, liuHC, liuHC, liuHC */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?). {
        // It is highly recommended that we initialize it once in Application, just for example
        FlutterMain.startInitialization(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //addContentView adds the FlutterView
        page1.setOnClickListener {
            startActivity<Page1Activity>()
        }

        // Add FlutterView in normal Fragment mode
        page2.setOnClickListener {
            startActivity<Page2Activity>()
        }

        / / use FlutterFragmentActivity
        page3.setOnClickListener {
            startActivity<PageFlutterFragmentActivity>()
        }

        / / use FlutterActivity
        page4.setOnClickListener {
            startActivity<PageFlutterActivity>()
        }

        //addContentView adds the FlutterView and passes the parameters
        page1Param.setOnClickListener {
            startActivity<Page1ParamActivity>()
        }

        // Another way to resolve the black screen in debug mode
        noBlack.setOnClickListener {
            startActivity<DebugNoBlackActivity>()
        }

        // Enter the Flutter page to demonstrate jumping to the Activity via Channel
        jumpByChannel.setOnClickListener {
            startActivity<JumpActivityFlutterWidget>()
        }

        // Enter the Flutter page embedded with Android View
        insertAndroidView.setOnClickListener {
            startActivity<InsertAndroidViewFlutterWidget>()
        }
    }

}
Copy the code

JumpActivityFlutterWidget.kt

package com.liuhc.myapplication

import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterMain
import org.jetbrains.anko.startActivity

/** * Description: This page contains the FlutterView, and then click the button in the FlutterView to jump to another Activity. 2019-09-04 on 23:30 */
class JumpActivityFlutterWidget : FlutterActivity() {

    private lateinit var methodChannel: MethodChannel

    override fun onCreate(savedInstanceState: Bundle?). {
        // It is highly recommended that we initialize it once in Application, just for example
        FlutterMain.startInitialization(this)
        // Intent parameters must be set before super.oncreate because super.oncreate takes those parameters
        intent.action = "android.intent.action.RUN"
        intent.putExtra("route"."page4")
        super.onCreate(savedInstanceState)
        initMethodChannel()
        // flutterView will have a value after calling super.oncreate (savedInstanceState).
        // If you need to register a plug-in, you should place it after the super.onCreate(savedInstanceState) code
        flutterView.enableTransparentBackground()
    }

    1, use Channel
    private fun initMethodChannel(a) {
        methodChannel = MethodChannel(
            this.registrarFor("pluginKeyMainActivity").messenger(),
            "MainActivityMethodChannel"
        )
        methodChannel.setMethodCallHandler { methodCall, result ->
            if (methodCall.method == "jumpTestActivity") {
                startActivity<TestActivity>()
            }
        }
    }
}
Copy the code

TestActivity.kt

package com.liuhc.myapplication

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.LinearLayout
import android.widget.TextView

/** * liuhc * 标 题 : 2019-09-05 on 14:31 */
class TestActivity : AppCompatActivity() {

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        val linearLayout = LinearLayout(this)
        val layoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        val textView = TextView(this)
        textView.text = "TestActivity: I got jumped back"
        val viewParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        linearLayout.addView(textView, viewParam)
        setContentView(linearLayout, layoutParam)
    }

}
Copy the code

InsertAndroidViewFlutterWidget.kt

package com.liuhc.myapplication

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import io.flutter.view.FlutterMain
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.startActivity

Liuhc, liuhc, liuHC, liuHC, liuHC */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?). {
        // It is highly recommended that we initialize it once in Application, just for example
        FlutterMain.startInitialization(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //addContentView adds the FlutterView
        page1.setOnClickListener {
            startActivity<Page1Activity>()
        }

        // Add FlutterView in normal Fragment mode
        page2.setOnClickListener {
            startActivity<Page2Activity>()
        }

        / / use FlutterFragmentActivity
        page3.setOnClickListener {
            startActivity<PageFlutterFragmentActivity>()
        }

        / / use FlutterActivity
        page4.setOnClickListener {
            startActivity<PageFlutterActivity>()
        }

        //addContentView adds the FlutterView and passes the parameters
        page1Param.setOnClickListener {
            startActivity<Page1ParamActivity>()
        }

        // Another way to resolve the black screen in debug mode
        noBlack.setOnClickListener {
            startActivity<DebugNoBlackActivity>()
        }

        // Enter the Flutter page to demonstrate jumping to the Activity via Channel
        jumpByChannel.setOnClickListener {
            startActivity<JumpActivityFlutterWidget>()
        }

        // Enter the Flutter page embedded with Android View
        insertAndroidView.setOnClickListener {
            startActivity<InsertAndroidViewFlutterWidget>()
        }
    }

}
Copy the code

The Dart code

main.dart

import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';

import 'insert_android_view_page.dart';
import 'invoke_method_page.dart';
import 'jump_activity_page.dart';
import 'my_home_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      1 / / way
      home: _getWidgetByRoute(window.defaultRouteName),
      // If the routes are the same, match routes instead of home
      routes: <String, WidgetBuilder>{
        "page1": (context) => MyHomePage(
              title: "Page1 is matched.",
              message: "Via routes variable",),"page2": (context) => MyHomePage(
              title: "Match to page2",
              message: "Via routes variable",),"page3": (context) => MyHomePage(
              title: "Match to page3",
              message: "Via routes variable",),"page4": (context) => JumpActivityPage(),
        "page5": (context) => InsertAndroidViewPage(),
      },
      // onUnknownRoute is used when both routes and home return null
      onUnknownRoute: (RouteSettings settings) {
        return new PageRouteBuilder(pageBuilder: (BuildContext context, _, __) {
          // Here is the returned Widget
          return MyHomePage(
            title: "No match.",
            message: "By onUnknownRoute variable",); }); }); }}// If you want to receive arguments sent by the platform layer, you can only use window.defaultroutename instead of using Channel (which is not normal and strongly recommended).
// Because the route of routes can only be defined in advance, it cannot be determined dynamically
Widget _getWidgetByRoute(String jsonStr) {
  print("json=$jsonStr");
  String _route;
  Map<String.dynamic> jsonMap;
  try {
    jsonMap = json.decode(jsonStr);
    _route = jsonMap["path"];
  } catch (e) {
    print(e);
    _route = jsonStr;
  }
  switch (_route) {
    Jump to the page of the flutter when the matching rule is received
    case 'page1':
      return MyHomePage(
        title: "Page1 is matched.",
        message: "By home variable",);case 'page1Param':
      return MyHomePage(
        title: "Match to page1Param",
        message: jsonMap["param"]);case "InvokeMethodPage":
      return InvokeMethodPage(
        title: jsonMap["title"],
        channelName: jsonMap["channelName"],
        androidMethod: jsonMap["androidMethod"]);default:
      return MyHomePage(
        title: "No match.",
        message: "By home variable",); }}Copy the code

jump_activity_page.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class JumpActivityPage extends StatefulWidget {
  @override
  _JumpActivityPageState createState() => _JumpActivityPageState();
}

class _JumpActivityPageState extends State<JumpActivityPage> {

  MethodChannel _methodChannel;

  @override
  void initState() {
    _methodChannel = MethodChannel("MainActivityMethodChannel");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("I am the Flutter page"),
      ),
      body: RaisedButton(
        child: Text("Click me to notify the Android layer to jump to the page by sending a Channel message"),
        onPressed: (){
          _methodChannel.invokeMethod("jumpTestActivity"); },),); }}Copy the code

insert_android_view_page.dart

import 'dart:io' show Platform;

import 'package:flutter/material.dart';

/// Description: Embed AndroidView
/// Author: liuhc
/// 2019-09-05 on 3:20pm 2019-09-05 on 3:20pm 2019-09-05 on 3:20pm
class InsertAndroidViewPage extends StatefulWidget {
  @override
  _InsertAndroidViewPageState createState() => _InsertAndroidViewPageState();
}

class _InsertAndroidViewPageState extends State<InsertAndroidViewPage> {
  GlobalKey key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Let me show you how to embed AndroidView."),
        ),
        body: Platform.isAndroid ? AndroidView(key: key, viewType: 'InsertAndroidView') : Text("Ios and Android work the same way.")); }}Copy the code

Welcome to the Flutter development group 457664582. Click join to learn and discuss Flutter