Android第三方庫解析
前言
很多人面試之前,可能沒有在互聯網公司工作過或者說工作過但年頭較短,不知道互聯網公司技術面試都會問哪些問題? 再加上可能自己準備也不充分,去面試沒幾個回合就被面試官幾個問題打蒙了,最后以慘敗收場。
1.Retrofit網絡請求框架
概念:Retrofit是一個基于RESTful的HTTP網絡請求框架的封裝,其中網絡請求的本質是由OKHttp完成的,而Retrofit僅僅負責網絡請求接口的封裝。
原理:App應用程序通過Retrofit請求網絡,實際上是使用Retrofit接口層封裝請求參數,Header、URL等信息,之后由OKHttp完成后續的請求,在服務器返回數據之后,OKHttp將原始的結果交給Retrofit,最后根據用戶的需求對結果進行解析。
retrofit使用
1.在retrofit中通過一個接口作為http請求的api接口
public interface NetApi { @GET("repos/{owner}/{repo}/contributors") Call contributorsBySimpleGetCall(@Path("owner") String owner, @Path("repo") String repo);}
2.創建一個Retrofit實例
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();
3.調用api接口
- NetApi repo = retrofit.create(NetApi.class);
- //第三步:調用網絡請求的接口獲取網絡請求
- retrofit2.Call<ResponseBody> call = repo.contributorsBySimpleGetCall("username", "path");
- call.enqueue(new Callback<ResponseBody>() { //進行異步請求
- @Override
- public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
- //進行異步操作
- }
- @Override
- public void onFailure(Call<ResponseBody> call, Throwable t) {
- //執行錯誤回調方法
- }
- });
retrofit動態代理
retrofit執行的原理如下:
- 首先,通過method把它轉換成ServiceMethod。
- 然后,通過serviceMethod,args獲取到okHttpCall對象。
- 最后,再把okHttpCall進一步封裝并返回Call對象。 首先,創建retrofit對象的方法如下:
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .build();
在創建retrofit對象的時候用到了build()方法,該方法的實現如下:
- public Retrofit build() {
- if (baseUrl == null) {
- throw new IllegalStateException("Base URL required.");
- }
- okhttp3.Call.Factory callFactory = this.callFactory;
- if (callFactory == null) {
- callFactory = new OkHttpClient(); //設置kHttpClient
- }
- Executor callbackExecutor = this.callbackExecutor;
- if (callbackExecutor == null) {
- callbackExecutor = platform.defaultCallbackExecutor(); //設置默認回調執行器
- }
- // Make a defensive copy of the adapters and add the default Call adapter.
- List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
- adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
- // Make a defensive copy of the converters.
- List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
- return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
- callbackExecutor, validateEagerly); //返回新建的Retrofit對象
- }
該方法返回了一個Retrofit對象,通過retrofit對象創建網絡請求的接口的方式如下:
- NetApi repo = retrofit.create(NetApi.class);
retrofit對象的create()方法的實現如下:
- public <T> T create(final Class<T> service) {
- Utils.validateServiceInterface(service);
- if (validateEagerly) {
- eagerlyValidateMethods(service);
- }
- return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
- new InvocationHandler() {
- private final Platform platform = Platform.get();
- @Override public Object invoke(Object proxy, Method method, Object... args)
- throws Throwable {
- // If the method is a method from Object then defer to normal invocation.
- if (method.getDeclaringClass() == Object.class) {
- return method.invoke(this, args); //直接調用該方法
- }
- if (platform.isDefaultMethod(method)) {
- return platform.invokeDefaultMethod(method, service, proxy, args); //通過平臺對象調用該方法
- }
- ServiceMethod serviceMethod = loadServiceMethod(method); //獲取ServiceMethod對象
- OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args); //傳入參數生成okHttpCall對象
- return serviceMethod.callAdapter.adapt(okHttpCall); //執行okHttpCall
- }
- });
- }
2.圖片加載庫對比
- Picasso:120K
- Glide:475K
- Fresco:3.4M
Android-Universal-Image-Loader:162K
圖片函數庫的選擇需要根據APP的具體情況而定,對于嚴重依賴圖片緩存的APP,例如壁紙類,圖片社交類APP來說,可以選擇最專業的Fresco。對于一般的APP,選擇Fresco會顯得比較重,畢竟Fresco3.4M的體量擺在這。根據APP對圖片的顯示和緩存的需求從低到高,我們可以對以上函數庫做一個排序。
Picasso < Android-Universal-Image-Loader < Glide < Fresco
介紹:
Picasso :和Square的網絡庫一起能發揮最大作用,因為Picasso可以選擇將網絡請求的緩存部分交給了okhttp實現。
Glide:模仿了Picasso的API,而且在他的基礎上加了很多的擴展(比如gif等支持),Glide默認的Bitmap格式是RGB_565,比 Picasso默認的ARGB_8888格式的內存開銷要小一半;Picasso緩存的是全尺寸的(只緩存一種),而Glide緩存的是跟ImageView尺寸相同的(即5656和128128是兩個緩存) 。
FB的圖片加載框架Fresco:最大的優勢在于5.0以下(最低2.3)的bitmap加載。在5.0以下系統,Fresco將圖片放到一個特別的內存區域(Ashmem區)。當然,在圖片不顯示的時候,占用的內存會自動被釋放。這會使得APP更加流暢,減少因圖片內存占用而引發的OOM。為什么說是5.0以下,因為在5.0以后系統默認就是存儲在Ashmem區了。
總結:
Picasso所能實現的功能,Glide都能做,無非是所需的設置不同。但是Picasso體積比起Glide小太多如果項目中網絡請求本身用的就是okhttp或者retrofit(本質還是okhttp),那么建議用Picasso,體積會小很多(Square全家桶的干活)。Glide的好處是大型的圖片流,比如gif、Video,如果你們是做美拍、愛拍這種視頻類應用,建議使用。
Fresco在5.0以下的內存優化非常好,代價就是體積也非常的大,按體積算Fresco>Glide>Picasso
不過在使用起來也有些不便(小建議:他只能用內置的一個ImageView來實現這些功能,用起來比較麻煩,我們通常是根據Fresco自己改改,直接使用他的Bitmap層)
3.各種json解析庫使用
(1)Google的Gson
Gson是目前功能最全的Json解析神器,Gson當初是為因應Google公司內部需求而由Google自行研發而來,但自從在2008年五月公開發布第一版后已被許多公司或用戶應用。Gson的應用主要為toJson與fromJson兩個轉換函數,無依賴,不需要例外額外的jar,能夠直接跑在JDK上。而在使用這種對象轉換之前需先創建好對象的類型以及其成員才能成功的將JSON字符串成功轉換成相對應的對象。類里面只要有get和set方法,Gson完全可以將復雜類型的json到bean或bean到json的轉換,是JSON解析的神器。Gson在功能上面無可挑剔,但是性能上面比FastJson有所差距。
(2)阿里巴巴的FastJson
Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發。
無依賴,不需要例外額外的jar,能夠直接跑在JDK上。FastJson在復雜類型的Bean轉換Json上會出現一些問題,可能會出現引用的類型,導致Json轉換出錯,需要制定引用。FastJson采用獨創的算法,將parse的速度提升到極致,超過所有json庫。
綜上Json技術的比較,在項目選型的時候可以使用Google的Gson和阿里巴巴的FastJson兩種并行使用,如果只是功能要求,沒有性能要求,可以使用google的Gson,如果有性能上面的要求可以使用Gson將bean轉換json確保數據的正確,使用FastJson將Json轉換Bean