一款基于AOP的Android注解框架

一、簡(jiǎn)介

當(dāng)下Java后端的SpringBoot微服務(wù)框架大火,原因離不開注解的使用,其簡(jiǎn)單易配置的注解方式使得更多的社區(qū)為其編寫適用于SpringBoot的框架,也就是注解逐漸取代了傳統(tǒng)的xml配置方式。那么注解在Android中也同樣的得到了升華,著名的框架有ButterKnife、 Dagger2、Retrofit等等。今天帶來一款A(yù)ndroid中比較實(shí)用的注解框架AopArms,其用法簡(jiǎn)單,里面編寫了Android開發(fā)中常用的一套注解,如日志、攔截(登錄)、異步處理、緩存、SP、延遲操作、定時(shí)任務(wù)、重試機(jī)制、try-catch安全機(jī)制、過濾頻繁點(diǎn)擊等,后續(xù)還會(huì)有更多更強(qiáng)大的注解功能加入。
本篇主要內(nèi)容講解在Android中的基本用法,關(guān)于AOP在Android中的實(shí)踐請(qǐng)參考另外一篇Android開發(fā)之AOP編程。

二、引入方式

1、在主工程中添加依賴

//引入aspectjx插件
apply plugin: 'android-aspectjx'

dependencies {
    ...
    implementation 'cn.com.superLei:aop-arms:1.0.1'
}

2、項(xiàng)目跟目錄的gradle腳本中加入

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        //該庫基于滬江aspect插件庫
        classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4'
    }
}

3、在Application中初始化

AopArms.init(this);

三、基本使用

1、緩存篇(可緩存任意類型)

1、插入緩存
    @Cache(key = "userList")
    private ArrayList<User> initData() {
        ArrayList<User> list = new ArrayList<>();
        for (int i=0; i<5; i++){
            User user = new User();
            user.setName("艾神一不小心:"+i);
            user.setPassword("密碼:"+i);
            list.add(user);
        }
        return list;
    }
    
2、獲取緩存
    private ArrayList<User> getUser() {
        return ACache.get(this).getAsList("userList", User.class);
    }

3、移除緩存
    @CacheEvict(key = "userList")
    public void removeUser() {
        Log.e(TAG, "removeUser: >>>>");
    }
    
image

2、SharedPreferences篇(可保存對(duì)象)

1、保存key到sp
    @Prefs(key = "article")
    private Article initArticle() {
        Article article = new Article();
        article.author = "jerry";
        article.title = "hello android";
        article.createDate = "2019-05-31";
        article.content = "this is a test demo";
        return article;
    }
    
2、從sp中移除key
    @PrefsEvict(key = "article")
    public void removeArticle() {
        Log.e(TAG, "removeArticle: >>>>");
    }

3、異步篇

    @Async
    public void asyn() {
        Log.e(TAG, "useAync: "+Thread.currentThread().getName());
    }

4、try-catch安全機(jī)制篇

    //自動(dòng)幫你try-catch   允許你定義回調(diào)方法
    @Safe(callBack = "throwMethod")
    public void safe() {
        String str = null;
        str.toString();
    }
    
    //自定義回調(diào)方法(注意要和callBack的值保持一致)
    private void throwMethod(Throwable throwable){
        Log.e(TAG, "throwMethod: >>>>>"+throwable.toString());
    }

5、重試機(jī)制篇

     /**
     * @param count 重試次數(shù)
     * @param delay 每次重試的間隔
     * @param asyn 是否異步執(zhí)行
     * @param retryCallback 自定義重試結(jié)果回調(diào)
     * @return 當(dāng)前方法是否執(zhí)行成功
     */
    @Retry(count = 3, delay = 1000, asyn = true, retryCallback = "retryCallback")
    public boolean retry() {
        Log.e(TAG, "retryDo: >>>>>>"+Thread.currentThread().getName());
        return false;
    }
    
    private void retryCallback(boolean result){
        Log.e(TAG, "retryCallback: >>>>"+result);
    }
image

6、定時(shí)任務(wù)篇

     /**
     * @param interval 初始化延遲
     * @param interval 時(shí)間間隔
     * @param timeUnit 時(shí)間單位
     * @param count 執(zhí)行次數(shù)
     * @param taskExpiredCallback 定時(shí)任務(wù)到期回調(diào)
     */
    @Scheduled(interval = 1000L, count = 10, taskExpiredCallback = "taskExpiredCallback")
    public void scheduled() {
        Log.e(TAG, "scheduled: >>>>");
    }
    
    private void taskExpiredCallback(){
        Log.e(TAG, "taskExpiredCallback: >>>>");
    }
image

7、延遲任務(wù)篇

    //開啟延遲任務(wù)(10s后執(zhí)行該方法)
    @Delay(key = "test", delay = 10000L)
    public void delay() {
        Log.e(TAG, "delay: >>>>>");
    }
    
    //移除延遲任務(wù)
    @DelayAway(key = "test")
    public void cancelDelay() {
        Log.e(TAG, "cancelDelay: >>>>");
    }

8、過濾頻繁點(diǎn)擊

    //value默認(rèn)500ms
    @SingleClick(value = 2000L)
    private void onclick(){
        Log.e(TAG, "onclick: >>>>");
    }

9、攔截篇(如登錄)

1、在需要進(jìn)行攔截的方法添加注解
    @Intercept("login_intercept")
    public void loginIntercept() {
        Log.e(TAG, "intercept: 已登陸>>>>");
    }
2、(建議,統(tǒng)一處理)在Application中進(jìn)行進(jìn)行監(jiān)聽攔截回調(diào)
public class MyApplication extends Application {

    private static final String TAG = "MyApplication";
    private static MyApplication mApplication;
    
    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        AopArms.init(this);
        AopArms.setInterceptor(new Interceptor() {
            @Override
            public boolean intercept(String key, String methodName) throws Throwable {
                Log.e(TAG, "intercept methodName:>>>>>"+methodName);
                if ("login_intercept".equals(key)){
                    String userId = SPUtils.get(mApplication, "userId", "");
                    if (TextUtils.isEmpty(userId)){
                        Toast.makeText(mApplication, "您還沒有登錄", Toast.LENGTH_SHORT).show();
                        return true;//代表攔截
                    }
                }
                return false;//放行
            }
        });
    }
}

以上是庫的一些常用的基本用法,后續(xù)會(huì)添加更多的注解來簡(jiǎn)化Android開發(fā),歡迎前來issues來提問或者提出你認(rèn)為所需要的更多注解需求。

GitHub地址:AopArms

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容