Статические андроидные ярлыки для нескольких ароматов?
Можно ли установить статические ярлыки для нескольких вариантов, не дублируя shortcuts.xml? У меня есть два варианта:
- main (пакет: com.test)
- бесплатно (пакет: com.test.free)
Shortcuts.xml выглядит следующим образом:
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_add_photo"
android:shortcutId="new_photo"
android:shortcutLongLabel="@string/new_photo"
android:shortcutShortLabel="@string/new_photo">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.test.MainActivity"
android:targetPackage="com.test"/>
</shortcut>
Проблема заключается в том, что имя пакета в намерении не может ссылаться на строковый ресурс и должно быть hardcoded в xml.
Чтобы также обеспечить ярлыки для свободного вкуса, я должен скопировать shortcuts.xml и изменить targetPackage на com.test.free, что является плохим решением.
Ответы
Ответ 1
Я создал плагин, который позволяет использовать manifestPlaceholders в ресурсах и может использоваться с версией 3.0.0 плагина android gradle
https://github.com/timfreiheit/ResourcePlaceholdersPlugin
SRC/основные/RES/shortcuts.xml:
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_add_photo"
android:shortcutId="new_photo"
android:shortcutLongLabel="@string/new_photo"
android:shortcutShortLabel="@string/new_photo">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.test.MainActivity"
android:targetPackage="${applicationId}"/>
</shortcut>
Ответ 2
ВАЖНО:. Это решение работает только для версий плагина Android версии gradle до 3.0 из-за изменений в способе обработки ресурсов.
Итак, просто удалите эту проблему из-за суффикса .debug
в нашем идентификаторе приложения для отладочных сборников. Это наш обходной путь (обратите внимание на непроверенную адаптацию из нашей кодовой базы):
src/main/res/shortcuts.xml
:
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_add_photo"
android:shortcutId="new_photo"
android:shortcutLongLabel="@string/new_photo"
android:shortcutShortLabel="@string/new_photo">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.test.MainActivity"
android:targetPackage="@string/application_id"/>
</shortcut>
<android module name>/build.gradle
:
apply plugin: 'com.android.application'
//region: Fix shortcuts.xml by manually replacing @string/application_id
final String APPLICATION_ID_STRING_RES_KEY = "application_id"
android.applicationVariants.all { variant ->
// Add the application id to the strings resources
// We do this so that in the future if google fixes the
// processing of the shortcuts.xml we can leave this
// and remove the `mergeResources.doLast` block below
resValue "string", APPLICATION_ID_STRING_RES_KEY, variant.applicationId
// Manually replace @string/application_id with `variant.applicationId`
variant.mergeResources.doLast {
println("variant = ${variant.applicationId}")
final File valuesFile = file("${buildDir}/intermediates/res/merged/${variant.dirName}/xml/shortcuts.xml")
final String content = valuesFile.getText('UTF-8')
final String updatedContent = content
.replace("@string/${APPLICATION_ID_STRING_RES_KEY}", variant.applicationId)
valuesFile.write(updatedContent, 'UTF-8')
}
}
//endregion
android {
...
}
Ответ 3
При исследовании этого я наткнулся на эту библиотеку, которая, похоже, делает трюк:
https://github.com/Zellius/android-shortcut-gradle-plugin
Даунсайд: вы не можете иметь shortcuts.xml
в папке res
вашего приложения, так как плагин берет файл, модифицирует его, чтобы автоматически добавить targetPackage
, а затем он его закроет во время сборки, а если у вас уже есть один определенный, это вызовет дублируемую ошибку ресурсов.
Помимо этого недостатка, кажется, отлично работает!