Today we are going to introduce how to transfer data from Android native to Flutter initialization. This is the latest version of Flutter initialization.
In the long future, countless time will change life bit by bit that can not resist the track, let the people in love separated, let the oath into nihilistic memories, let the young poem harp accumulate years of wind and sand, let read to the name engraved in the cemetery stele. Long enough for you and me to meet, fall in love, and. To make you fall in love with someone else.
Let’s take a look at today’s results:
(Effect Figure 1.1):
Analysis:
- Android layouts a button, a text box
- The flutter layout: a Text() receives data sent by Android
Android layout:
<? 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=".ToFlutterDataActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me into Flutter."/>
<EditText
android:id="@+id/edit"
android:hint="A word to Flutter"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:background="#42aabbcc"
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Copy the code
Effect:
Rendering (1.2) :
Java code :(ToFlutterDataActivity class)
public class ToFlutterDataActivity extends AppCompatActivity {
public final static String INIT_PARAMS = "initParams";
BasicMessageChannelPlugin basicMessageChannelPlugin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edit = findViewById(R.id.edit);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FlutterAppActivity.start(ToFlutterDataActivity.this,edit.getText().toString()); }}); }}Copy the code
Java code :(FlutterAppActivity class);
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
public class FlutterAppActivity extends FlutterActivity {
public final static String INIT_PARAMS = "initParams";
public static void start(Context context, String initParams) {
Intent intent = new Intent(context, FlutterAppActivity.class);
intent.putExtra(INIT_PARAMS, initParams);
context.startActivity(intent);
}
String mInitParam;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInitParam = getIntent().getStringExtra(INIT_PARAMS);
}
/** Pass the initialization parameter */ through the getInitialRoute method
@NonNull
@Override
public String getInitialRoute(a) {
return mInitParam == null ? super.getInitialRoute() : mInitParam;
}
// Use the Flutter engine pre-initialized in MyApplication to increase the Flutter page opening speed.
// Note: in this mode, getInitialRoute will not be called so initialization parameters cannot be set
// @Override
// public String getCachedEngineId() {
// return App.ENG_INED;
/ /}
}
Copy the code
As you can see, it’s pretty simple in the layout but you might ask, why doesn’t MianActivity inherit directly from FlutterActivity?
This is where the life cycle comes into play, because you click on a button to pass data to a flutter. As we mentioned in the previous chapter,FlutterActivity is the main method that a flutter executes. In a nutshell,FlutterActivity is the implementation of a flutter page Click the button to jump to the Flutter page. If ToFlutterDataActivity directly inherits from FlutterActivity, the method passing the initialization parameters (getInitialRoute) in ToFlutterDataActivity is executed at startup, but the method passing the parameters after clicking the button is not. Writing a new class (FlutterAppActivity) inherited from FlutterAppActivity perfectly avoids the problem of passing parameters without executing
FlutterAppActivity in this class is very simple: just get the parameters passed to the Flutter by ToFlutterappActivity and pass them to the Flutter method getInitialRoute()
/** * Pass initialization parameters to Flutter *@return* /
@NonNull
@Override
public String getInitialRoute(a) {
return mInitParam == null ? super.getInitialRoute() : mInitParam;
}
Copy the code
Here are some things to note:
The Flutter engine (FlutterEngine()) must be initialized in Application
public class App extends Application {
private FlutterEngine fe;
public static String ENG_INED ="engined";
@Override
public void onCreate(a) {
super.onCreate();
/ / Flutter engine
fe = new FlutterEngine(this);
/** * sets the page to cache */
// fe.getNavigationChannel().setInitialRoute("text_page");
/ / by engine_id unique identifier to cache fe. GetDartExecutor () executeDartEntrypoint (DartExecutor. DartEntrypoint. CreateDefault ());
FlutterEngineCache
.getInstance()
.put(ENG_INED, 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 your App and Activity in AndroidMainifest. XML
<? xml version="1.0" encoding="utf-8"? > <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="demo.ht.com.androidproject">
<application
android:name=".App". >... <activity android:name=".FlutterAppActivity"/>
<activity android:name="io.flutter.embedding.android.FlutterActivity" />
</application>
</manifest>
Copy the code
This concludes the Android code. Let’s look at the code for Flutter:
import 'dart:ui';
void main(a) => runApp(MyApp(window.defaultRouteName));
Copy the code
Window. defaultRouteName is imported as’ dart: UI ‘;
Flutter obtains data from Android via windod. defaultRouteName.
Take a look at the results:
Rendering (1.3)
You can see the effect and the implementation,However, during the jump, there is a black screen of 1-2sIn theIn the previousIf the Flutter engine is used, the page can be cached first, and then the black screen will not appear when jumping. However, the Flutter engine is also used in the code above.
Solutions:
In FlutterAppActivity, override the getCachedEngineId() method to return the app.eng_ined parameter, using the cache
// Use the Flutter engine pre-initialized in MyApplication to increase the Flutter page opening speed.
// Note: in this mode, getInitialRoute will not be called so initialization parameters cannot be set
@Override
public String getCachedEngineId(a) {
return App.ENG_INED;
}
Copy the code
Rendering (1.5) :
As you can see, the black screen problem was resolved, but the flutter did not get the data sent by Android because the getInitialRoute() would not be called in this mode and therefore could not set the initialization parameters
Conclusion:
You can only choose between passing initialization parameters and caching pages. I recommend caching pages because everything is cleared.
Notes for this chapter:
The Android side:
- GetInitalRoute () can pass initialization parameters or getCachedEngineId() can cache pages
- Note the addition of the Activity’s four component declarations in Androidmainifest. XML
- Enough to add the Appcation declaration in androidMainifest. XML
The Flutter end:
- Receive data from Android via window.defaultRouteName
- Window. defaultRoute adds the guide package to :Nameimport ‘dart: UI’;
The complete code
What do you like?
Android jump page, FLutter engine, etc. (4.1)
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)
Original is not easy, your thumbs up is my biggest support, leave your thumbs up ~