一款基于AOP的Android注解框架

一、簡介

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

二、引入方式

1、在主工程中添加依賴

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

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

2、項目跟目錄的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篇(可保存對象)

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安全機制篇

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

5、重試機制篇

     /**
     * @param count 重試次數
     * @param delay 每次重試的間隔
     * @param asyn 是否異步執行
     * @param retryCallback 自定義重試結果回調
     * @return 當前方法是否執行成功
     */
    @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、定時任務篇

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

7、延遲任務篇

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

8、過濾頻繁點擊

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

9、攔截篇(如登錄)

1、在需要進行攔截的方法添加注解
    @Intercept("login_intercept")
    public void loginIntercept() {
        Log.e(TAG, "intercept: 已登陸>>>>");
    }
2、(建議,統一處理)在Application中進行進行監聽攔截回調
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;//放行
            }
        });
    }
}

以上是庫的一些常用的基本用法,后續會添加更多的注解來簡化Android開發,歡迎前來issues來提問或者提出你認為所需要的更多注解需求。

GitHub地址:AopArms

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容