Android Studio 提高代码质量——Inspact Code


原文链接:http://www.jianshu.com/p/ddd23bb06a67

原文作者:李艳超_Harry 

Android Studio 提高代码质量——Inspact Code

前言

什么是静态代码检测?
静态代码检测是不运行代码的前提下,利用预先设定好的规则对程序进行分析,发现潜在问题。检测工具价值度主要体现在检测规则的数量和检测精确度两个方面。编译器进行编译的过程中会检测程序中的"硬伤",给出错误和警告,静态代码检测工作原理和编译器相似,规则更严苛。
静态代码分析可以在开发过程中尽早的帮助团队发现潜在的问题和风险,提高代码质量。关于java的静态检测工具可以参考下面链接:
https://www.ibm.com/developerworks/cn/java/j-lo-statictest-tools/
Android Studio逐渐替代Eclipse 成为Android开发首选IDE,一起来挖掘下Studio中静态检测的使用。


1. 前身:Eclipse ADT 工具Lint

功能入口:
右键Android项目--Android Tools--Run Lint:Check for Common Error
unused 资源:

The resource R.string.ok appears to be unused
The resource R.drawable.goback appears to be unused

布局问题:

Avoid using "px" as units; use "dp" instead
This RelativeLayout layout or its LinearLayout parent is useless

2. Android Studio中的Analyze

功能入口:
a.导航栏--Analyze--Inspact Code
b.项目顶层目录--右键--Analyze--Inspact Code
Inspact Code 结果展示(啊啊!这么多问题啊,大部分是真实存在的问题)


结果展示

2.1 问题分类

在官方文档没有找到对应的文档介绍,有找到的同学可以告诉我一下。
再上图中点击左侧工具栏中的“设置”图标,检测规则好多啊,分类就这么一大排。


可检测规则列表

2.2 Android


andoid分类下的规则


举例:

Missing JNI function
在java代码中定义了native方法,但是没有找到对应的native实现

2.3 Android Lint


Lint 分类下的规则


这个部分很多规则是从历史版本继承来的
举例:

Handler reference leaks

Handler作为内部类时,会持有外部类的引用,可能会出现内存泄露的风险
Handler reference leaks Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.


SD卡路径硬编码

使用了SD卡路径硬编码

private static final String AUDIO_FILE = "/sdcard/harry/reult/audio.txt";

修改建议是

Environment.getExternalStorageDirectory().getPath()

Unused resources——没有使用的资源

开发过程中有资源没有使用,白白的浪费资源,使Apk包变大,程序构建变慢。现在Android 开发大家不太在意这些问题,早在几年前Java ME的时代,整个安装包只有几百K,产品上线前此项检测很严格。

The resource R.drawable.button_bg appears to be unused

Using dp instead of sp for text sizes——字体大小使用sp

当然硬要使用sp也没什么的只要UI在各个分辨率上展示ok就行。

PerFomance issues

代码中有些无用的语句,浪费性能。
比如我的代码里写了如下代码:其中getName()方法的返回值已经是String类型了。

temp.getName().toString()

Use of 'java.lang.reflect'
使用java反射机制,被认为是不安全的、低效的。
Object allocation in loop
在循环体内new 对象可能会造成内存泄露和性能问题。

总结

Android Studio中的静态代码检测面很广,规则很丰富。一起慢慢挖掘使用吧。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值