Hello everyone, I have been learning Flutter for more than a month. Today, I finally arrived at the mixed development I have been dreaming of. During this period, I did not write many things, and I will make up for them when I have time later.

  • Creating an Android project
  • Android jumps to the Flutter page
  • Android jumps to the page specified for Flutter
  • Mixed development Flutter engine issues
  • The Flutter engine jumps to the specified page
  • Android transition animation jumps to the Flutter page

No matter what you are, no matter what you are for, as long as you live in this world, it is necessary to live up to your youth, because youth is just blooming to the extreme but the end of too hasty a farce, so until the end of the world, to love you should love, to do what you should do, to think you should think.

Creating an Android project

If there is a need for mixed development, there must be an Android project. Add Flutter as a Module to the Android project. Remember: Don’t use the Android project that comes with Flutter

Create an Android project with Android Studio

My studio is the latest version of 4.1.

After creating the Android project, create the Flutter_module



Note: How to convert a Flutter project into a Module into an Android project (4.6)

Once created, the directory looks like this:

Here’s what he added:

setBinding(new Binding([gradle: this]))
evaluate(new File(
  settingsDir,
  'flutter_module/.android/include_flutter.groovy'
))
rootProject.name = "AndroidProject"

include ':flutter_module'
Copy the code

This code can be understood as adding the FLUTTER module, which must be added!

The next thing to note is:

The minSdkVersion cannot be <16 because the minimum version of FLUTTER is 16

It is also necessary to use Java8 to parse:

 compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
Copy the code

Finally, add module dependencies:

implementation project(path: ':flutter')
Copy the code

The module name is flutter_module. If you add a dependency, you should add flutter_module.

It’s wrong to think so

Because it’s already declared with this code in settings.gradle:

setBinding(new Binding([gradle: this]))
evaluate(new File(
  settingsDir,
  'flutter_module/.android/include_flutter.groovy'
))
rootProject.name = "AndroidProject"

include ':flutter_module'
Copy the code

So we must write:

implementation project(path: ':flutter')
Copy the code

This is where the FLutter module is created

Android jumps to the Flutter page

The simplest way:

import io.flutter.embedding.android.FlutterActivity;

public class MainActivity extends FlutterActivity {}Copy the code

Directly inherited from FLutterActivity, this opens the code that the Flutter module main() runs

There’s another way:

Simulate real scene, click the button to jump to the page of Flutter;

<? xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me into Flutter."/>

</LinearLayout>
Copy the code

Effect:

Code:

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** * Enter the Main page of Flutter */
                  startActivity(new Intent(MainActivity.this,FlutterActivity.class)); }});Copy the code

Jump to the main() entry method of the Flutter module.

Let’s take a look at the image first:

Android jumps to the page specified for Flutter

When Android jumps to the page specified by Flutter, the route must be declared first.

Declare the route under MeterialApp; Create ImagePage() and TextPage() pages

MaterialApp(
      theme: ThemeData(
      ),
      home: MyHomePage(),
      routes: <String,WidgetBuilder>{
        "image_page" : (context) => ImagePage(ImageTitle),
        "text_page" : (context) => TextPage(),
      },
    );
Copy the code

ImagePage() page effect:



TextPage()



The effect of these two pages is written casually, I will not show you;

The Android part jumps through the specified route:

 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** * Enter the page of the Flutter by specifying the page */
                startActivity(FlutterActivity.
                        withNewEngine().
                        initialRoute("image_page").// Jump to image_page
                        build(MainActivity.this)); }});Copy the code

Effect:



As you can see in the renderings, click the button directly to the image_page page;

What must be noted here is:

  • When using FlutterActivity must import: import IO flutter. Embedding. Android. FlutterActivity this package,
  • Must be in AndroidManifest. In the XML declaration FlutterActivity. < the activity of the android: name = “IO. Flutter. Embedding. Android. FlutterActivity” / >

Mixed development Flutter engine issues

No matter what engine or not, you must have seen the above renderings. Every time you jump from Android to a Flutter, there is a black screen (delay) for 2 seconds. This problem is caused by the need to complete the jump and the page initialization of the Flutter

Solution:

When Android starts up, the Flutter can also be initialized. When Android starts, Application is called first; So declare it in Application

public class App extends Application {

    private FlutterEngine fe;

    @Override
    public void onCreate(a) {
        super.onCreate();
        / / Flutter engine
        fe = new FlutterEngine(this);
        // Use engine_id to create a unique identifier
  		fe.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
        FlutterEngineCache
                .getInstance()
                .put("engine_id", fe);

    }

    /** * onTerminate() Executes */ when App is destroyed
    @Override
    public void onTerminate(a) {
        Destroy the Flutter engine
        fe.destroy();
        super.onTerminate(); }}Copy the code

Remember to declare Application in androidmanifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="demo.ht.com.androidproject">

    <application
    	/ / declare the Application
        android:name=".App". > <activity android:name="io.flutter.embedding.android.FlutterActivity"/>
    </application>

</manifest>
Copy the code

This code is fixed and cached by the engine_id identifier in the Application declaration. The engine_id identifier is unique!

Take a look at how the Android code is used after the declaration:

 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                * Remember: declare App in androidmanifest.xml (Android :name=".app ") * Use engine_id to find the cache and jump to */
                startActivity(FlutterActivity.
                        withCachedEngine("engine_id").
                        build(MainActivity.this)); }});Copy the code

Take a look at the effects of using the Flutter engine cache:



As you can see, no matter how fast I jump, I don’t get a black screen

The Flutter engine jumps to the specified page

To jump to the specified page, add a line of code:

public class App extends Application {

    private FlutterEngine fe;

    @Override
    public void onCreate(a) {
        super.onCreate();
        / / Flutter engine
        fe = new FlutterEngine(this);
        /** * sets the page to cache */
        fe.getNavigationChannel().setInitialRoute("image_page");
        // Use engine_id to create a unique identifier
        fe.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
        FlutterEngineCache
                .getInstance()
                .put("a", fe);

    }


    /** * onTerminate() Executes */ when App is destroyed
    @Override
    public void onTerminate(a) {
        Destroy the Flutter engine
        fe.destroy();
        super.onTerminate(); }}Copy the code
/** * sets the page to cache */
  fe.getNavigationChannel().setInitialRoute("image_page");
Copy the code

This line of code sets the page to jump to!

Check out the results:



You can see the renderings and jump to the image_page as we expected!

Android transition animation jumps to the Flutter page

First come kangkang effect:

Analysis:

  • You can see that there is a transition animation when Android jumps to the Flutter page,
  • You can’t use caching, because if you cache, you jump,
  • The black screen turns to white during the jump

Take a look at the complete code first, and then parse it step by step:

ToFlutterPageActivity jump to Flutter page

public class ToFlutterPageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_flutter_page);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
	              /** * 0 Pass initialization data to Flutter * 1 pass data using BasicMsgChannel * 2 Pass current power using EventChannel * 3 Get data using MethodChannel * 4 Simply jump to Flutter page */
                // Transition animation jumps to the Flutter page
                FlutterAppActivity.start(ToFlutterPageActivity.this."I'm a transition animation.".4); }}); }}Copy the code

FlutterAppActivity page

public class FlutterAppActivity extends FlutterActivity {
 /** * 0 Pass initialization data to Flutter * 1 pass data using BasicMsgChannel * 2 Pass current power using EventChannel * 3 Get data using MethodChannel * 4 Simply jump to Flutter page */
    private static int mtype;

    public static void start(Context context, String initParams, int type) {
        mtype = type;
        Intent intent = new Intent(context, FlutterAppActivity.class);
        intent.putExtra(INIT_PARAMS, initParams);
        context.startActivity(intent);
    }

/** * configureFlutterEngine has a higher priority than onCreate! * *@param flutterEngine
     */
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        if ( mtype == 4 ) {
            // Simply jump to the Flutter page transition animation
            // Pass initialization data to Flutter
            mInitParam = getIntent().getStringExtra(INIT_PARAMS);
            // Set the animationoverridePendingTransition(R.anim.pageup_enter,R.anim.pageup_exit); }}@NonNull
    @Override
    public TransparencyMode getTransparencyMode(a) {
        Log.i("szjmType",mtype+"");
        returnTransparencyMode.transparent ; }}Copy the code
  • Through the overridePendingTransition (int, int) to set up the Android jump Flutter transition animations

  • Set transparency by overriding the getTransparencyMode method

    • TransparencyMode. Transparent transparent (white)
    • Transparencymode.opaque (black) // Default is this

pageup_enter.xml

<? xml version="1.0" encoding="utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="700"
        android:fromYDelta="100%p"
        android:toYDelta="0" />
    <alpha
        android:duration="700"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>
Copy the code

pageup_xit.xml

<? xml version="1.0" encoding="utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="700"
        android:fromYDelta="0"
        android:toYDelta="-100%p" />
    <alpha
        android:duration="700"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>
Copy the code

The simple understanding here is that there was a black screen when Android jumped to the Flutter page. Now the black screen is changed to transparent color.

Why is this white? Because the flutter page startup is white.

Now will jump through the process of the overridePendingTransition (int int) to set up a anim animation.

The complete code

What do you like?

Pass initialization data to Android for Flutter hybrid development (4.2)

BasicMessageChannel and native android communication (4.3)

Flutter hybrid development EventChannel one-way data transfer (4.4)

MethodChannel of Flutter hybrid development one-way message passing (4.5)

How to convert a Flutter project into a Module into an Android project (4.6)

Your like is the biggest support for me, leave your like ~