一些很不錯的Android開發技巧

一些很不錯的Android開發技巧,這個項目翻譯自 android-tips-tricks 去掉了一些我認爲不重要的,對我使用過的東東做了評價,同時翻譯了一些自己沒有注意到的知識點的文章。

❤️ star 支持一下

GitHub stars GitHub forks GitHub watchers GitHub followers

歡迎協作

瞭解你的工具

Android Studio

  • 使用快捷鍵

    完整的快捷鍵指南 : MacOSX | Linux/Win

  • 使用更有效率的插件

    1. KeyPromoter

      快捷鍵提示插件 -- 試用了一下,就是你點擊的時候有些按鈕會出來提示框告訴你這個的快捷鍵是什麼以及你使用的次數,還不錯,目的就是讓你進行鍵盤流操作。

    2. String Manipulation

      提供 Action 轉換大小寫什麼的,感覺想不起來用。

    3. Lines Sorter

      Add Sort Lines action in Edit menu to sort selected lines or whole file if selection is empty.

    4. Findbugs

      靜態代碼審查工具

    5. Sonar Lint

      也是個代碼審查工具,檢查可能出現的bug

    6. Checkstyles

      代碼風格管理的插件

    7. ADB Idea

      增加了例如卸載,重啓App的功能

    8. Exynap

      這個玩意挺NB的輸入個大概就能幫你寫代碼。其中的bind view 挺好用的。

    9. Dagger IntelliJ Plugin

      Dagger的可視化輔助工具

    10. 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>.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

    你應該使用一個標準的編碼風格,它可以是:

    表示在編碼風格這一塊自己確實有待規範^^

  • 使用 Embedded Terminal inside Android Studio

  • 使用 Memory/Network/CPU Monitor 檢測你的 code/app

  • 配置 Android Studio

    這個可以看下,文章提到的我是早就配置過了

模擬

Vysor

簡單說就是顯示你連上的真機,也就在你做演示的時候有些用處,而且我一連上手機就自己跳出來,各位自己使用評價吧!

DeskDock

不但能展示還可以控制你的Android設備.免費版本 可以使用電腦鼠標, 收費版本 可以使用電腦鍵盤. 你可以手不離開鍵盤進行測試.

-

編碼時候的更優選擇

  • 使用 OkHttp 替代 HttpUrlConnect

    HttpUrlConnect 有一些bug quite some bugsOkhttp 優雅的解決了他們. [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使用不生效,原因不明。

  • 使用 Battery Historian

    使用"bugreport"分析耗電

  • 總是使用固定的版本號 例如 "24.2.0"

    版本依賴時候避免使用 +

    • 防止api變更.
    • 編譯的時候不會請求網絡檢查版本.
  • 使用 Handler 替代 TimerTask

    這篇文章可以看一下,作者說在一些設備上 Timer 不工作但是原因不明,作者說的使用 Handler 替代 Timer 確實是對的,我們商店有一段時間anr很多,後來發現和Timer相關。

  • Google Play 的開發者賬戶不要使用你的個人郵箱

  • 使用 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

  • 參考 降低 gradel 內存又加快構建

    譯文見降低 gradel 內存又加快構建

        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'
      }

    更多的Gradle技巧

  • 記住 DRY

    DRY = Do not Repeat Yourself

  • 按照功能分包

    一開始我們也是按照層去分包的,很坑爹。按照功能分可能你不是很好區分在哪個功能中,不過也比你按照層區分要好找很多。

  • 學習依賴原理

    有利於你學習解決一些依賴衝突. 官方參考

  • 給你沒發佈的版本使用不同包名

          android {
              buildTypes {
                  debug {
                      applicationIdSuffix '.debug'
                      versionNameSuffix '-DEBUG'
                  }
    
                  release {
                      // ...
                  }
              }
          }
  • 找出並解決你的內存泄露

  • 小心使用 @android:color/transparent

  • 遵循標準的資源命名

  • build.gradle 中使用自定義任務

    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 的超集. [參考]

  • 這樣清除 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 的命令行版本.


 
  1. + 執行

  2.  
  3. ```bash

  4. alfi name_of_library

  5. ```

  6.  
  7. + 複製結果

  8. + 粘貼到 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]

    Image

  • 你收到過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]
  • 水波紋

    • 使用 ?attr/selectableItemBackground 替代 ?android:attr (Ref)
    • 在例如 Button 這種控件內部實現水波紋 (Ref)

        android:background="?attr/selectableItemBackground"
    • 實現可溢出的水波紋: (Ref)

        ?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 顏色要互補,形成比較好的對比度。

Tips 關於 Kotlin

其他資源

作者的開源庫(不是曉晨哦,這篇文檔原作者)

  • 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章