android-tips-tricks-cn
一些很不错的Android开发技巧,这个项目翻译自 android-tips-tricks 去掉了一些我认为不重要的,对我使用过的东东做了评价,同时翻译了一些自己没有注意到的知识点的文章。
:heart: star 支持一下
欢迎协作
了解你的工具
Android Studio
使用快捷键
使用更有效率的插件
快捷键提示插件 – 试用了一下,就是你点击的时候有些按钮会出来提示框告诉你这个的快捷键是什么以及你使用的次数,还不错,目的就是让你进行键盘流操作。
提供 Action 转换大小写什么的,感觉想不起来用。
Add Sort Lines action in Edit menu to sort selected lines or whole file if selection is empty.
静态代码审查工具
也是个代码审查工具,检查可能出现的bug
代码风格管理的插件
增加了例如卸载,重启App的功能
这个玩意挺NB的输入个大概就能帮你写代码。其中的bind view 挺好用的。
Dagger的可视化辅助工具
可以调试JVM的一些细节,讲真我用的不多
在 Android Studio 中使用 Live Templateso
newInstance
- 在Fragment中生成newInstance
方法Toast
- 生成Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
fbc
- 生成 findViewByIdconst
- 定义一个 android style int 常量logd
- 生成Log.d(TAG, "");
logm
- Log 当前方法名称和参数logr
- Log 当前方法结果logt
- 当前类生成 log tagpsf
- public static finalsout
- 打印一个字符串到 System.outsoutm
- 打印当前类名和方法到 System.outsoutp
- 打印方法参数和返回值到 System.outvisible
- 设置 view VISIBLEgone
- 设置 view GONEnoInstance
- 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
你应该使用一个标准的编码风格,它可以是:
表示在编码风格这一块自己确实有待规范^^
使用 Memory/Network/CPU Monitor 检测你的 code/app
-
这个可以看下,文章提到的我是早就配置过了
模拟器
- Genymotion 曾经我最喜欢的模拟器,貌似收费了,现在x86的模拟器也挺快的了。
- Intel Emulator bundled in SDK Manger
Vysor
简单说就是显示你连上的真机,也就在你做演示的时候有些用处,而且我一连上手机就自己跳出来,各位自己使用评价吧!
DeskDock
不但能展示还可以控制你的Android设备.免费版本 可以使用电脑鼠标, 收费版本 可以使用电脑键盘. 你可以手不离开键盘进行测试.
-
编码时候的更优选择
使用 OkHttp 替代 HttpUrlConnect
HttpUrlConnect 有一些bug quite some bugs. Okhttp 优雅的解决了他们. [Reference Link]
按照如下方式使用本地
aar
[Stackoverflow Ref]dependencies { compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar') } repositories{ flatDir{ dirs 'libs' } }
使用 Pidcat 获得更好的阅读体验
这个不错,不过我没找到一个命令参数表,就只关注我想要关注的 log
使用版本控制系统(VCS) 例如 Git
使用 ClassyShark
可以分析Android Apk很不错
使用 Stetho
Facebook 出品,非常不错的工具,可以在 Chrome 中看到网络请求,调试数据库和SharePreference,和 Okhttp搭配使用更好,我配合urlconnection使用不生效,原因不明。
-
使用”bugreport”分析耗电
总是使用固定的版本号 例如 “24.2.0”
版本依赖时候避免使用
+
- 防止api变更.
- 编译的时候不会请求网络检查版本.
-
这篇文章可以看一下,作者说在一些设备上 Timer 不工作但是原因不明,作者说的使用 Handler 替代 Timer 确实是对的,我们商店有一段时间anr很多,后来发现和Timer相关。
使用 Vectors 替代 PNG
如果你 确实 要用png, 可以使用 TinyPNG 压缩.
使用 proguard
android { ... buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }
使用 shrinkResources
android { ... buildTypes { release { shrinkResources true minifyEnabled true ... } } }
shrinkResources 是把你没用到的文件用一个很小的文件替换,我觉得要是你发现了那个文件确实没啥用,你还是删除了吧。
模拟 app 在后台被杀死, 在终端运行
adb shell am kill
-
Gradle memory >= Dex memory + 1Gb
使用 ndk 的时候注意自己分割 abi
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
这个任务gradle
./gradlew clean build -x javaDoc
为每个子项目的脚本配置同名 gradle 构建文件
settings.gradle 中设置
gradle
rootProject.children.each{
it.buildFileName = it.name + '.gradle'
}
记住 DRY
DRY = Do not Repeat Yourself
-
一开始我们也是按照层去分包的,很坑爹。按照功能分可能你不是很好区分在哪个功能中,不过也比你按照层区分要好找很多。
-
有利于你学习解决一些依赖冲突. 官方参考
给你没发布的版本使用不同包名
android { buildTypes { debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' } release { // ... } } }
build.gradle 中使用自定义任务
Android使用Gradle构建,这实际上可以很容易做些自动化的东西。实用的 Gradle 脚本
给你的Android项目使用合适的 .gitignore, Check it here
使用 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 的超集. [参考]
这样清除 gradle 缓存
~/.gradle/caches/
删除cache
文件夹- 打开 SDK Manager 重新同步 support libs 和 google play services
- re-sync project
- 搞定
给你的 adb 设置别名 [Ref Link]
以下的 Aliases 可以被添加到
~/.bashrc
或者~/.zshrc
,看起来不错
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` 如下设置
```gradle
android {
...
lintOptions {
abortOnError true
fatal 'StopShip'
}
}
```
//STOPSHIP
注释也会导致编译失败。
在 Android Studio
Preferences
>Editor
>Code Style
>Inspections
, 可以控制这个功能
使用
adb install -g
安装并授予manifest中的全部权限 [More Info]使用
alfi
查找一个库的依赖Gradle, Please 的命令行版本.
执行
alfi name_of_library
复制结果
- 粘贴到 build.gradle
使用
dryrun
直接测试一个库- 运行
dryrun REMOTE_GIT_URL
表示还得下各种gradle版本,也就那么回事,不见得多快。
控制台直接输入单元测试结果 [Ref Link]
控制台输出单元测试结果小技巧.
gradle
android {
...
testOptions.unitTests.all {
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
outputs.upToDateWhen { false }
showStandardStreams = true
}
}
}
离线模式编译更快 [Ref Link]
--offline
总是从cache运行, 离线模式不会访问网络.没有缓存会编译失败.给你的Debug加速:
./gradlew assembleDevelopDebug --offline
给你的单元测试加速:
./gradlew test --offline
使用一个抽象 Logger 类
如果你想自动初始化你的库 Content Provider [Read how Firebase does it - Ref Link]
译文自动初始化你的库
使用
"android:extractNativeLibs:false"
在<application>
减小包体积 [Ref Link]这个属性是6.0开始的属性,告诉系统你不用把apk解压缩出来了,但是so不能被压缩,so 需要zipalign对齐,这个步骤不是自动的,我觉得慎用。
选择执行一个特定方法 [Ref Link]
你收到过Google Play 违反政策的邮件吗? 别担心给你的app生成隐私策略 [Ref ink]
* 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]
- Icons should be designed at 48dp, with 1dp edges, which equates to
水波纹
其他
- 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 颜色要互补,形成比较好的对比度。
Tips 关于 Kotlin
-
Java 转 Kotlin 的 Cheatsheet.
-
其他资源
关注 podcasts
这两个最为著名。
-
Android 专家的采访短视频。
关注 CodePath Android Cliffnotes
有关于各种主题的完整的 Android 资源,并且实时更新。
关注新的 Android 开发库
Android Arsenal - 和 Android 开发者相关的工具、库、app
关注 android example apps
- Android Examples - 简单的 Android 例子。
- Google Samples - google 提供的多种 Android 例子
- Google Android Codelabs
Twitter上进行关注
Twitter 创建列表
-
Android开发视频
书签中加入这些网站
- Android Developers - Youtube Channel
- Android Niceties - UI Showcase
- Material Design Specs
- Everything About Material Design
- Platform Version Distribution
- Android Studio Release Notes
- Android Developers Blog
- AndroidDev-Reddit
- Github Trending Java Projects
- Stackoverflow-Android tag
- Support Library History
- Android Conferences
- Android Dev Docs
- Material Up - DesignShowcase
- Dribbble - MaterialDeisgnShowcase
使用免费的 mockable api
- Mockey - A tool for testing application interactions over http, with a focus on testing web services, specifically web applications that consume XML, JSON, and HTML.
- JSON Placeholder - Fake Online REST API for Testing and Prototyping
- API Studio - a playground for API developers
- Mocky - Mock your HTTP responses to test your REST API
- Mockbin - Mockbin allows you to generate custom endpoints to test, mock, and track HTTP requests & responses between libraries, sockets and APIs.
订阅这些内容
- Android Weekly - Free newsletter that helps you to stay cutting-edge with your Android Development
- AndroidDevDigest - A Handcrafted Weekly #AndroidDev Newsletter
- Infinium #AndroidSweets - Fresh news from Droid zone
- Kotlin Weekly - Free newsletter to stay uptodate with Kotlin Development
ADB/Fastboot Tools made avaialble as a separate package by google, download latest version for
其他的一些优秀的开发工具
- Android SVG to VectorDrawable - 一个 VectorDrawable 适配所有屏幕分辨率
- SQLite Viewer - 在线查看Sqlite
- Android 9-patch shadow generator - 帮助实现可完全定制的阴影
- APK method count - apk 方法数目统计
- Material Palette - 快速生成 material 风格调色板
- Javadoc Themer - 丰富你的JavaDoc
- Method Count
- Gradle, please - 通过名称查出 Android 依赖
- jsonschema2pojo - Json转Obj(我一般用GsonFormat)
- Android Asset Studio - A web-based set of tools for generating graphics and other assets that would eventually be in an Android application’s res/ directory.
- Device Art Generator - Quickly wrap app screenshots in device artwork
- Google Translator Toolkit - string.xml 快速翻译
- JSONViewer - json格式化
- ShapeShifter - SVG动画编辑器
- App Privacy Policy Generator - 生成你google play 的隐私策略
优秀的 android libraries
- StorIO - SQLiteDatabase 和 ContentResolver 的优雅封装
- Retrofit - Square 出品 NB 网络库
- Picasso - 优秀的图片加载库
- LeakCanary - 内存泄露检查工具
- AndroidViewAnimations - 可爱的动画合集
- Calligraphy - 最简单的自定义字体使用方法
-
作者的开源库(不是晓晨哦,这篇文档原作者)
- 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