1. 关于UETool
第一次见到UETool是在掘金上面,看到介绍的时候反正我是被惊到了,原来还可以这么玩!迫不及待下载下来源码,准备好好看一波。这个框架的代码不多,原理很简单通过一个透明的Activity在上面将获取的Activity控件的边界通过Canvas绘制到View上,但是我觉得写框架的同学对Android的源码理解很深,有许多坑都避免了,一起学习一波吧!
![img_2aaf454bfb70db2fe93d39ff9c9805ba.gif](https://yqfile.alicdn.com/img_2aaf454bfb70db2fe93d39ff9c9805ba.gif?x-oss-process=image/resize,w_1400/format,webp)
2. UETool程序入口
一般来说,拿到新的项目首先看工程目录,接着看各种Gradle文件,最后看运行Module的AndroidManifest文件,我们看下:
![img_21b20f6bca9625516707e67c8183e3cd.png](https://yqfile.alicdn.com/img_21b20f6bca9625516707e67c8183e3cd.png?x-oss-process=image/resize,w_1400/format,webp)
这里面的Application我们就不看了(没什么代码),还是先看下
MainActivity
吧:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 开关控件
final SwitchCompat control = findViewById(R.id.control);
control.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 显示menu
if (!UETool.showUETMenu()) {
control.setChecked(false);
}
} else {
UETool.dismissUETMenu();
}
}
});
control.setChecked(true);
// 更新布局显示gif SpanText 等
updateDraweeView();
updateSpanTextView();
updateCustomView();
}
很明显,最主要的就是显示Menu,通过Menu的代码可以知道,这是一个自定义的View,继承了LinearLayout。并且,其通过WindowManager添加到了Window上。这个先不用细看,看看其三个功能:
/**
* UETool.java
* @param y 显示位置
* @return 是否显示成功
*/
private boolean showMenu(int y) {
// Application.getApplicationContext() 通过反射获取ActivityThread的currentApplication对象 ① 反射
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(Application.getApplicationContext())) {
requestPermission(Application.getApplicationContext());
Toast.makeText(Application.getApplicationContext(), "After grant this permission, re-enable UETool", Toast.LENGTH_LONG).show();
return false;
}
}
if (uetMenu == null) {
uetMenu = new UETMenu(Application.getApplicationContext(), y);
}
uetMenu.show();
return true;
}
// UETMenu.java
public UETMenu(final Context context, int y) {
......
subMenus.add(new UETSubMenu.SubMenu(resources.getString(R.string.uet_catch_view), R.drawable.uet_edit_attr, new OnClickListener() {
@Override
public void onClick(View v) {
// 打开了一个透明的Activity
open(TransparentActivity.Type.TYPE_EDIT_ATTR);
}
}));
......
}
/**
* UETMenu.java打开一个透明的Activity
* @param type 类型
*/
private void open(@TransparentActivity.Type int type) {
// 通过反射,获取当前ActivityThread的mActivities保存的对象中显示的那个(即为topActivity)
Activity currentTopActivity = Util.getCurrentActivity();
if (currentTopActivity == null) {
return;
} else if (currentTopActivity.getClass() == TransparentActivity.class) {
currentTopActivity.finish();
return;
}
Intent intent = new Intent(currentTopActivity, TransparentActivity.class);
intent.putExtra(TransparentActivity.EXTRA_TYPE, type);
currentTopActivity.startActivity(intent);
currentTopActivity.overridePendingTransition(0, 0);
UETool.getInstance().setTargetActivity(currentTopActivity);
}
我们的菜单按钮,打开了一个透明的Activity,接下来的各种操作都是通过这个透明的Activity进行的(牛皮)!
3. TransparentActivity
从名字就可以知道,这是一个透明的Activity,其布局更加简答,只有一个id为container的FrameLayout
。
这里我们分析捕捉控件的原理吧:
@Override
protected void onCreate(Bundle savedInstanceState) {
......
vContainer = findViewById(R.id.container);
// 底部那一行字
final BoardTextView board = new BoardTextView(this);
type = getIntent().getIntExtra(EXTRA_TYPE, TYPE_UNKNOWN);
switch (type) {
case TYPE_EDIT_ATTR:
// 创建EditAttrLayout,并设置拖动监听
EditAttrLayout editAttrLayout = new EditAttrLayout(this);
editAttrLayout.setOnDragListener(new EditAttrLayout.OnDragListener() {
@Override
public void showOffset(String offsetContent) {
board.updateInfo(offsetContent);
}
});
vContainer.addView(editAttrLayout);
break;
......
}
}
看来所有的东西都在EditAttrLayout
里面,EditAttrLayout
是一个自定义View,继承自CollectViewsLayout
,看下主要代码:
private IMode mode = new ShowMode();
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (targetElement != null) {
canvas.drawRect(targetElement.getRect(), areaPaint);
mode.onDraw(canvas);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = event.getX();
lastY = event.getY();
break;
case MotionEvent.ACTION_UP:
mode.triggerActionUp(event);
break;
case MotionEvent.ACTION_MOVE:
mode.triggerActionMove(event);
break;
}
return true;
}
绘制和触摸事件都交给ShowMode
处理,我们先看看如何查找选中的是哪个View:
// 获取当前位置的Element
final Element element = getTargetElement(event.getX(), event.getY());
getTargetElement()
即便猜想也可以知道是通过View的位置以及点击的位置来获取Element
,但是这个Element
又是如何获得的?这里又通过反射来获取了:
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
try {
// 获取targetActivity
Activity targetActivity = UETool.getInstance().getTargetActivity();
// 获取其WindowManager
WindowManager windowManager = targetActivity.getWindowManager();
// WindowManagerImpl的mGlobal字段
Field mGlobalField = Class.forName("android.view.WindowManagerImpl").getDeclaredField("mGlobal");
mGlobalField.setAccessible(true);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { // 低版本处理
Field mViewsField = Class.forName("android.view.WindowManagerGlobal").getDeclaredField("mViews");
mViewsField.setAccessible(true);
List<View> views = (List<View>) mViewsField.get(mGlobalField.get(windowManager));
for (int i = views.size() - 1; i >= 0; i--) {
View targetView = getTargetDecorView(targetActivity, views.get(i));
if (targetView != null) {
traverse(targetView);
break;
}
}
} else {
Field mRootsField = Class.forName("android.view.WindowManagerGlobal").getDeclaredField("mRoots");
mRootsField.setAccessible(true);
List viewRootImpls;
// 这里没必要了肯定是true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
viewRootImpls = (List) mRootsField.get(mGlobalField.get(windowManager));
} else {
viewRootImpls = Arrays.asList((Object[]) mRootsField.get(mGlobalField.get(windowManager)));
}
for (int i = viewRootImpls.size() - 1; i >= 0; i--) {
Class clazz = Class.forName("android.view.ViewRootImpl");
Object object = viewRootImpls.get(i);
Field mWindowAttributesField = clazz.getDeclaredField("mWindowAttributes");
mWindowAttributesField.setAccessible(true);
Field mViewField = clazz.getDeclaredField("mView");
mViewField.setAccessible(true);
View decorView = (View) mViewField.get(object);
WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) mWindowAttributesField.get(object);
if (layoutParams.getTitle().toString().contains(targetActivity.getClass().getName())
|| getTargetDecorView(targetActivity, decorView) != null) {
traverse(decorView);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
本来我是不想放这么一大段代码,但是我觉得这个代码写的真好。通过反射获取了当前的DecorView。可不可以不适用反射直接通过Activity.getWindow().getDecorView()
这种方式获取DecorView?不行,普通的Activity获取DecorView没有问题,如果当前Activity上显示了Dialog,那么此时我们应该获取Dialog的DecorView,因此这里使用了反射去获取View(猜想)。
接着就需要去遍历DecorView,将其添加到Element中:
private void traverse(View view) {
if (UETool.getInstance().getFilterClasses().contains(view.getClass().getName())) return;
if (view.getAlpha() == 0 || view.getVisibility() != View.VISIBLE) return;
if (getResources().getString(R.string.uet_disable).equals(view.getTag())) return;
elements.add(new Element(view));
if (view instanceof ViewGroup) {
ViewGroup parent = (ViewGroup) view;
for (int i = 0; i < parent.getChildCount(); i++) {
traverse(parent.getChildAt(i));
}
}
}
OK,Element已经获取,并且当前点击的Element已经获取到,我们看下如何显示距离的:
@Override
public void triggerActionUp(final MotionEvent event) {
// 抬起触发,获取当前位置的Element
final Element element = getTargetElement(event.getX(), event.getY());
if (element != null) {
targetElement = element;
// 重绘
invalidate();
......
}
}
@Override
public void onDraw(Canvas canvas) {
/**
* 绘制,targetElement如何获取
*/
Rect rect = targetElement.getRect();
// 绘制线以及文字
drawLineWithText(canvas, rect.left, rect.top - lineBorderDistance, rect.right, rect.top - lineBorderDistance);
drawLineWithText(canvas, rect.right + lineBorderDistance, rect.top, rect.right + lineBorderDistance, rect.bottom);
}
通过获取到的Element,我们可以获得View的位置并且通过Canvas将线条和文字绘制到View上。(属性显示的dialog这里割掉了)
4. 总结
关于原理,这东西我觉得看看源码基本上都可以理解。为啥还要写这篇呢?我觉得有几个地方确实惊艳到我了:
- 通过反射获取Context
- 通过反射获取DecorView
- 通过反射获取TopActivity
虽然代码不多,但是用到了很多源码知识。想必这就是书读百遍,其义自见吧!