美文网首页
优雅的提高onActivityResult代码可读性

优雅的提高onActivityResult代码可读性

作者: 代码改变人生 | 来源:发表于2018-10-31 21:01 被阅读0次

    onActivityResult简单使用

    正常情况下启动Activity和接收回调信息的方式:

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 启动Activity
            startActivityForResult(new Intent(this, AActivity.class), 1);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 1) {
                // 处理回调信息
            }
        }
    

    正常情况下,我们都会这样写,但会有两个问题:

    1.onActivityResult必须在原始Activity中才能接收,如果想在非Activity中调用startActivityForResult,那么调用和接收的地方就不在同一个地方,代码可读性较差。
    2.onActivityResult中所有页面跳转回调结果处理都会在该方法中,需要通过对resultCode进行if...else...判断才能区分,如果跳转比较多的话,代码可读性较差。

    我们在写点击事件的时候,都知道其通过回调的方式接收点击回调信息?那么能不能将onActivityResult封装成,在哪调用的跳转,就在哪接收回调呢?答案是肯定的,类似于下面这样:

    startActivityForResult(TestActivity.class, new Callback() {
        @Override
        public void onActivityResult(int resultCode, Intent data) {
            // 处理回调信息
        }
    });
    

    一种简单稳定的方法来实现onActivityResult的自动调用:

    相信大家对Fragment都很熟悉,其依赖于Activity,有着一样的生命周期,却比Activity更轻量级。我们可以利用一个空的无界面的Fragment来监听onActivityResult方法,并通过回调形式返回给调用者。由于Fragment的onActivityResult是系统自动调用的,所以可以简单轻松的告别onActivityResult了,而且这个方法是系统自带的,稳定性得到保障。

    /**
     * 把OnActivityResult方式转换为Callback方式的空Fragment(V4兼容包)
     *
     */
    public class RouterFragment extends Fragment {
    
        private SparseArray<ActivityLauncher.Callback> mCallbacks = new SparseArray<>();
        private Random mCodeGenerator = new Random();
    
        public RouterFragment() {
            // Required empty public constructor
        }
    
        public static RouterFragment newInstance() {
            return new RouterFragment();
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }
    
        public void startActivityForResult(Intent intent, ActivityLauncher.Callback callback) {
            int requestCode = makeRequestCode();
            mCallbacks.put(requestCode, callback);
            startActivityForResult(intent, requestCode);
        }
    
        /**
         * 随机生成唯一的requestCode
         *
         * @return
         */
        private int makeRequestCode() {
            int requestCode;
            int tryCount = 0;
            do {
                requestCode = mCodeGenerator.nextInt(0x0000FFFF);
                tryCount++;
            } while (mCallbacks.indexOfKey(requestCode) >= 0 && tryCount < 10);
            return requestCode;
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            ActivityLauncher.Callback callback = mCallbacks.get(requestCode);
            mCallbacks.remove(requestCode);
            if (callback != null) {
                callback.onActivityResult(resultCode, data);
            }
        }
    }
    
    /**
     * Activity跳转封装类,把OnActivityResult方式改为Callback方式
     *
     */
    public class ActivityLauncher {
    
        private static final String TAG = "ActivityLauncher";
        private Context mContext;
        /** V4兼容包下的Fragment */
        private RouterFragment mRouterFragment;
    
        public static ActivityLauncher init(Fragment fragment) {
            return init(fragment.getActivity());
        }
    
        public static ActivityLauncher init(FragmentActivity activity) {
            return new ActivityLauncher(activity);
        }
    
        public static ActivityLauncher init(Activity activity) {
            return new ActivityLauncher(activity);
        }
    
        private ActivityLauncher(FragmentActivity activity) {
            mContext = activity;
            mRouterFragment = getRouterFragment(activity);
        }
    
        private ActivityLauncher(Activity activity) {
            mContext = activity;
            mRouterFragment = getRouterFragment(activity);
        }
    
        private RouterFragment getRouterFragment(FragmentActivity activity) {
            RouterFragment routerFragment = findRouterFragment(activity);
            if (routerFragment == null) {
                routerFragment = RouterFragment.newInstance();
                FragmentManager fragmentManager = activity.getSupportFragmentManager();
                fragmentManager
                        .beginTransaction()
                        .add(routerFragment, TAG)
                        .commitAllowingStateLoss();
                fragmentManager.executePendingTransactions();
            }
            return routerFragment;
        }
    
        private RouterFragment findRouterFragment(FragmentActivity activity) {
            return (RouterFragment) activity.getSupportFragmentManager().findFragmentByTag(TAG);
        }
    
        public void startActivityForResult(Class<?> clazz, Callback callback) {
            Intent intent = new Intent(mContext, clazz);
            startActivityForResult(intent, callback);
        }
    
        public void startActivityForResult(Intent intent, Callback callback) {
            if (mRouterFragment != null) {
                mRouterFragment.startActivityForResult(intent, callback);
            } else {
                throw new RuntimeException("please do init first!");
            }
        }
    
        public interface Callback {
            void onActivityResult(int resultCode, Intent data);
        }
    }
    

    使用方式如下:

            // 启动Activity
            ActivityLauncher.init(this)
                    .startActivityForResult(TestActivity.class, new ActivityLauncher.Callback() {
                        @Override
                        public void onActivityResult(int resultCode, Intent data) {
                            // 处理回调信息
                        }
                    });
    

    相关文章

      网友评论

          本文标题:优雅的提高onActivityResult代码可读性

          本文链接:https://www.haomeiwen.com/subject/voomtqtx.html