博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android AOP网络检查
阅读量:601 次
发布时间:2019-03-12

本文共 3003 字,大约阅读时间需要 10 分钟。

文章目录

Android AOP网络检查

在这里插入图片描述

在这里插入图片描述

功能实现

定义注解

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface CheckNet {
int SHOW_TIP = 1; int SHOW_DIALOG = 2; int value() default SHOW_TIP;}

定义切面类

@Aspectpublic class CheckNetAspect {
@Pointcut("execution(@com.example.mylibrary.network.CheckNet * *(..))") public void method() {
} @Around("method()") public void handleCheckNet(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); CheckNet checkNet = methodSignature.getMethod().getAnnotation(CheckNet.class); if (checkNet != null) {
Object aThis = joinPoint.getThis(); Context context = getContext(aThis); if (context != null && !isNetworkAvailable(context)) {
if (checkNet.value() == CheckNet.SHOW_TIP) {
showTip(context); } else if (checkNet.value() == CheckNet.SHOW_DIALOG) {
showSettingDialog(context); } return; } } joinPoint.proceed(); } /** * 显示提示 */ private void showTip(Context context) {
Toast.makeText(context, "当前没有网络连接,请检查网络设置", Toast.LENGTH_SHORT).show(); } /** * 显示弹窗 */ private void showSettingDialog(Context context) {
new AlertDialog.Builder(context) .setMessage("当前没有网络连接,请检查网络设置") .setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } }) .show(); } /** * 判断网络是否能用 */ private boolean isNetworkAvailable(Context context) {
ConnectivityManager manager = ContextCompat.getSystemService(context, ConnectivityManager.class); if (manager != null) {
NetworkInfo info = manager.getActiveNetworkInfo(); // 判断网络是否连接 if (info == null || !info.isConnected()) {
return false; } } return true; } /** * 获取Context对象 */ 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; }}

使用

@CheckNet()private void getUserInfo() {
Log.e(TAG, "获取用户信息");}@CheckNet(CheckNet.SHOW_DIALOG)private void getUserInfo2() {
Log.e(TAG, "获取用户信息2");}

转载地址:http://geqxz.baihongyu.com/

你可能感兴趣的文章