一些很不錯的Android開發技巧,這個項目翻譯自 android-tips-tricks 去掉了一些我認爲不重要的,對我使用過的東東做了評價,同時翻譯了一些自己沒有注意到的知識點的文章。
❤️ 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>.nootnull
轉換成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
簡單說就是顯示你連上的真機,也就在你做演示的時候有些用處,而且我一連上手機就自己跳出來,各位自己使用評價吧!
不但能展示還可以控制你的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
這個任務./gradlew clean build -x javaDoc
-
爲每個子項目的腳本配置同名 gradle 構建文件
settings.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 | cut -sf 1 | xargs -I X adb -s X shell am start $1" |
startintent https://twitter.com/nisrulz |
alias apkinstall="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X install -r $1" |
apkinstall ~/Desktop/DemoApp.apk |
alias rmapp="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X uninstall $1" |
rmapp com.example.demoapp |
alias clearapp="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X shell pm clear $1" |
clearapp com.example.demoapp |
-
設置含有
//STOPSHIP
時候編譯失敗 [Ref Link]啓用這個功能
//STOPSHIP
失敗功能,build.gradle
如下設置android { ... lintOptions { abortOnError true fatal 'StopShip' } }
//STOPSHIP
註釋也會導致編譯失敗。在 Android Studio
Preferences
>Editor
>Code Style
>Inspections
, 可以控制這個功能 -
使用
adb install -g
安裝並授予manifest中的全部權限 [More Info] -
使用
alfi
查找一個庫的依賴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運行, 離線模式不會訪問網絡.沒有緩存會編譯失敗.-
給你的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
其他資源
-
關注 podcasts
- Fragmented
-
這兩個最爲著名。
-
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