Dagger2(二) Hilt注入技术实现隔离层架构

之所以把Hilt 归类到Dagger2 文章系列,原因是,Hilt 是专门为Android设计,设计团队专门找到Dagger2团队合作,为Android设计了这套注入框架Hilt。底层api其实还是高度还原Dagger语法。

1. Hilt 注入框架

1.1特点

Hilt就是Android团队联系了Dagger2团队,一起开发出来的一个专门面向Android的依赖注入框架。
相比于Dagger2,Hilt最明显的特征就是:1. 简单。2. 提供了Android专属的API。

Hilt做的优化包括

无需编写大量的Component代码
Scope也会与Component自动绑定
预定义绑定,例如 Application与Activity
预定义的限定符,例如@ApplicationContext与@ActivityContext

1.2基本配置

apply plugin: 'dagger.hilt.android.plugin'
//hilt
    implementation "com.google.dagger:hilt-android:2.28-alpha"
    annotationProcessor "com.google.dagger:hilt-android-compiler:2.28-alpha"
//kotlin
//katp "com.google.dagger:hilt-android-compiler:2.28-alpha"

------
//支持java8
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

------
Hilt 目前支持以下 Android 类:

Application
Activity
Fragment
View
Service
BroadcastReceiver

1.3基本使用

1.提供一个对象

public class HttpObject {
}

2.编写Module

@InstallIn(ActivityComponent.class)
@Module
public class HttpModule {
    @Provides
    public HttpObject getHttpObject(){
        return new HttpObject();
    }
}

3.注入到Activity

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    @Inject
    HttpObject httpObject;
    @Inject
    HttpObject httpObject2;

4.Application中注册

@HiltAndroidApp
public class MyApplication extends Application {
}

5.全局单例使用

@InstallIn(ApplicationComponent.class)
@Module
public class HttpModule {

    @Provides
    @Singleton
    public HttpObject getHttpObject(){
        return new HttpObject();
    }
}

注意:Hilt注入的字段是不可以声明成private

为接口注入实例

public interface AnalyticsService {
  void analyticsMethods();
}

-------
public class AnalyticsServiceImpl implements AnalyticsService {
  ...
  @Inject
  AnalyticsServiceImpl(...) {
    ...
  }
}
------
@Module
@InstallIn(ActivityComponent.class)
public abstract class AnalyticsModule {

  @Binds
  public abstract AnalyticsService bindAnalyticsService(
    AnalyticsServiceImpl analyticsServiceImpl
  );
}

1.4 Component与Scope

Hilt 提供了以下组件:

组件生命周期

 

同时还提供了相应的作用域 

1.5 注意事项

实现有使用gradle插件做字节码插桩

类似路径
windows

C:\Users\Administrator\.gradle\caches\modules-2\files-2.1\com.google.dagger\hilt-android-gradle-plugin\2.28-alpha\eb33a043b2bbdc7cdee3c851d0f8532bfd3645a5\hilt-android-gradle-plugin-2.28-alpha-sources\dagger\hilt\android\plugin

mac

/Users/zcw/.gradle/caches/modules-2/files-2.1/com.google.dagger/hilt-android-gradle-plugin/2.28.1-alpha/898bcdda64bf6f48581dbb24e555505bb66c1acf/hilt-android-gradle-plugin-2.28.1-alpha-sources.jar

2 网络请求隔离层应用

2.1设计具有网络访问能力的接口

package top.zcwfeng.httpprocessor_java_hilt;

public interface IHttpProcessor {
    // 网络访问能力
    void post(String url, Map<String,Object> params,ICallback callback);
    void get(String url, Map<String,Object> params,ICallback callback);
}

2.2顶层的回调接口

将来可能是,json,xml,Protobuf

package top.zcwfeng.httpprocessor_java_hilt;

public interface ICallback {
    void onSuccess(String result);
    void onFailure(String e);
}

2.3核心回调接口一种实现

将来可以用其他方式实现

/**
 * 回调接口的一种实现 new HttpCallback<JavaBean>
 */
public abstract class HttpCallback<Result> implements ICallback {

    @Override
    public void onSuccess(String result) {
        //result 就是网络访问第三方框架返回的字符串
//        1. 得到调用者用什么样的JavaBean接受数据
        Class<?> clz = analysisClassInfo(this);
//        2. 把result转换成对应的javabean
        Gson gson = new Gson();
        Result objResult = (Result) gson.fromJson(result, clz);
//        3.objResult 交给程序员使用
        onSuccess(objResult);
    }

    public abstract void onSuccess(Result objResult);

    private Class<?> analysisClassInfo(Object object){
        // getGenericSuperclass
        // 得到包含原始类型,参数化类型,数组,类型变量,进本数据类型
        Type type = object.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) type).getActualTypeArguments();
        return (Class<?>) params[0];
    }

    @Override
    public void onFailure(String e) {

    }
}

2.4 定义接口bean

public class ResponceData {
    /**
     * result : null
     * reason : 当前可请求的次数不足
     * error_code : 10012
     * resultcode : 112
     */
    private String result;
    private String reason;
    private int error_code;
    private String resultcode;

    public void setResult(String result) {
        this.result = result;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public void setError_code(int error_code) {
        this.error_code = error_code;
    }

    public void setResultcode(String resultcode) {
        this.resultcode = resultcode;
    }

    public String getResult() {
        return result;
    }

    public String getReason() {
        return reason;
    }

    public int getError_code() {
        return error_code;
    }

    public String getResultcode() {
        return resultcode;
    }
}

2.5三种请求实现

用我们之前的hilt注入基础,用@Inject 构造方法注入完成

OkHttpProcessor

package top.zcwfeng.httpprocessor_java_hilt;

import android.os.Handler;

import java.io.IOException;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public
class OkHttpProcessor implements IHttpProcessor {
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;

    @Inject
    public OkHttpProcessor() {
        mOkHttpClient = new OkHttpClient();
        mHandler = new Handler();
    }

    @Override
    public void post(String url, Map<String, Object> params, ICallback callback) {
        final RequestBody requestBody=appendBody(params);
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result=response.body().string();
                if(response.isSuccessful()){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(result);
                        }
                    });
                }else{
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(result);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure("onFailure");
                    }
                });
            }

        });
    }

    @Override
    public void get(String url, Map<String, Object> params, ICallback callback) {

    }
    private RequestBody appendBody(Map<String, Object> params){
        FormBody.Builder body=new FormBody.Builder();
        if(params==null || params.isEmpty()){
            return body.build();
        }
        for(Map.Entry<String, Object> entry:params.entrySet()){
            body.add(entry.getKey(),entry.getValue().toString());
        }
        return body.build();
    }
}

VolleyProcessor

package top.zcwfeng.httpprocessor_java_hilt;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.Map;

import javax.inject.Inject;

import dagger.hilt.android.qualifiers.ApplicationContext;

public
class VolleyProcessor implements IHttpProcessor {
    private static RequestQueue mQueue = null;

    @Inject
    public VolleyProcessor(@ApplicationContext Context context) {
        mQueue = Volley.newRequestQueue(context);
    }

    @Override
    public void post(String url, Map<String, Object> params, ICallback callback) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        callback.onSuccess(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mQueue.add(stringRequest);
    }

    @Override
    public void get(String url, Map<String, Object> params, ICallback callback) {

    }
}

XUtilsProcessor

package top.zcwfeng.httpprocessor_java_hilt;

import android.app.Application;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

import javax.inject.Inject;

public
class XUtilsProcessor implements IHttpProcessor {

    @Inject
    public XUtilsProcessor(Application app) {
        x.Ext.init((MyApplication)app);
    }

    @Override
    public void post(String url, Map<String, Object> params, ICallback callback) {

        RequestParams requestParams = new RequestParams(url);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                callback.onSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void get(String url, Map<String, Object> params, ICallback callback) {

    }
}

2.6 定义请求的Module,注入管理

package top.zcwfeng.httpprocessor_java_hilt;

import javax.inject.Singleton;

import dagger.Binds;
import dagger.Module;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import top.zcwfeng.httpprocessor_java_hilt.annotation.BindOkHttp;
import top.zcwfeng.httpprocessor_java_hilt.annotation.BindVolley;
import top.zcwfeng.httpprocessor_java_hilt.annotation.BindXUtils;

@Module
@InstallIn(ApplicationComponent.class)
public abstract class HttpProcessorModule {
    @BindOkHttp
    @Singleton
    @Binds
    abstract IHttpProcessor bindOKHttp(OkHttpProcessor okHttpProcessor);

    @BindVolley
    @Singleton
    @Binds
    abstract IHttpProcessor bindVolley(VolleyProcessor okHttpProcessor);

    @BindXUtils
    @Singleton
    @Binds
    abstract IHttpProcessor bindXUtils(XUtilsProcessor okHttpProcessor);
}

为了区分我们@Binds的注入,我们添加三个annotation

BindOkHttp,BindVolley,BindXUtils 实现相同名字不同

package top.zcwfeng.httpprocessor_java_hilt.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface BindOkHttp {
}

2.7 全局注入Application使用

package top.zcwfeng.httpprocessor_java_hilt;

import android.app.Application;

import javax.inject.Inject;

import dagger.hilt.android.HiltAndroidApp;
import top.zcwfeng.httpprocessor_java_hilt.annotation.BindOkHttp;

@HiltAndroidApp
public class MyApplication extends Application {

    @BindOkHttp
    @Inject
    IHttpProcessor iHttpProcessor;

    public IHttpProcessor getiHttpProcessor(){
        return iHttpProcessor;
    }
}

2.8 MainActivity 进行测试

package top.zcwfeng.httpprocessor_java_hilt;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.HashMap;

import dagger.hilt.android.AndroidEntryPoint;
import top.zcwfeng.httpprocessor_java_hilt.bean.ResponceData;
@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    //全局注入
    IHttpProcessor iHttpProcessor;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iHttpProcessor = ((MyApplication)getApplication()).getiHttpProcessor();
    }

    public void click(View view) {
        Log.e("zcwfeng", "11111111");

        String url="https://v.juhe.cn/historyWeather/citys";
        HashMap<String,Object> params=new HashMap<>();
        //https://v.juhe.cn/historyWeather/citys?&province_id=2&key=bb52107206585ab074f5e59a8c73875b
        params.put("province_id","2");
        params.put("key","bb52107206585ab074f5e59a8c73875b");
        iHttpProcessor.post(url, params, new HttpCallback<ResponceData>() {
            @Override
            public void onSuccess(ResponceData objResult) {
                Log.e("zcwfeng", "click(View view) ==== onSuccess");
                Toast.makeText(MainActivity.this, objResult.getResultcode(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 



作者:zcwfeng
链接:https://www.jianshu.com/p/9a7b476fe5b4
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值