因爲Flutter boost目前尚未很好的解決方案,因此只能魔改了,大體的思路就是在剛打開app的時候就初始化一個不可見的Flutter頁面,讓其自動註冊&初始化。java
先編寫一個FlutterFragmentandroid
package xxx; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.taobao.idlefish.flutterboost.containers.BoostFlutterFragment; import io.flutter.plugins.GeneratedPluginRegistrant;import java.util.HashMap; import java.util.Map; import io.flutter.plugin.common.PluginRegistry; public class MagicFragment extends BoostFlutterFragment { public MagicFragment() { } public static MagicFragment instance(String tag) { MagicFragment fragment = new MagicFragment(); fragment.setTabTag(tag); return fragment; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void setArguments(@Nullable Bundle args) { if (args == null) { args = new Bundle(); args.putString("tag", ""); } super.setArguments(args); } public void setTabTag(String tag) { Bundle args = new Bundle(); args.putString("tag", tag); super.setArguments(args); } @Override public void onRegisterPlugins(PluginRegistry registry) { GeneratedPluginRegistrant.registerWith(registry); } @Override public String getContainerName() { return ""; } @Override public Map getContainerParams() { Map<String, String> params = new HashMap<>(); return params; } @Override public void destroyContainer() { } @Override public void onContainerShown() { super.onContainerShown(); } }
而後在應用的第一個頁面的Activity中加入一個不可見的FrameLayoutapp
<FrameLayout android:id="@+id/magic" android:layout_width="1dp" android:layout_height="1dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"></FrameLayout>
而後在應用的第一個頁面的Activity中加入一個方法,把這個Fragment加入到這個Activity中ide
private fun addMagicFragment() { var time: Long = System.currentTimeMillis() val instance = instance("magic") val fm = supportFragmentManager val ft = fm.beginTransaction() val cacheFragment = fm.findFragmentByTag("magic") if (cacheFragment != null) { ft.show(cacheFragment) } else { ft.add(R.id.magic, instance) } ft.commit() }
這樣每次打開app就會第一時間去初始化Flutter了。spa