Xamarin(.Forms) Android 專案如何修正符合 Google Play 的目標 API 級別規定 (for API 31)

根據前一篇的說明,針對目標套件 API 31 的規範問題,若沒有調整 App 所使用的目標套件 SDK 就無法上架。

若有使用 Xamarin(.Forms) 技術開發 Android App 的話,該如何修正這個問題以利符合 Google Play 的目標 API 規範呢?

 


在 Android 的專案上的右鍵選單,找到 "屬性"。接著在 "應用程式" 分頁找到 "使用下列 Android 版本編譯: (目標 Framework)" 並選到 "Android 12.0"。

 

再到 "Android 資訊清單" 分頁中找到 "目標 Android 版本" 選到 "Android 12.0 (API 層級 31)"。

 

理論上這時候重新編譯 Xamarin.Android 專案就會出現類似下圖中的錯誤訊息:

 

上圖所出現的錯誤是切換 Target 到 API 31 時最容易遇到的錯誤(宣告 android exported 屬性),其他可能遇到的問題可參考下列連結說明:
https://developer.android.com/google/play/requirements/target-sdk?hl=zh-tw

 

而針對宣告 android: exported 屬性的設定原由可參考以下連結:
https://developer.android.com/topic/security/risks/android-exported?hl=zh-tw

而其中又討論到三個元件 Activity (活動)、Service (服務)、Broadcast Receiver(廣播接收器) 有設定 intent-filter (意圖篩選器) 時,其 android: exported 屬性需要明確宣告。

  1. Activity (活動) 的  android: exported 屬性的說明:
    https://developer.android.com/guide/topics/manifest/activity-element?hl=zh-tw
  2. Service (服務) 的  android: exported 屬性的說明:
    https://developer.android.com/guide/topics/manifest/service-element?hl=zh-tw
  3. Broadcast Receiver(廣播接收器) 的  android: exported 屬性的說明:
    https://developer.android.com/guide/topics/manifest/receiver-element?hl=zh-tw

於是乎,在 Xamarin.Android 專案當中需要針對實作 Activity (活動)、Service (服務)、Broadcast Receiver(廣播接收器) 的部份去明確宣告 android: exported 屬性。

 

喔~~~對了,如果沒有修正此 android: exported 屬性明確宣告問題,但仍成功的產出 .apk or .aab 也不用高興得太早(某一次莫名的成功產生,但再現不能…😓),上傳到 Google Play Console 的時候仍是會得到錯誤結果如下:

 

然後真的把 .apk 拿去 Android 12 的手機安裝,會無法安裝。

 

好,回到 Xamarin(.Forms) Android 專案當中,注意到文章前面有描述到當設定目標套件為 API 31 後 Visual Studio 重新編譯後發生的錯誤。

 

在這邊錯誤訊息中所指的 "AndroidManifest.xml" 並非在 Xamarin(.Forms) Android 專案當中的 "AndroidManifest.xml",而是經過編譯組合後的 "AndroidManifest.xml"。

可以在哪裡看到呢? 在專案資料夾底下的 obj → Release(組態) → 120(API 數字) 資料夾底下:

 

打開此 AndroidManifest 就可看到對應前面三個錯誤(一個 Activity;兩個 Services) 的 xml 標記:

 

所以再次回到 Visual Studio 當中,在方案總管當中找到 MainActivity.cs 開啟後,在該類別的 Activity Attritube 描述中加入 "Exported = false | true" 的設定:

注意: 是要設定為 true 還是 false 請參考上述列的官方文件說明(Activity),並根據自己專案當中所設計的應用需求去決定。

 

接著繼續在方案總管當中找到 XXXXService.cs 開啟後,在該類別的 Service Attritube 描述中加入 "Exported = false | true" 的設定:

注意: 是要設定為 true 還是 false 請參考上述列的官方文件說明(Service),並根據自己專案當中所設計的應用需求去決定。

 

當都找到對應的實作並調整 android: exported 屬性宣告完畢時,再次重新編譯專案成功,再來就能進行封存 Android 的發步套件 .apk or .aab,並上傳到 Google Play Console 囉!


 


I'm a Microsoft MVP - Developer Technologies (From 2015 ~).
 

MVP_Logo



I focus on the following topics: Xamarin Technology, Azure, Mobile DevOps, and Microsoft EM+S.

If you want to know more about them, welcome to my website:
https://jamestsai.tw 


本部落格文章之圖片相關後製處理皆透過 Techsmith 公司 所贊助其授權使用之 "Snagit" 與 "Snagit Editor" 軟體製作。