android-tips-tricks-cn
一些很不错的Android开发技巧,这个项目翻译自 android-tips-tricks 去掉了一些我认为不重要的,对我使用过的东东做了评价,同时翻译了一些自己没有注意到的知识点的文章。
:heart: star 支持一下

欢迎协作
了解你的工具
Android Studio
-
使用快捷键
完整的快捷键指南 : MacOSX | Linux/Win
-
使用更有效率的插件
- KeyPromoter
快捷键提示插件 – 试用了一下,就是你点击的时候有些按钮会出来提示框告诉你这个的快捷键是什么以及你使用的次数,还不错,目的就是让你进行键盘流操作。
- String Manipulation
提供 Action 转换大小写什么的,感觉想不起来用。
- Lines Sorter
Add Sort Lines action in Edit menu to sort selected lines or whole file if selection is empty.
- Findbugs
静态代码审查工具
- Sonar Lint
也是个代码审查工具,检查可能出现的bug
- Checkstyles
代码风格管理的插件
- ADB Idea
增加了例如卸载,重启App的功能
- Exynap
这个玩意挺NB的输入个大概就能帮你写代码。其中的bind view 挺好用的。
- Dagger IntelliJ Plugin
Dagger的可视化辅助工具
- JVM Debugger Memory View
可以调试JVM的一些细节,讲真我用的不多
-
在 Android Studio 中使用 Live Templateso
newInstance - 在Fragment中生成 newInstance 方法
Toast - 生成 Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
fbc - 生成 findViewById
const - 定义一个 android style int 常量
logd - 生成 Log.d(TAG, "");
logm - Log 当前方法名称和参数
logr - Log 当前方法结果
logt - 当前类生成 log tag
psf - public static final
sout - 打印一个字符串到 System.out
soutm - 打印当前类名和方法到 System.out
soutp - 打印方法参数和返回值到 System.out
visible - 设置 view VISIBLE
gone - 设置 view GONE
noInstance - private 构造方法
Comprehensive list of all Live Templates in Android Studio 这个库有很多的自定义模版
-
Android Studio 的自动完成
Android Studio/IntelliJ 可以帮你自动完成一些代码
<expr>.null 转换成 if(<expr> == null)
<expr>.notnull 转换成 if(<expr> != null)
<expr>.var 转换成 T name = <expr>
<expr>.field 会自动生成一个全局变量 field = <expr>
<ArrayExpr>.for 转换成 for(T item : <Arrayexpr>)
<ArrayExpr>.fori 转换成 for(int i = 0; i < <Arrayexpr>.length; i++)
<ArrayExpr>.forr 转换成 for(int i = <Arrayexpr>.length - 1; i > 0 ; i--)
完整的转换列表参见 Settings → Editor → Postfix Templates
-
使用黑色主题
虽然是个人爱好,反正我觉得使用白色主题好瞎眼啊
-
别使用小字体
给你的 Android Studio 选择一个合适的字体,作者推荐使用Menlo font 反正我觉得mac的字体就挺好的,在linux上开发已经觉得不顺眼了.
-
使用一个 code style
你应该使用一个标准的编码风格,它可以是:
表示在编码风格这一块自己确实有待规范^^
-
使用 Embedded Terminal inside Android Studio
-
使用 Memory/Network/CPU Monitor 检测你的 code/app
-
配置 Android Studio
这个可以看下,文章提到的我是早就配置过了
模拟器
简单说就是显示你连上的真机,也就在你做演示的时候有些用处,而且我一连上手机就自己跳出来,各位自己使用评价吧!
不但能展示还可以控制你的Android设备.免费版本 可以使用电脑鼠标, 收费版本 可以使用电脑键盘. 你可以手不离开键盘进行测试.
编码时候的更优选择
- 使用 OkHttp 替代 HttpUrlConnect
HttpUrlConnect 有一些bug quite some bugs. Okhttp 优雅的解决了他们. [Reference Link]
dependencies {
compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar')
}
repositories{
flatDir{
dirs 'libs'
}
}
这个不错,不过我没找到一个命令参数表,就只关注我想要关注的 log
可以分析Android Apk很不错
Facebook 出品,非常不错的工具,可以在 Chrome 中看到网络请求,调试数据库和SharePreference,和 Okhttp搭配使用更好,我配合urlconnection使用不生效,原因不明。
使用"bugreport"分析耗电
这篇文章可以看一下,作者说在一些设备上 Timer 不工作但是原因不明,作者说的使用 Handler 替代 Timer 确实是对的,我们商店有一段时间anr很多,后来发现和Timer相关。
如果你 确实 要用png, 可以使用 TinyPNG 压缩.
android {
...
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
android {
...
buildTypes {
release {
shrinkResources true
minifyEnabled true
...
}
}
}
shrinkResources 是把你没用到的文件用一个很小的文件替换,我觉得要是你发现了那个文件确实没啥用,你还是删除了吧。
adb shell am kill
译文见降低 gradle 内存又加快构建
Gradle memory >= Dex memory + 1Gb
defaultConfig {
...
ndk {
abiFilters "armeabi", "armeabi-v7a", "mips", "x86"
}
}
//Split into platform dependent APK
splits {
abi {
enable true
reset()
include 'armeabi', 'armeabi-v7a', 'mips', 'x86' //select ABIs to build APKs for
universalApk false //generate an additional APK that contains all the ABIs
}
}
// map for the version code
project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'mips': 5, 'x86': 8]
// Rename with proper versioning
android.applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
output.versionCodeOverride =
project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) *
1000000 +
android.defaultConfig.versionCode
}
}
-
学习一些架构例如 MVP 或者 Clean架构
-
尝试理解 TDD (测试驱动开发)
-
强制重新下载 dependencies
./gradlew --refresh-dependencies
-
gradle 中跳过某个task
下面的例子是跳过 javaDoc 这个任务
./gradlew clean build -x javaDoc
-
为每个子项目的脚本配置同名 gradle 构建文件
settings.gradle 中设置
rootProject.children.each{
it.buildFileName = it.name + '.gradle'
}
更多的Gradle技巧
-
记住 DRY
DRY = Do not Repeat Yourself
一开始我们也是按照层去分包的,很坑爹。按照功能分可能你不是很好区分在哪个功能中,不过也比你按照层区分要好找很多。
android {
buildTypes {
debug {
applicationIdSuffix '.debug'
versionNameSuffix '-DEBUG'
}
release {
// ...
}
}
}
Android使用Gradle构建,这实际上可以很容易做些自动化的东西。实用的 Gradle 脚本
-
给你的Android项目使用合适的 .gitignore, Check it here
-
使用 LeakCanary 分析你的app
-
使用 Android Studio 2.3 加速 gradle 构建+
-
切换到 gradle 3.3
执行下面的代码升级你的 gradle wrapper
./gradlew wrapper --gradle-version 3.3 --distribution-type all
-
全局 gradle.properties 如下设置
android.enableBuildCache=true
这个命令我测试了,不好使啊!直接改wrapper里面引用就行。
-
停止 gradle 构建进程
./gradlew -stop
-
开启 gradle 自动下载sdk
全局gradle.properties如下设置
android.builder.sdkDownload=true
实验性功能 [Bug Ref]
-
jcenter()和 mavenCentral()不用同时依赖`
JCenter 是 MavenCentral 的超集. [参考]
| Alias |
Usage |
alias screenshot="adb exec-out screencap -p > screen-$(date -j "+%s").png" |
screenshot |
| `alias startintent="adb devices |
tail -n +2 |
| `alias apkinstall="adb devices |
tail -n +2 |
| `alias rmapp="adb devices |
tail -n +2 |
| `alias clearapp="adb devices |
tail -n +2 |
-
设置含有 //STOPSHIP 时候编译失败 [Ref Link]
启用这个功能 //STOPSHIP 失败功能, build.gradle 如下设置
android {
...
lintOptions {
abortOnError true
fatal 'StopShip'
}
}
//STOPSHIP 注释也会导致编译失败。
在 Android Studio Preferences > Editor > Code Style > Inspections, 可以控制这个功能
Gradle, Please 的命令行版本.
+ 执行
```bash
alfi name_of_library
```
+ 复制结果
+ 粘贴到 build.gradle
-
使用 dryrun 直接测试一个库
dryrun REMOTE_GIT_URL
表示还得下各种gradle版本,也就那么回事,不见得多快。
-
控制台直接输入单元测试结果 [Ref Link]
控制台输出单元测试结果小技巧.
android {
...
testOptions.unitTests.all {
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
outputs.upToDateWhen { false }
showStandardStreams = true
}
}
}
-
离线模式编译更快 [Ref Link]
--offline 总是从cache运行, 离线模式不会访问网络.没有缓存会编译失败.
-
使用一个抽象 Logger 类
-
如果你想自动初始化你的库 Content Provider [Read how Firebase does it - Ref Link]
译文自动初始化你的库
- 使用
"android:extractNativeLibs:false" 在 <application> 减小包体积 [Ref Link]
这个属性是6.0开始的属性,告诉系统你不用把apk解压缩出来了,但是so不能被压缩,so 需要zipalign对齐,这个步骤不是自动的,我觉得慎用。
*** UI/UX 相关***
-
移动
- Material Design 使用的是现实风格的设计.现实世界中物体根据运动的性质在曲线上进行加速或者减速,而不是做直线运动.
- 所以移动也应该使用这样的属性或者动画来保持自然。
- 例如一辆车离开屏幕应该是先慢后快直到离开。同样的, 视图也应该使用插值器类例如 AccelerateInterpolator, FastOutSlowInInterpolator
- 等等 [更多参考]
-
排版
- While custom typefaces can be used for branding, it is essential to stick to Roboto and Noto if possible, especially for body text, due to their clarity and optimistic nature.
- Roboto covers Latin, Greek and Cyrillic extended scripts, with Noto filling in for other language scripts [More Info]
- Weight balancing is an important aspect of typography, the fundamental concept of which is that the larger a typeface is, the less its weight should be so that it doesn’t appear too thick and balances its weight with smaller typefaces of higher weights
- Typography should align to a 4dp baseline grid, and maintain a minimum contrast ratio of 4.5:1 based on luminance values, with a recomemended ratio being 7:1.
- The ideal reading length for large blocks of text is 40 to 60 characters per line. Anything less is too narrow and anything more is too wide.
-
图标
- Icons should be designed at 48dp, with 1dp edges, which equates to
- 48px by 48px at mdpi
- 72px by 72px at hdpi
- 96px by 96px at xhdpi
- 144px by 144px at xxhdpi
- 192px by 192px at xxxhdpi
- An additional icon of 512px by 512px should be designed for use on Google Play
- Material icons, in addition to the base icon, should contain the following important elements
- 1dp tinted edge at the top
- 1dp shaded edge at the bottom
- Contact shadow - a soft shadow around all edges of raised elements
- Finish - a soft tint to provide surface lighting, fading from upper life to lower right [More Info]
-
水波纹
-
使用 ?attr/selectableItemBackground 替代 ?android:attr (Ref)
-
在例如 Button 这种控件内部实现水波纹 (Ref)
```xml
android:background="?attr/selectableItemBackground"
```
-
实现可溢出的水波纹: (Ref)
```xml
?attr/selectableItemBackgroundBorderless
```
-
其他
- Views should be aligned to Material Design’s 8dp baseline grid and the keylines when possible. This gives the UI a sense of structure and hierarchy. [More Info](这个说的是设计方面的,8dp基线我不知道是啥)
- 如果你要保留一个 ViewGroup 的引用(像 LinearLayout 、FrameLayout等等)又没有用到他们的特殊方法,就生命一个ViewGroup[More Info]
- accent color 和 primary color 颜色要互补,形成比较好的对比度。
其他资源
作者的开源库(不是晓晨哦,这篇文档原作者)
- EasyDeviceInfo - Enabling device information to be at android developers hand like a piece of cake!
- Sensey - Android library to make detecting gestures easy
- PackageHunter - Android library to hunt down package information
- Zentone - Easily generate audio tone in android
- RecyclerViewHelper - RecyclerViewHelper provides the most common functions around recycler view like Swipe to dismiss, Drag and Drop, Divider in the ui, events for when item selected and when not selected, on-click listener for items.
- StackedHorizontalProgressbar - Android Library to implement stacked horizontal progressbar
- QREader - A library that uses google’s mobile vision api and simplify the QR code reading process
- ScreenShott - Simple library to take a screenshot of the device screen , programmatically!
- EvTrack - Android library to make event and exception tracking easy
- OptimusHTTP - Android library that simplifys networking in android via an async http client
- ShoutOut - Android library for logging information in android
评论