Flutter在Android端註冊外掛流程原始碼解析

o動感超人o發表於2019-09-06

先發一段Flutter在Android註冊外掛的程式碼流程,這裡就拿我之前寫的Flutter與Android的混合開發(2)Activity如何跳轉到Flutter頁面,如何傳值裡的PageFlutterActivity.kt類來舉例

PageFlutterActivity.kt

package com.liuhc.myapplication

import android.os.Bundle
import android.util.Log
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterMain
import org.json.JSONObject

/**
 * 描述:
 * 作者:liuhc
 * 建立日期:2019-09-04 on 23:30
 */
class PageFlutterActivity : FlutterActivity() {

    private lateinit var methodChannel: MethodChannel

    override fun onCreate(savedInstanceState: Bundle?) {
        //強烈建議放到Application裡初始化,初始化一次即可,放這裡只是舉個例子
        FlutterMain.startInitialization(this)
        //intent的引數設定必須在super.onCreate之前,因為super.onCreate裡會取這些引數
        intent.action = "android.intent.action.RUN"
        val channelName = "channelName_PageFlutterActivity"
        val androidMethod = "methodName_PageFlutterActivity"
        val jsonObject = JSONObject()
        jsonObject.put("path", "InvokeMethodPage")
        jsonObject.put("title", "PageFlutterActivity")
        jsonObject.put("channelName", channelName)
        jsonObject.put("androidMethod", androidMethod)
        intent.putExtra("route", jsonObject.toString())
        super.onCreate(savedInstanceState)
        //呼叫super.onCreate(savedInstanceState)之後flutterView才有值,
        //所以如果需要註冊外掛,則應該放到super.onCreate(savedInstanceState)程式碼之後才可以
        flutterView.enableTransparentBackground()
        //如果不需要平臺互動的話,只需要上面的程式碼並在最後加上super.onCreate就可以了
        //這裡this.registrarFor方法實際呼叫的是FlutterFragmentActivity裡的delegate的registrarFor方法,
        //而delegate的registrarFor方法實際呼叫的是FlutterActivityDelegate裡的flutterView.getPluginRegistry().registrarFor方法,
        //而FlutterActivityDelegate裡的flutterView在呼叫了這裡的super.onCreate(savedInstanceState)才有值,
        //所以如果需要註冊外掛,則應該放到super.onCreate(savedInstanceState)程式碼之後才可以
        val key = "PageFlutterActivity"
        if (this.hasPlugin(key)) return
        val registrar = this.registrarFor(key)
        methodChannel = MethodChannel(
            registrar.messenger(),
            channelName
        )
        methodChannel.setMethodCallHandler { methodCall, result ->
            if (methodCall.method == androidMethod) {
                Log.e("Android", "接收到了Flutter傳遞的引數:${methodCall.arguments}")
                result.success("$androidMethod ok")
                Log.e("Android", "主動呼叫Flutter的methodInvokeMethodPageState方法")
                methodChannel.invokeMethod("methodInvokeMethodPageState", "Android傳送給Flutter的引數")
            }
        }
    }

}
複製程式碼

看其中的這段程式碼

methodChannel = MethodChannel(
    registrar.messenger(),
    channelName
)
複製程式碼

MethodChannel這裡我們傳了2個引數,第二個就是一個String型別,我們主要看第一個registrar.messenger()是什麼,這個registrar是我們呼叫父類的方法registrarFor(key)得到的,所以我們去父類檢視registrarFor方法,原始碼如下:

FlutterActivity

public class FlutterActivity extends Activity implements Provider, PluginRegistry, ViewFactory {
    private static final String TAG = "FlutterActivity";
    private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this);
    private final FlutterActivityEvents eventDelegate;
    private final Provider viewProvider;
    private final PluginRegistry pluginRegistry;

    public FlutterActivity() {
        this.eventDelegate = this.delegate;
        this.viewProvider = this.delegate;
        this.pluginRegistry = this.delegate;
    }

    public FlutterView getFlutterView() {
        return this.viewProvider.getFlutterView();
    }

    public final boolean hasPlugin(String key) {
        return this.pluginRegistry.hasPlugin(key);
    }

    public final Registrar registrarFor(String pluginKey) {
        return this.pluginRegistry.registrarFor(pluginKey);
    }
    //刪掉了這裡不需要關心的程式碼
}
複製程式碼

可以看到registrarFor方法呼叫的是this.pluginRegistry.registrarFor方法,而this.pluginRegistry在建構函式裡可看到實際上是FlutterActivityDelegate類的例項,所以我們再去看FlutterActivityDelegate的原始碼

FlutterActivityDelegate

public final class FlutterActivityDelegate implements FlutterActivityEvents, Provider, PluginRegistry {
    private static final String SPLASH_SCREEN_META_DATA_KEY = "io.flutter.app.android.SplashScreenUntilFirstFrame";
    private static final String TAG = "FlutterActivityDelegate";
    private static final LayoutParams matchParent = new LayoutParams(-1, -1);
    private final Activity activity;
    private final FlutterActivityDelegate.ViewFactory viewFactory;
    private FlutterView flutterView;
    private View launchView;

    public FlutterActivityDelegate(Activity activity, FlutterActivityDelegate.ViewFactory viewFactory) {
        this.activity = (Activity)Preconditions.checkNotNull(activity);
        this.viewFactory = (FlutterActivityDelegate.ViewFactory)Preconditions.checkNotNull(viewFactory);
    }

    public FlutterView getFlutterView() {
        return this.flutterView;
    }

    public boolean hasPlugin(String key) {
        return this.flutterView.getPluginRegistry().hasPlugin(key);
    }

    public Registrar registrarFor(String pluginKey) {
        return this.flutterView.getPluginRegistry().registrarFor(pluginKey);
    }

    public void onCreate(Bundle savedInstanceState) {
        if (VERSION.SDK_INT >= 21) {
            Window window = this.activity.getWindow();
            window.addFlags(-2147483648);
            window.setStatusBarColor(1073741824);
            window.getDecorView().setSystemUiVisibility(1280);
        }

        String[] args = getArgsFromIntent(this.activity.getIntent());
        FlutterMain.ensureInitializationComplete(this.activity.getApplicationContext(), args);
        this.flutterView = this.viewFactory.createFlutterView(this.activity);
        if (this.flutterView == null) {
            FlutterNativeView nativeView = this.viewFactory.createFlutterNativeView();
            this.flutterView = new FlutterView(this.activity, (AttributeSet)null, nativeView);
            this.flutterView.setLayoutParams(matchParent);
            this.activity.setContentView(this.flutterView);
            this.launchView = this.createLaunchView();
            if (this.launchView != null) {
                this.addLaunchView();
            }
        }

        if (!this.loadIntent(this.activity.getIntent())) {
            String appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
            if (appBundlePath != null) {
                this.runBundle(appBundlePath);
            }

        }
    }

    private boolean loadIntent(Intent intent) {
        String action = intent.getAction();
        if ("android.intent.action.RUN".equals(action)) {
            String route = intent.getStringExtra("route");
            String appBundlePath = intent.getDataString();
            if (appBundlePath == null) {
                appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
            }

            if (route != null) {
                this.flutterView.setInitialRoute(route);
            }

            this.runBundle(appBundlePath);
            return true;
        } else {
            return false;
        }
    }

    private void runBundle(String appBundlePath) {
        if (!this.flutterView.getFlutterNativeView().isApplicationRunning()) {
            FlutterRunArguments args = new FlutterRunArguments();
            ArrayList<String> bundlePaths = new ArrayList();
            bundlePaths.add(appBundlePath);
            args.bundlePaths = (String[])bundlePaths.toArray(new String[0]);
            args.entrypoint = "main";
            this.flutterView.runFromBundle(args);
        }

    }

    public interface ViewFactory {
        FlutterView createFlutterView(Context var1);

        FlutterNativeView createFlutterNativeView();

        boolean retainFlutterNativeView();
    }
    //刪掉了這裡不需要關心的程式碼
}
複製程式碼

找到其中的registrarFor方法

public Registrar registrarFor(String pluginKey) {
    return this.flutterView.getPluginRegistry().registrarFor(pluginKey);
}
複製程式碼

發現呼叫的是this.flutterView.getPluginRegistry().registrarFor(pluginKey),我們再去看FlutterView的原始碼

FlutterView

public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
    private FlutterNativeView mNativeView;

    public FlutterView(Context context) {
        this(context, (AttributeSet)null);
    }

    public FlutterView(Context context, AttributeSet attrs) {
        this(context, attrs, (FlutterNativeView)null);
    }

    public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
        super(context, attrs);
        this.nextTextureId = new AtomicLong(0L);
        this.mIsSoftwareRenderingEnabled = false;
        this.onAccessibilityChangeListener = new OnAccessibilityChangeListener() {
            public void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
                FlutterView.this.resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled);
            }
        };
        Activity activity = getActivity(this.getContext());
        if (activity == null) {
            throw new IllegalArgumentException("Bad context");
        } else {
            if (nativeView == null) {
                this.mNativeView = new FlutterNativeView(activity.getApplicationContext());
            } else {
                this.mNativeView = nativeView;
            }

            this.dartExecutor = this.mNativeView.getDartExecutor();
            this.flutterRenderer = new FlutterRenderer(this.mNativeView.getFlutterJNI());
            this.mIsSoftwareRenderingEnabled = FlutterJNI.nativeGetIsSoftwareRenderingEnabled();
            this.mMetrics = new FlutterView.ViewportMetrics();
            this.mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
            this.setFocusable(true);
            this.setFocusableInTouchMode(true);
            this.mNativeView.attachViewAndActivity(this, activity);
            this.mSurfaceCallback = new Callback() {
                public void surfaceCreated(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface());
                }

                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceChanged(width, height);
                }

                public void surfaceDestroyed(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceDestroyed();
                }
            };
            this.getHolder().addCallback(this.mSurfaceCallback);
            this.mActivityLifecycleListeners = new ArrayList();
            this.mFirstFrameListeners = new ArrayList();
            this.navigationChannel = new NavigationChannel(this.dartExecutor);
            this.keyEventChannel = new KeyEventChannel(this.dartExecutor);
            this.lifecycleChannel = new LifecycleChannel(this.dartExecutor);
            this.localizationChannel = new LocalizationChannel(this.dartExecutor);
            this.platformChannel = new PlatformChannel(this.dartExecutor);
            this.systemChannel = new SystemChannel(this.dartExecutor);
            this.settingsChannel = new SettingsChannel(this.dartExecutor);
            PlatformPlugin platformPlugin = new PlatformPlugin(activity, this.platformChannel);
            this.addActivityLifecycleListener(platformPlugin);
            this.mImm = (InputMethodManager)this.getContext().getSystemService("input_method");
            PlatformViewsController platformViewsController = this.mNativeView.getPluginRegistry().getPlatformViewsController();
            this.mTextInputPlugin = new TextInputPlugin(this, this.dartExecutor, platformViewsController);
            this.androidKeyProcessor = new AndroidKeyProcessor(this.keyEventChannel, this.mTextInputPlugin);
            this.androidTouchProcessor = new AndroidTouchProcessor(this.flutterRenderer);
            this.mNativeView.getPluginRegistry().getPlatformViewsController().attachTextInputPlugin(this.mTextInputPlugin);
            this.sendLocalesToDart(this.getResources().getConfiguration());
            this.sendUserPlatformSettingsToDart();
        }
    }

    public FlutterNativeView getFlutterNativeView() {
        return this.mNativeView;
    }

    public FlutterPluginRegistry getPluginRegistry() {
        return this.mNativeView.getPluginRegistry();
    }

    public interface Provider {
        FlutterView getFlutterView();
    }
}
複製程式碼

找到其中的getPluginRegistry方法

public FlutterPluginRegistry getPluginRegistry() {
    return this.mNativeView.getPluginRegistry();
}
複製程式碼

this.mNativeViewFlutterNativeView的例項,我們再去看FlutterNativeView

FlutterNativeView

public class FlutterNativeView implements BinaryMessenger {
    private static final String TAG = "FlutterNativeView";
    private final FlutterPluginRegistry mPluginRegistry;
    private final DartExecutor dartExecutor;
    private FlutterView mFlutterView;
    private final FlutterJNI mFlutterJNI;
    private final Context mContext;
    private boolean applicationIsRunning;

    public FlutterNativeView(@NonNull Context context) {
        this(context, false);
    }

    public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
        this.mContext = context;
        this.mPluginRegistry = new FlutterPluginRegistry(this, context);
        this.mFlutterJNI = new FlutterJNI();
        this.mFlutterJNI.setRenderSurface(new FlutterNativeView.RenderSurfaceImpl());
        this.dartExecutor = new DartExecutor(this.mFlutterJNI);
        this.mFlutterJNI.addEngineLifecycleListener(new FlutterNativeView.EngineLifecycleListenerImpl());
        this.attach(this, isBackgroundView);
        this.assertAttached();
    }

    @NonNull
    public FlutterPluginRegistry getPluginRegistry() {
        return this.mPluginRegistry;
    }

    public void runFromBundle(FlutterRunArguments args) {
        boolean hasBundlePaths = args.bundlePaths != null && args.bundlePaths.length != 0;
        if (args.bundlePath == null && !hasBundlePaths) {
            throw new AssertionError("Either bundlePath or bundlePaths must be specified");
        } else if ((args.bundlePath != null || args.defaultPath != null) && hasBundlePaths) {
            throw new AssertionError("Can't specify both bundlePath and bundlePaths");
        } else if (args.entrypoint == null) {
            throw new AssertionError("An entrypoint must be specified");
        } else {
            if (hasBundlePaths) {
                this.runFromBundleInternal(args.bundlePaths, args.entrypoint, args.libraryPath);
            } else {
                this.runFromBundleInternal(new String[]{args.bundlePath, args.defaultPath}, args.entrypoint, args.libraryPath);
            }

        }
    }

    /** @deprecated */
    @Deprecated
    public void runFromBundle(String bundlePath, String defaultPath, String entrypoint, boolean reuseRuntimeController) {
        this.runFromBundleInternal(new String[]{bundlePath, defaultPath}, entrypoint, (String)null);
    }

    private void runFromBundleInternal(String[] bundlePaths, String entrypoint, String libraryPath) {
        this.assertAttached();
        if (this.applicationIsRunning) {
            throw new AssertionError("This Flutter engine instance is already running an application");
        } else {
            this.mFlutterJNI.runBundleAndSnapshotFromLibrary(bundlePaths, entrypoint, libraryPath, this.mContext.getResources().getAssets());
            this.applicationIsRunning = true;
        }
    }

    @UiThread
    public void send(String channel, ByteBuffer message) {
        this.dartExecutor.send(channel, message);
    }

    @UiThread
    public void send(String channel, ByteBuffer message, BinaryReply callback) {
        if (!this.isAttached()) {
            Log.d("FlutterNativeView", "FlutterView.send called on a detached view, channel=" + channel);
        } else {
            this.dartExecutor.send(channel, message, callback);
        }
    }

    @UiThread
    public void setMessageHandler(String channel, BinaryMessageHandler handler) {
        this.dartExecutor.setMessageHandler(channel, handler);
    }

    FlutterJNI getFlutterJNI() {
        return this.mFlutterJNI;
    }
    //刪掉了不需要關心的程式碼
}
複製程式碼

找到其中的getPluginRegistry方法

@NonNull
public FlutterPluginRegistry getPluginRegistry() {
    return this.mPluginRegistry;
}
複製程式碼

然後再看一下FlutterPluginRegistry的程式碼

FlutterPluginRegistry

public class FlutterPluginRegistry implements PluginRegistry, RequestPermissionsResultListener, ActivityResultListener, NewIntentListener, UserLeaveHintListener, ViewDestroyListener {
    private static final String TAG = "FlutterPluginRegistry";
    private Activity mActivity;
    private Context mAppContext;
    private FlutterNativeView mNativeView;
    private FlutterView mFlutterView;
    private final PlatformViewsController mPlatformViewsController;
    private final Map<String, Object> mPluginMap = new LinkedHashMap(0);
    private final List<RequestPermissionsResultListener> mRequestPermissionsResultListeners = new ArrayList(0);
    private final List<ActivityResultListener> mActivityResultListeners = new ArrayList(0);
    private final List<NewIntentListener> mNewIntentListeners = new ArrayList(0);
    private final List<UserLeaveHintListener> mUserLeaveHintListeners = new ArrayList(0);
    private final List<ViewDestroyListener> mViewDestroyListeners = new ArrayList(0);

    public FlutterPluginRegistry(FlutterNativeView nativeView, Context context) {
        this.mNativeView = nativeView;
        this.mAppContext = context;
        this.mPlatformViewsController = new PlatformViewsController();
    }

    public FlutterPluginRegistry(FlutterEngine engine, Context context) {
        this.mAppContext = context;
        this.mPlatformViewsController = new PlatformViewsController();
    }

    public boolean hasPlugin(String key) {
        return this.mPluginMap.containsKey(key);
    }

    public Registrar registrarFor(String pluginKey) {
        if (this.mPluginMap.containsKey(pluginKey)) {
            throw new IllegalStateException("Plugin key " + pluginKey + " is already in use");
        } else {
            this.mPluginMap.put(pluginKey, (Object)null);
            return new FlutterPluginRegistry.FlutterRegistrar(pluginKey);
        }
    }

    private class FlutterRegistrar implements Registrar {
        private final String pluginKey;

        FlutterRegistrar(String pluginKey) {
            this.pluginKey = pluginKey;
        }

        public BinaryMessenger messenger() {
            return FlutterPluginRegistry.this.mNativeView;
        }

        public PlatformViewRegistry platformViewRegistry() {
            return FlutterPluginRegistry.this.mPlatformViewsController.getRegistry();
        }

        public FlutterView view() {
            return FlutterPluginRegistry.this.mFlutterView;
        }
    }
}
複製程式碼

我們看其中的registrarFor方法

public Registrar registrarFor(String pluginKey) {
    if (this.mPluginMap.containsKey(pluginKey)) {
        throw new IllegalStateException("Plugin key " + pluginKey + " is already in use");
    } else {
        this.mPluginMap.put(pluginKey, (Object)null);
        return new FlutterPluginRegistry.FlutterRegistrar(pluginKey);
    }
}
複製程式碼

可以看到FlutterActivity的子類呼叫父類的registrarFor時,最終獲取到的返回值就是FlutterPluginRegistry.FlutterRegistrar類的例項

到這裡我們把整個流程梳理一下

最開始FlutterActivity的子類呼叫registrarFor方法時,最終呼叫順序是FlutterActivity.registrarFor->FlutterActivityDelegate.registrarFor->(FlutterView.getPluginRegistry->FlutterNativeView.getPluginRegistry->返回值FlutterPluginRegistry)->FlutterPluginRegistry.registrarFor,最終返回值為FlutterPluginRegistry.FlutterRegistrar

好了,現在註冊器的來歷我們弄清楚了,那麼最開始的FlutterActivity的子類程式碼裡

methodChannel = MethodChannel(
    registrar.messenger(),
    channelName
)
複製程式碼

裡面的registrar.messenger()實際是什麼呢,因為FlutterActivity裡的registrarFor方法最終返回的是FlutterPluginRegistry.FlutterRegistrar,所以registrar.messenger()的返回值就是FlutterPluginRegistry.FlutterRegistrar類裡的messenger()方法的返回值,我們看一下FlutterPluginRegistry.FlutterRegistrar類裡的messenger()方法

public BinaryMessenger messenger() {
    return FlutterPluginRegistry.this.mNativeView;
}
複製程式碼

返回的是FlutterNativeView的例項,這個mNativeView是哪裡來的呢?

public FlutterPluginRegistry(FlutterNativeView nativeView, Context context) {
    this.mNativeView = nativeView;
    this.mAppContext = context;
    this.mPlatformViewsController = new PlatformViewsController();
}
複製程式碼

這個mNativeView例項就是FlutterNativeView建立FlutterPluginRegistry時將自己作為引數傳入並賦值的,而FlutterNativeView是在FlutterActivityDelegateonCreate方法裡,由FlutterActivityDelegate的屬性viewFactory呼叫createFlutterNativeView方法(viewFactory是FlutterActivity將自己作為引數傳入並賦值)建立並作為引數傳入FlutterView並賦值的,或者是由FlutterView自己建立的FlutterNative並賦值的(如果viewFactory.createFlutterNativeView返回值為null)

到這裡,我們也就知道了最開始建立通道時的引數registrar.messenger()到底是什麼了,實際就是FlutterNativeView,那麼我們將registrar.messenger()替換為getFlutterView()可以嗎,答案是可以的,因為FlutterView實現了介面BinaryMessenger並且BinaryMessenger的方法實現都委託給了mNativeView例項,所以最開始的程式碼也可以用如下方式實現

methodChannel = MethodChannel(
    flutterView,
    channelName
)
複製程式碼

或者

methodChannel = MethodChannel(
    flutterView.flutterNativeView,
    channelName
)
複製程式碼

但是用這種方式的話記得提前呼叫父類的registrarFor註冊方法將自己作為外掛註冊到系統


歡迎加入Flutter開發群457664582,點選加入,大家一起學習討論

Flutter開發

相關文章