为什么要使用support包

2018/06/02

为什么要使用support包?

在回答这个问题之前我们先看看一般可能的想法。

使用support包的开发者:

  • support包支持更多机型,兼容更多Android版本,最低支持到1.6(minSdkVersion="4"),而app包仅支持3.0(minSdkVersion="11")以上的版本。
  • support包下有google封装的一些比较炫酷的东西,比如AppCompatActivity

使用app包的开发者:

  • app包更纯粹,没有太多的封装和依赖,需要的东西我们可以自己封装,这样可以一定程度减少apk体积。
  • 别说兼容了,现在几年前安卓4.4系统以下的手机差不多都灭绝了,满大街跑的5.0系统以上的手机,7.0都开始逐渐流行,太低版本系统的手机不想支持,该抛弃了。

在以前,这在我看来用哪个都没有对错优劣之分,完全看开发者的喜好和项目需要选择。以前我更是app包使用偏好的开发者。

而现在,我已经转投support包了。为什么?

答:support包里的东西做了一些相当有用的封装。

Naive you.这谁不懂!你倒是说说哪里有必要啊。

慢,要真这么泛泛一句话的答案我也不会写这个东西了。仅凭这句话你肯定不知道我要说什么东西,也基本get不到什么点。

很多开发者项目都会封装BaseActivityBaseFragment,相信多多少少会碰到继承的问题:使用第三方开源框架,碰到都需要继承他们框架Actvity的场景。这样就麻烦了,Java单继承的特性注定我们只能继承一个。有了这个经验,我们在封装的时候会尽可能的少用继承,而用多组件实现的形式,比如接口。这里具体怎么弃用继承而用接口实现的方式将不会展开。

我的项目原来BaseActivity,BaseFragment中的封装已经放到别处去统一实现,原有的BaseActivity,BaseFragment要彻底删除,但BaseActivity,BaseFragment继承了 RxLifecycle 框架(处理RxJava内存泄漏问题的多少会知道这个框架)里面的RxActivity,RxFragment,我需要保留RxLifecycle的功能怎么办?我找到了RxLifecycle框架作者Daniel Lew 推荐使用的替代框架AutoDispose (为什么推荐Daniel Lew写了一篇文章Why Not RxLifecycle?  ,其中提到RxLifecycle的一点局限性就有继承问题)。

使用AutoDispose监听ActivityFragment生命周期需要LifecycleOwner ,这个东西是去年Google IO大会上Google官方向我们推出 Android Architecture ComponentsLifecycle 里面的东西,Release版已正式植入support包,包括SupportActivityAppCompatActivity的基类)、Fragment,而app包没有,对比一下:

Activity:

package android.support.v4.app;

...

public class SupportActivity extends Activity implements LifecycleOwner {
    ...
}

android.support.v4.app.Fragment

package android.support.v4.app;

...

/**
 * Static library support version of the framework's {@link android.app.Fragment}.
 * Used to write apps that run on platforms prior to Android 3.0.  When running
 * on Android 3.0 or above, this implementation is still used; it does not try
 * to switch to the framework's implementation. See the framework {@link android.app.Fragment}
 * documentation for a class overview.
 *
 * <p>The main differences when using this support version instead of the framework version are:
 * <ul>
 *  <li>Your activity must extend {@link FragmentActivity}
 *  <li>You must call {@link FragmentActivity#getSupportFragmentManager} to get the
 *  {@link FragmentManager}
 * </ul>
 *
 */
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner {
    ...
}

android.app.Fragment

package android.app;

...

public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
    ...
}

看样子,不只是Lifecycle,后续的官方新特性或优化应该会优先加入到support中。

因而,应优先考虑使用support包。

Post Directory