- How to Create Your Own Shortcut in Android Studio?
- Approach
- Add Keyboard Shortcut:
- Add Mouse Shortcut:
- Add Abbreviation:
- Обзор Android Shortcuts
- Общий обзор
- Основные компоненты
- Виды шорткатов
- Статические шорткаты
- Динамические шорткаты
- Закрепленные шорткаты
- Детали и тонкости применения
- App shortcuts overview
- Shortcut types
- Display shortcuts in assistants using capabilities
- Shortcut limitations
- How to Create a Shortcut on Android
- Add a shortcut to any app or website on your home screen
- What to Know
- How Do I Put an Icon on My Home Screen?
- How Do I Create a Shortcut for an App Function?
- How Do I Create a Shortcut to a Website on Android?
- How Do I Create a Shortcut to My Android Home Screen?
- How Do I Delete Shortcuts on Android?
How to Create Your Own Shortcut in Android Studio?
Android Studio is the official integrated development environment for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android app development . Android Studio offers a lot of shortcuts to users. It also provides to configure Keymap and add your own shortcuts. So in this article let’s create our own shortcut and use them to easily navigate throughout the Android Studio.
Approach
On Windows, go to File -> Settings, on Mac: Android Studio -> Preferences and navigate to the Keymap pane. It opens with the shortcuts for different categories that you want to make or are already there in Android Studio.
On expanding editor actions, and right-clicking on the desired Keymap, we can add shortcuts in three ways.
Add Keyboard Shortcut:
Making the Keyboard shortcut feature also gives the choice that whether or not we are overriding the previously set shortcuts.
One can anytime change/remove the shortcut too. For example, the custom shortcut Shift+ A which we set for Move Caret Backward a Paragraph can be removed.
Remove the shortcut by right click and Remove Shift+A.
Add mouse shortcut and add abbreviations are similar to add the Keyboard shortcut.
Add Mouse Shortcut:
This option asks to create shortcuts by creating shortcuts mouse operations or with Ctrl, Tab, Shift, etc. like done in the following image.
Add Abbreviation:
Adding the Abbreviation feature lets you search for an action when you do “Search Everywhere“(double shift). Here’s the added abbreviation to Move Caret Backward a Paragraph.
Источник
Обзор Android Shortcuts
С версии ОС Android 7.1 (API 25) Google предлагает нам новый механизм работы с приложениями — Android Shortcuts. Мы написали краткий обзор этой фичи, созданной для удобства пользователей.
Общий обзор
В переводе с английского «shortcut» — кратчайший путь, такое название хорошо отражает основное предназначение шорткатов. Они позволяют нам попасть в какую-то определенную точку приложения и выполнить конкретное действие всего за пару нажатий. Шорткаты неплохо смотрятся, например, если пользователю надо:
• выбрать заранее определенный маршрут в навигаторе;
• начать беседу с другом в мессенджере;
• продолжить игру с последней точки сохранения.
Основные компоненты
Шорткат включает в себя:
1) интент или массив интентов, которые запускают конкретное действие;
2) идентификатор или ID, определяющий именно этот шорткат;
3) короткое и длинное сообщения, отображающиеся при его показе;
4) иконка слева от текста.
Чтобы лучше разобраться в механике работы с шорткатами, рассмотрим их классификацию.
Виды шорткатов
Android предлагает 2 вида шорткатов (на самом деле их три, но об этом ниже): статические и динамические. Далее рассмотрим каждый тип шорткатов с небольшими примерами и пояснениями.
Статические шорткаты
Описание статических шорткатов содержится в xml -файле. Они создаются один раз, их нельзя удалить, добавить и изменить без обновления приложения, но их достаточно просто создать.
Файл shortcuts.xml , содержащийся в res/xml/ :
И пара строк в AndroidManifest.xml :
Удалить шорткат или поменять его составляющие никак не получится, пока приложение не будет обновлено.
Статические шорткаты рекомендуется использовать для тех действий, которые точно никак не изменятся из-за пользовательских манипуляций с приложением и всегда будут доступны. Например, открыть новый поисковый запрос, перейти в настройки уведомлений, начать новую беседу. Однако использовать статический шорткат, к примеру, для того, чтобы отправлять пользователя сразу на экран авторизации — не очень хорошая идея. А что, если он уже авторизован? Тогда это действие не имеет смысла. В таких случаях нам пригодятся динамические шорткаты.
Динамические шорткаты
Их можно добавлять, удалять, изменять в режиме реального времени, то есть в зависимости от тех или иных событий. Вернемся к примеру с авторизацией: если пользователь не авторизован, то добавляем этот шорткат, как только авторизовался — удаляем.
Все взаимодействие с шорткатами программно происходит через класс ShortcutManager, доступный для 23 версии API, однако большинство его методов доступны только для 25 версии API. Операции с ними достаточно просты, но есть некоторые нюансы, которые будут подробно рассмотрены дальше.
Удалять и изменять динамические шорткаты также достаточно просто:
Закрепленные шорткаты
На самом деле есть еще один вид шорткатов — это, если дословно переводить, «приколотые» или «закрепленные» (pinned) шорткаты. Выглядят они так:
Создавать такие шорткаты программным образом нельзя, как и удалять. Это может сделать только сам пользователь. Но с помощью кода их можно отключить ( disableShortcuts() ). Можно закреплять как статические, так и динамические шорткаты.
При дизейбле любого шортката можно задать соответствующее сообщение, которое будет выведено пользователю при нажатии на него.
Мы ознакомились с шорткатами и основными принципами их работы в целом. Теперь можно перейти к деталям, особенностям и практическим советам.
Детали и тонкости применения
1. При добавлении шорткатов в большинстве случаев они будут отображаться от первого добавленного к последнему, первый добавленный будет ближе всех к иконке приложения. Сначала будут отображены статические, затем динамические.
2. При создании шортката необходимо установить длинное и короткое сообщения. Длинное сообщение указывается в списке, если оно не вмещается — то короткое. Google рекомендует устанавливать короткое сообщение не более 10 символов, а длинное — не более 25.
3. Несмотря на то, что можно добавить максимально пять шорткатов, Google рекомендует не добавлять более четырех. Да и в списке больше четырех шорткатов не отобразится (последний добавленный не покажется). Зачем нужен пятый шорткат — загадка, ведь на планшетах он тоже не отображается.
4. У атрибута targetPackage статических шорткатов есть одна особенность — он может иметь только хардкод-значение. Если у Вас для разных сборок приложения используются различные суффиксы applicationId , то при объявлении шортката указать значение targetPackage ссылкой, например, @string/shortcut_target_package , не получится. Придется создавать файл shortcuts.xml отдельно для каждого buildFlavour приложения и прописывать необходимый targetPackage вручную с нужным суффиксом applicationId .
5. Важно, что Android сам никак не регулирует количество добавляемых шорткатов. Если вы по какой-то причине захотите добавить шестой шорткат, приложение просто упадет, выбросив IllegalArgumentException: Max number of dynamic shortcuts exceeded . Самостоятельно следите за количеством добавляемых шорткатов.
6. Если не задать хотя бы одному интенту шортката атрибут action, то в случае динамического шортката приложение упадет при создании этого шортката, а в случае статического — шорткат просто не будет создан. Отметим, что в extras интентов шортката нельзя положить некоторые типы, например, Serializable , допустимые типы можно увидеть в исходниках PersistableBundle.
7. Если попытаться вызвать getSystemService(ShortcutManager.class) на устройстве ниже 23 API, то приложение упадет с ClassNotFoundException .
8. При добавлении нескольких интентов к шорткату, которые обрабатываются разными активностями, можно выстроить определенный стек активностей. Самой нижней в этом стеке будет активность, обработавшая первый добавленный интент.
9. Если пользователь заблокирован на устройстве, то воспользоваться шорткатами у него не получится — они содержатся в зашифрованном хранилище.
10. Если пользователь хочет поддерживать приложение на другом устройстве, то только «закрепленные» шорткаты будут воссозданы на нем. Динамические и статические не воссоздаются, однако статические будут заново определены при установке приложения. Если вас волнует поддержка приложения на разных устройствах, и вы не поставили флаг allowBackup = false в Манифесте, нужно заботиться только о ручном воссоздании динамических шорткатов.
11. Android developers также предлагают нам использовать метод reportShortcutUsed(String id) при выполнении действия из соответствующего шортката — как при нажатии на шорткат, так и локально в приложении, если действие то же самое. Как утверждают разработчики, должна быть статистика использования тех или иных действий из шорткатов, и на основе этой статистики пользователю могут предлагаться определенные шорткаты. Возможно, именно здесь должен раскрыться потенциал пятого шортката.
Напоследок парочка еще не упомянутых советов от Android developers.
1. Обновляйте шорткаты ( updateShortcuts() ), если их содержание и значение не изменилось, а изменилось только отображаемое сообщение или иконка. Если вы хотите убрать один шорткат и добавить другой, то не используйте обновление, выполните операции удаления, а затем добавления. Пренебрегая этим советом, можно получить разного рода казусы с «закрепленными» шорткатами.
2. Следуйте руководству по дизайну шорткатов. Это небольшой документ, которому нетрудно следовать.
Источник
App shortcuts overview
As a developer, you can define shortcuts to perform specific actions in your app. These shortcuts can be displayed in a supported launcher or assistant, like Google Assistant, and help your users quickly start common or recommended tasks within your app.
This set of guides teaches you how to create and manage app shortcuts. Additionally, you’ll learn some best practices that will improve the effectiveness of your shortcuts.
Shortcut types
Each shortcut references one or more intents, each of which launches a specific action in your app when users select the shortcut. The types of shortcuts that you create for your app depend on the app’s key use cases. Examples of actions you can express as shortcuts include the following:
- Composing a new email in an email app.
- Navigating users to a particular location in a mapping app.
- Sending messages to a friend in a communication app.
- Playing the next episode of a TV show in a media app.
- Loading the last save point in a gaming app.
- Ordering a drink in a delivery app with your voice, using spoken commands.
Note: Only main activities—activities that handle the Intent.ACTION_MAIN action and the Intent.CATEGORY_LAUNCHER category—can have shortcuts. If an app has multiple main activities, you need to define the set of shortcuts for each activity.
You can publish the following types of shortcuts for your app:
- Static shortcuts are defined in a resource file that is packaged into an APK or app bundle.
- Dynamic shortcuts can be pushed, updated, and removed by your app only at runtime.
Pinned shortcuts can be added to supported launchers at runtime, if the user grants permission.
Note: Users can also create pinned shortcuts themselves by copying your app’s static and dynamic shortcuts onto the launcher.
Display shortcuts in assistants using capabilities
Capabilities in shortcuts.xml allow you to declare the types of actions users can take to launch your app and jump directly to performing a specific task. For example, you can allow users to have voice control of your app through Google Assistant by declaring capability elements that extend your in-app functionality to Assistant App Actions. For more details, see Add capabilities.
Shortcut limitations
Most supported launchers display up to four shortcuts at a time, counting both static and dynamic shortcuts. When pushing dynamic shortcuts for display on Googles surfaces such as Google Assistant, use the Google Shortcuts Integration library to avoid being subjected to the shortcut limit.
If you choose not to use the Google Shortcuts Integration library, your app is limited to pushing up to the maximum number of shortcuts supported by the device at a time. Shortcuts published in this manner only appear within the Android launchers and are not discoverable on Google surfaces such as Assistant.
Note: The maximum number of shortcuts a device supports may vary. Use the getMaxShortcutCountPerActivity() method to determine how many shortcuts a particular device supports.
There is no limit to the number of pinned shortcuts to your app that users can create. Even though your app cannot remove pinned shortcuts, it can still disable them.
Note: Although other apps can’t access the metadata within your shortcuts, the launcher itself can access this data. Therefore, these metadata should conceal sensitive user information.
To start creating shortcuts for your app, refer to the following pages:
For more details about operations that can be performed on shortcuts, see the ShortcutManager API reference.
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник
How to Create a Shortcut on Android
Add a shortcut to any app or website on your home screen
What to Know
- To add an Android app’s icon to your Home screen, long-press its icon and select Add to home.
- Long-press an app icon then long-press a function’s name and drag it to your Home screen to create an app function shortcut.
- To make a website shortcut on Android, open the site in Chrome, tap the ellipsis, and select Add to Home screen.
This guide will explain all of the steps for adding an app icon to an Android tablet or smartphone’s Home screen, how to make a shortcut to a website, and what to do to make a shortcut to an Android app function.
How Do I Put an Icon on My Home Screen?
You can add a shortcut for any app to your Android Home screen as long as you have the app installed. Here’s how to do it.
Open the list of all of your apps.
This can usually be done by tapping the icon that looks like a white circle with six blue dots in it.
Find the app you want to create a shortcut for and long-press on its icon.
Tap Add to home.
The app’s icon should then appear in the top-right corner of your Home screen on your Android tablet or smartphone. Long-press the app icon and drag it to where you want it to be.
How Do I Create a Shortcut for an App Function?
Some Android apps support functions which can be accessed by performing a long-press on their app icon. These functions can be pinned to your Android home screen as a separate icon to act as a shortcut to that specific task.
Perform a long-press on the app whose function you want to create a shortcut for.
A menu of available app functions should appear. Long-press the function you want to create a shortcut for and drag it onto your Home screen.
Move the shortcut icon to its desired position and release your finger. The icon will now work as a shortcut which will open the Android app and immediately activate that one specific function.
How Do I Create a Shortcut to a Website on Android?
Much like how you can create shortcuts for apps and app functions on Android tablets and mobiles, you can also add shortcuts to websites to your device’s Home screen.
For this example, we’ll use the Google Chrome app which comes pre-installed on most Android devices. You can also create website shortcuts with some other Android web browser apps which use similar steps though the phrasing may be slightly different.
Here’s how to pin a shortcut to a website onto your Android Home screen.
Open the Google Chrome web browser and navigate to the website you want to pin to your Home screen.
Tap the ellipsis icon in the top-right corner.
From the menu, tap Add to Home screen.
Enter a custom name for the website.
This name will be the word or words which will appear under the shortcut on your Home screen (shorter is better).
Tap Add.
Tap Add Automatically for the shortcut to be added to the top-left of your Home screen. Alternatively, you can long-press the icon and place the website shortcut icon manually.
Whichever option you choose, you can manually move the shortcut icon afterwards to wherever you like.
How Do I Create a Shortcut to My Android Home Screen?
There’s no need to create a shortcut to your Home screen as all Android devices have built-in ways to return to your Home screen no matter what app you’re using or which video you’re watching.
» data-caption=»» data-expand=»300″ data-tracking-container=»true»/>
To return to your Home screen, tap the Home button. Depending on your Android smartphone or tablet model, it may look like a circle or a horizontal line. It’s always located under the screen.
Alternatively, some Android smartphones allow you to return to your Home screen by swiping up from the bottom of the screen.
How Do I Delete Shortcuts on Android?
To delete a shortcut from your Android Home screen, long-press its icon and tap Remove from the popup menu.
This process will just delete the icon for the shortcut. To delete the app from your Android smartphone or tablet, tap Uninstall from the same menu.
In the My Files app, go to the Downloads folder and select the file. Then, tap the three dots in the upper-right corner and choose Add shortcut from the drop-down menu.
You can add contact shortcuts as Android widgets. In the Widget menu, choose Contacts to add a contact to your home screen.
Android comes with many built-in shortcuts for making calls, taking photos, sending texts, and more. Many Android devices also allow you to control your phone using gestures.
In the app drawer, tap the three dots in the upper-right corner and select Hide Apps to view your hidden Android apps. If you don’t see the Hide apps option, you have no hidden apps.
Источник