由于Flutter boost目前还没有很好的解决方案,所以只能魔改了,大致的思路就是在刚打开app的时候就初始化一个不可见的Flutter页面,让其自动注册&初始化。
先编写一个FlutterFragment
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中加入一个不可见的FrameLayout
<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中
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了。