美文网首页
Android之AOP架构<第三篇>:网络判断

Android之AOP架构<第三篇>:网络判断

作者: NoBugException | 来源:发表于2020-05-27 07:24 被阅读0次

    直接贴代码

    [第一步] 网络判断切面

    /**
     * 网络判断切面
     */
    @Aspect
    public class CheckNetAspect {
    
    
        @Pointcut("execution(* com.example.aopdemo.MainActivity.test(..))")
        public void checkNetBehavior() {
    
        }
    
        @Around("checkNetBehavior()")
        public Object checkNet(ProceedingJoinPoint joinPoint) throws Throwable {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            CheckNet annotation = signature.getMethod().getAnnotation(CheckNet.class);
            if (annotation != null) {
                Object object = joinPoint.getThis();
                Context context = getContext(object);
                if (context != null) {
                    if (!isNetworkAvailable(context)) {
                        Toast.makeText(context,"请检查您的网络",Toast.LENGTH_LONG).show();
                        return null;
                    }
                }
            }
            return joinPoint.proceed();
        }
    
        /**
         * 通过对象获取上下文
         *
         * @param object
         * @return
         */
        private Context getContext(Object object) {
            if (object instanceof Activity) {
                return (Activity) object;
            } else if (object instanceof Fragment) {
                Fragment fragment = (Fragment) object;
                return fragment.getActivity();
            } else if (object instanceof View) {
                View view = (View) object;
                return view.getContext();
            }
            return null;
        }
    
        /**
         * 检查当前网络是否可用
         *
         * @return
         */
        private static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
    
                if (networkInfo != null && networkInfo.length > 0) {
                    for (int i = 0; i < networkInfo.length; i++) {
                        if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    
    }
    

    在名字叫CheckNet的注解上埋下切点。

    [自定义注解]

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface CheckNet {
    }
    

    [注解的使用]

    @CheckNet
    private void test(){
        Log.i("yunchong", "开始进行网络判断!");
    }
    

    [本章完...]

    相关文章

      网友评论

          本文标题:Android之AOP架构<第三篇>:网络判断

          本文链接:https://www.haomeiwen.com/subject/agjiahtx.html