Flutter Plugin中监听Activity生命周期

2022-03-23  本文已影响0人  倪大头

最近接了个三方支付功能,接口方没有提供支付回调,需要在onResume里获取intent里的值,所以我需要在plugin里监听activity的生命周期。

registerWith注册通道的方式已经淘汰,我们使用onAttachedToEngine注册通道,并把监听写在这里:

@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
    methodChannel = new MethodChannel(binding.getBinaryMessenger(), "xxx_plugin");
    methodChannel.setMethodCallHandler(this);

    ((Application) binding.getApplicationContext()).registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {
            Log.i(TAG, "----onActivityResumed-----");
        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity act) {
            if (act == activity) {
                ((Application) binding.getApplicationContext()).unregisterActivityLifecycleCallbacks(this);
            }
        }
   });
}

FlutterPluginBinding提供的getApplicationContext()方法可以获取Application,再使用registerActivityLifecycleCallbacks注册生命周期监听即可。

如果你的插件包没有升级到V2,仍然使用registerWith注册通道的话,可以用registrar.context()注册生命周期监听:

((Application) registrar.context()).registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
  ......
}
上一篇下一篇

猜你喜欢

热点阅读