Android 12 適配升級小結

    Android 12 發佈已經有 4 個月了,而且隨着各大市場對應用適配的要求逐漸提高,小菜也嘗試將一個歷史的應用簡單升級適配 Android 12

Android 12

    Android 12 對應 Build.VERSION_CODES.S,使用 Material You 打造的全新系統界面,富有表現力、活力和個性。使用重新設計的微件、AppSearch、遊戲模式和新的編解碼器擴展您的應用。支持隱私信息中心和大致位置等新的保護功能。使用富媒體內容插入功能、更簡便的模糊處理功能、經過改進的原生調試功能等提高工作效率。

    Android 12 相對我們的歷史項目來說屬於較大版本的更新,在適配過程中遇到一系列問題,小菜簡單記錄整理一下。

SDK 版本號升級

    小菜首先對 SDK 版本號進行升級,之後對升級後的應用逐步進行適配更新;

當前版本

minSdkVersion = 17
targetSdkVersion = 28
compileSdkVersion = 28
buildToolsVersion = '28.0.3'

升級後版本

minSdkVersion = 17
targetSdkVersion = 31
compileSdkVersion = 31
buildToolsVersion = '31.0.0'

Q1: Gradle 不匹配

    升級 SDKsync 後遇到第一個 Gradle 不匹配問題;

Installed Build Tools revision 31.0.0 is corrupted. Remove and install again using the SDK Manager.

A1: 升級 Android 12 對應 Gradle 版本

    歷史版本 Gradle 對應版本是 3.3.3,升級到最新的 7.0.4

classpath 'com.android.tools.build:gradle:7.0.4'

Q2: distributionUrl 不匹配

Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'com.android.internal.version-check']
    at com.android.build.gradle.BasePlugin.apply(BasePlugin.kt:33)
    at com.android.build.gradle.LibraryPlugin.apply(LibraryPlugin.kt:26)
    at build_21d4k8dpcp55f408j9ar3yifm.run(/Users/user/Documents/workspace/App/adlibrary/build.gradle:1)
Caused by: java.lang.RuntimeException: Minimum supported Gradle version is 7.0.2. Current version is 6.1.1. If using the gradle wrapper, try editing the distributionUrl in /Users/user/Documents/workspace/App/gradle/wrapper/gradle-wrapper.properties to gradle-7.0.2-all.zip
    at com.android.build.gradle.internal.plugins.VersionCheckPlugin.apply(VersionCheckPlugin.kt:59)
    at com.android.build.gradle.internal.plugins.VersionCheckPlugin.apply(VersionCheckPlugin.kt:33)
    ...

A2: 升級 Android 12 對應 distributionUrl Gradle 版本

    小菜將本地 gradle-wrapper.properties 中升級到與 classpath 一致的 7.0.2-all 即可;

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

Q3: Marven 倉庫不支持 Http

    小菜歷史項目中引入了很多公司內部倉庫和部分非 Https 的線上庫,在 Gradle 升級後,Marven 倉庫建議使用 Https 安全的倉庫;

Could not resolve all dependencies for configuration ':classpath'.
   > Using insecure protocols with repositories, without explicit opt-in, is unsupported. Switch Maven repository 'maven(http://0.0.0.0:80/xxx/App)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. 
   See https://docs.gradle.org/7.0.2/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 

A3: 升級 Https 線上庫或解決安全警告

    對於部分線上 Marven 倉庫可以更新至 Https,對於不可更新的庫可以通過添加 allowInsecureProtocol 屬性解決 Gradle 倉庫地址的不安全警告;

repositories {
    maven {
      url "http://0.0.0.0:80/xxx/App"
      allowInsecureProtocol = true
    }
}

Q4: compile 棄用

    小菜的歷史項目中有個別 Module 中未及時修改 compile(),而 Gradle 升級之後已完全棄用 compile()

A problem occurred evaluating project ':lib'.
> Could not find method compile() for arguments [directory 'libs'] on object of type
    org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

A4: 更新爲 api 或 implementation

    根據具體的業務需求將 compile() 更新爲 api / implementation 即可;

api fileTree(dir: 'libs', include: ['*.jar'])

Q5: Android 工程依賴的 Java 版本過低

A problem occurred evaluating project ':lib'.
> Failed to apply plugin 'com.android.internal.library'.
   > Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.
     You can try some of the following options:
       - changing the IDE settings.
       - changing the JAVA_HOME environment variable.
       - changing `org.gradle.java.home` in `gradle.properties`.

A5: 更新 Android 依賴版本爲 jdk 11.0.13

    通過 AndroidStudio -> Preferences... -> Gradle 更新 jdk 版本即可;

Q6: AGCPluginTask 中 randomEncryptComponent 屬性不應使用 @Optional 進行註釋

    小菜的歷史項目中使用了 Huawei HMS 推送等,使用的 Marven 庫版本較低,與升級後的 Gradle 不兼容;

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':push:processDebugManifest'.
> A failure occurred while executing com.android.build.gradle.tasks.ProcessLibraryManifest$ProcessLibWorkAction
   > Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem was found with the configuration of task ':app:processDebugAGCPlugin' (type 'AGCPluginTask').
  - Type 'com.huawei.agconnect.agcp.AGCPluginTask' property 'randomEncryptComponent' of type boolean shouldn't be annotated with @Optional.
    
    Reason: Properties of primitive type cannot be optional.
    
    Possible solutions:
      1. Remove the @Optional annotation.
      2. Use the java.lang.Boolean type instead.
    
    Please refer to https://docs.gradle.org/7.0.2/userguide/validation_problems.html#cannot_use_optional_on_primitive_types for more details about this problem.

A6: 升級華爲 HMS 庫版本

classpath 'com.huawei.agconnect:agcp:1.5.2.300'

Q7: 使用 Intent 過濾器的 Service 需設置 exported 屬性

    此元素設置 Activity 是否可由其他應用的組件啓動 —“true”表示可以,“false”表示不可以。若爲“false”,則 Activity 只能由同一應用的組件或使用同一用戶 ID 的不同應用啓動。
    如果您使用的是 Intent 過濾器,則不應將此元素設置爲“false”。否則,在應用嘗試調用 Activity 時,系統會拋出 ActivityNotFoundException 異常。相反,您不應爲其設置 Intent 過濾器,以免其他應用調用 Activity。

    如果沒有 Intent 過濾器,則此元素的默認值爲“false”。如果您將元素設置爲“true”,則任何知道其確切類名的應用均可訪問 Activity,但在系統嘗試匹配隱式 Intent 時,該 Activity 無法解析。

    此屬性並非是限制 Activity 向其他應用公開的唯一方式。您還可使用權限來限制哪些外部實體能夠調用 Activity

/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <service>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. 
    See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <service>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. 
    See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

A7: 在所有 Module 中找到使用 Intent 過濾器的 Service 並按業務需求添加對應的 exported 屬性

<service
    android:name="com.xxx.app.push.OPushMessageService"
    android:permission="com.coloros.mcs.permission.SEND_MCS_MESSAGE"
    android:exported="true">
  <intent-filter>
    <action android:name="com.coloros.mcs.action.RECEIVE_MCS_MESSAGE" />
  </intent-filter>
</service>

Q8: 使用 Intent 過濾器的 Receiver 需設置 exported 屬性

/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <receiver>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <receiver>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

A8: 在所有 Module 中找到使用 Intent 過濾器的 Receiver 並按業務需求添加對應的 exported 屬性

<receiver android:name="com.xxx.app.SystemReceiver"
    android:exported="false">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    <action android:name="android.intent.action.USER_PRESENT" />
  </intent-filter>
  <intent-filter>
    <action android:name="android.intent.action.PACKAGE_REMOVED" />

    <data android:scheme="package" />
  </intent-filter>
</receiver>

Q9: 使用 Intent 過濾器的 Activity 需設置 exported 屬性

/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
/.../src/main/AndroidManifest.xml Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

A9: 在所有 Module 中找到使用 Intent 過濾器的 Activity 並按業務需求添加對應的 exported 屬性

<activity
    android:name=".xxx.app.TestActivity"
    android:exported="false"
    android:theme="@style/Theme.notAnimation">
  <intent-filter>
    <action android:name="com.sogou.novel.reader.setting.clean" />

    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

Q10: PendingIntent 需聲明可變性

    在 Android 12 中創建 PendingIntent 的時候,需要顯示的聲明是否可變,請分別使用 PendingIntent.FLAG_MUTABLEPendingIntent.FLAG_IMMUTABLE 標誌,如果您的應用試圖在不設置任何可變標誌的情況下創建 PendingIntent 對象,系統會拋出 IllegalArgumentException 異常;

PACKAGE_NAME: Targeting S+ (version 10000 and above) requires that one of \
FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.

Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if \
some functionality depends on the PendingIntent being mutable, e.g. if \
it needs to be used with inline replies or bubbles.

A10: 根據業務設置 PendingIntent 可變性

    PendingIntent 是一個可以給另一個應用程序使用的 IntentPendingIntent 接收待處理意圖的應用程序可以使用與產生待處理意圖的應用程序相同的權限和身份執行待處理意圖中指定的操作;

    在 Adnroid 12 之前,默認創建一個 PendingIntent 它是可變的,因此其他惡意應用程序可能會攔截,重定向或修改此 Intent

PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext().getApplicationContext(), type, intent, PendingIntent.FLAG_IMMUTABLE);
            

W11: 避免使用 flatDirs 提醒

    Gradle 升級之後,提示避免使用 flatDir 提醒,因該方式不支持任何元數據方式;

Using flatDir should be avoided because it doesn't support any meta-data formats.
Using flatDir2 should be avoided because it doesn't support any meta-data formats.

A11: 使用 jniLibs.srcDirs 方式引入 libs 庫

    Gradle 升級之後使用 jniLibs.srcDirs 方式替代 flatDirlibs 庫引入,並更新 aar 引入方式;

當前版本

repositories {
    flatDir {
        dirs 'libs'
    }
}

implementation(name: 'test_name', ext: 'aar')

升級後版本

android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}

implementation (files("libs/test_name.aar"))

W12: dexOptions 棄用提醒

DSL element 'dexOptions' is obsolete and should be removed.
It will be removed in version 8.0 of the Android Gradle plugin.
Using it has no effect, and the AndroidGradle plugin optimizes dexing automatically.

A12: Gradle 升級後 dexOptions 已棄用,刪除即可

dexOptions {
    preDexLibraries = true
}

Tips:

    小菜在測試過程中,明明代碼中所有涉及 intent-filter 過濾器的 Activity / Service / Receiver 都已經設置了 exported 屬性,但依舊提示使用 Intent 過濾器的 XX 需設置 exported 屬性;其原因在於引入了各類三方 SDK,在引入的各類三方庫中可以存在對應的未設置 exported 屬性的 Activity / Service / Receiver,單獨設置處理一下即可;


    Android 12 的初步升級到此位置,還有很多特有的屬性,小菜會在後續的適配中進行完善;如有錯誤,請多多指導!

阿策小和尚

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