Fri. Dec 2nd, 2022

Hello Android

All android in one place

App Shortcuts: Getting Started | kodeco.com, the new raywenderlich.com

9 min read

Learn how to implement App Shortcuts in your Android app to make it more engaging for your users.

Many of the most commonly used apps consume App Shortcuts to provide users with easy access to its most important features. For example, Instagram provides shortcuts to Camera, New Post, View Activity, and Direct messages, while WhatsApp provides Camera and four conversations.

All these apps consume the ShortcutManager API for easy shortcut creations.

In this tutorial, you’ll learn how to manage three different shortcut types:

  • Static shortcuts through the xml file.
  • Dynamic shortcuts through the code.
  • Pinned shortcuts through the code.

Getting Started

Download the starter project by clicking on the Download Materials button at the top or bottom of the tutorial. Then, open the starter project in Android Studio 3.5 or later.

Take a look at the code. You’ll find the starter project with activities, a layout, a shortcut wrapper, and many TODOs.

Build and run the starter project. You’ll see an empty screen with a FabButton that launches a new Activity where you can create a new Note.

Try using the app. Tap the FabButton and create a new note. A new note will be visible in the list. Long press the note, and BottomSheetDialogFragment will show with two actions.

Actions related to the note

Now you’ll see what types of shortcuts are present and see what type you should use in which case.

Introducing App Shortcuts

Shortcut performs specific action in the specific app, triggered from the:

  • Supported launcher.
  • Assistant – e.g. Google Assistant.

Android app shortcuts could make your app more efficient if they’re used correctly.

A developer has a duty to take care of which features will provide in the app shortcut list, but a user needs to discover them and find them helpful.

Even for people like us, Android developers, it’s hard to remember how many powerful tools Android provides for the easier use of the device. One of these is app shortcuts functionality.

Although app shortcuts are already easy to access by long-pressing the icon on the home screen or app list, a user can pin all the shortcuts to the home screen for even easier access.

Developers should always consider supporting shortcuts, even if it’s hard for users to find them.

The next section will give you an overview of the app you’ll create in this article.

Types of Shortcuts

How you deliver content with shortcuts depends on your use case and whether the shortcut’s context is app-driven or user-driven. No matter if the shortcut’s context changes, both static and dynamic shortcuts are driven by your app.

In cases where a user chooses how they want your app to deliver content to them, such as with a pinned shortcut, a user defines the context.

The following scenarios show a few use cases for each shortcut type:

  • Static shortcuts: utilized for the content with the consistent structure through the lifetime of a user’s interaction. Instagram is using it for quick access to the Posts, Camera, or Direct messages.
  • Dynamic shortcuts: used for the actions that are context-sensitive. They’re made for the actions users perform in an app. For example, if you’re building a game that allows the user to start from their current level, you need to update the shortcut often.
  • Pinned shortcuts: used for specific, user-driven actions. The best example is pinning a specific website from your favorite browser. This is beneficial because it allows the user to perform a custom action. For e.g. quick navigation to the specific website

Although we have different types of shortcuts that cover all use cases, there are some limitations that we need to be aware of.

Limitations

Even though users can create as many dynamic shortcuts as they want, most supported launchers display up to four shortcuts at a time.If the app supports dynamic shortcuts, choose static shortcuts carefully, so there’s still some space for a user to create dynamic ones.

Yet, for the dynamic shortcuts used with Google Assistant, use Google Shortcuts Integration Library to avoid the limitation.

Note: If you want to learn more about pushing dynamic shortcuts to Google Assistant follow this Google Codelabs.

If you choose not to use the Google Shortcuts Integration Library, your app will support a limited number of shortcuts at a time.

Sometimes you’ll have to decide whether you want more static shortcuts or let the user create dynamic ones.

To determine how many shortcuts the launcher supports, use getMaxShortcutCountPerActivity() method provided in ShortcutManagerCompat class.

But, if your app supports pinned shortcuts, you’re safe from these limitations. Launchers don’t have a maximum number of pinned shortcuts.

It’s time to jump in on the actions used to manage shortcuts!

Managing App Shortcuts

As you already know, there are three different types of shortcuts, and the user manages dynamic ones.

The user is able to do several actions with the shortcuts:

  • Push: creates a new dynamic shortcut.
  • Update: updates dynamic shortcuts that already exist.
  • Remove: removes dynamic shortcuts from the list.
  • Remove All: removes all dynamic shortcuts.
  • Reordering: adds/updates dynamic shortcuts with the rank property.

Reordering is an action that happens as a side effect of Push or Update actions. Access these action on the ShortcutManagerCompat API, and they’re super easy to use.

Working With Shortcuts

In this section, you’ll find all the actions available for managing the app shortcuts and how to implement them.

Creating Static Shortcuts

Now, you’re going to start by creating static shortcuts with predefined and unchangeable actions.

Firstly, in the res package, under xml subfolder, find the shortcuts.xml file and open it.

In this file, you’ll find TODO 1: which you’ll replace with the following code:


<!-- 1 -->
<shortcut
    android:shortcutId="new_note"
    android:enabled="true"
    android:icon="@drawable/ic_new_note_shortcut"
    android:shortcutLongLabel="@string/new_note_long_label"
    android:shortcutShortLabel="@string/new_note_short_label">
    
    <!-- 2 -->
    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass="com.yourcompany.quicknotes.screen.notes.NotesActivity"
        android:targetPackage="com.yourcompany.quicknotes" />
    
    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass="com.yourcompany.quicknotes.screen.newnote.NoteActivity"
        android:targetPackage="com.yourcompany.quicknotes" />
        
    <!-- 3 -->
    <categories android:name="com.yourcompany.quicknotes" />
    <!-- 4 -->
    <capability-binding android:key="actions.intent.CREATE_NOTE" />
</shortcut>

This is what you’re code does:

  1. Define shortcut properties like ID, enabled state, icon, long and short labels.
  2. Define screens that opens after a user selects the shortcut.
  3. Define category in which the note belongs./li>
  4. Define the capability which links the shortcut with the built-in intents.

It’s essential to define the shortcut action properly. When you create a shortcut, allow users to open the screen flow that defines the feature they need.

Note: Capability binding relates to the Built-in intents which gives a user the option to access the feature defined as a shortcut action through the Google Assistant. You can see how to achieve that here.

Your next step is to give an app instructions to create static shortcuts. Go to the manifests folder and open AndroidManifest.xml file and replace TODO 2: with the following code snippet:


<meta-data
    android:name="android.app.shortcuts"
    android:resource="@xml/shortcuts" />

Your shortcut is ready to use. Build and run the app, go to launcher and long press on the app icon. Press the shortcut, and you’re ready to create a new note!

Instructions how to create a note with Static shortcut

Okay, that was easy. Time to move on to the logic of creating dynamic shortcuts.

Creating Dynamic Shortcuts

Dynamic shortcuts are a little bit tricky but still very easy to implement.

As before mentioned, you’ll need to use the ShortcutManager API. It is part of the Jetpack Libraries that lets you manage dynamic shortcuts within your app. It reduces boilerplate code and, most importantly, ensures that shortcuts behave the same across Android versions.

To add the functionality which will create a new dynamic shortcut, open the ShortcutManagerWrapper.kt file and replace TODO 3: with these lines of code:


return ShortcutInfoCompat.Builder(context, note.id)
    .setShortLabel(note.title)
    .setLongLabel("See ${note.title}")
    .setIcon(IconCompat.createWithResource(context, R.drawable.ic_note))
    .setIntents(
        arrayOf(
            NotesActivity.createIntent(context).apply { action = Intent.ACTION_VIEW },
            NoteActivity.createIntent(context, note.id).apply { action = Intent.ACTION_VIEW }
        )
    )
    .build()

Note: It’s likely that you have to make some imports for the code to work.

You can see that a dynamic shortcut acts the same as the static one. The difference is that now you have logic for making the shortcut more context-sensitive.

To fully enable creating dynamic shortcuts, replace TODO 4: with these two lines of code:


val shortcut = createShortcutInfo(note)
ShortcutManagerCompat.pushDynamicShortcut(context, shortcut)

The method pushDynamicShortcut(...) will do:

  1. Check limitation of the maximum number of shortcuts.
  2. Prepare shortcuts depending on the Android Verson.
  3. Remove shortcut with the lowest rank.
  4. Add a new one to the top of the list.

Awesome, you’re now ready to create your very first dynamic shortcut. Build and run the app, long-press the created note, and then long-press the app icon to show the shortcuts.

Instructions how to create a Dynamic Shortcut

The next step is enabling updates for the dynamic shortcut you’ve added.

Updating Dynamic Shortcuts

Updating a dynamic shortcut is the same as creating a new one.

In the QuickNotes app, your shortcut will update when you open an existing note and modify the content by pressing the update action in the top right corner.

Next task for you is to implement it so you can update the shortcut when needed.

In the ShortcutManagerWrapper.kt file, find TODO 5: and replace it with the following:


addNoteShortcut(note)

That’s it! Easy, right? 🙂

Try to update your existing note. Open it from the shortcut you’ve added, update it and confirm that the app has updated the note. Now go and check the shortcut you previously created.

You will create another note and the shortcut for it. Close the app, open the shortcut list, and verify that the bottom-most shortcut is the one you created first.

Creating a second shortcut

Open the first note, change the title, and press update. If you check the shortcuts, you’ll see that you’ve changed the order. The one that you’ve edited is now at the top. Updating the shortcut also changes the shortcut rank.

Update first shortcut to make a change in order

Good job, you’re next step is to delete the shortcut.

Deleting a Dynamic Shortcut

To delete a dynamic shortcut, the first thing you’ll need to know is if the shortcut already exists.

Find TODO 6: and replace it with the following block of code:


override fun isShortcutCreated(noteId: String): Boolean {
    return ShortcutManagerCompat.getDynamicShortcuts(context)
        .find { it.id == noteId } != null
}

Check if the shortcut with the requested note exists in the list of dynamic shortcuts.

Since you don’t want your user to have the option to access a note once it gets deleted from the database or service, you’ll need to delete the shortcut too.

In the ShortcutManagerWrapper.kt find TODO 7: and replace it with these lines of code:


ShortcutManagerCompat.removeDynamicShortcuts(context, listOf(noteId))

Great, a user is now able to create, update and delete a dynamic shortcut, go ahead and try it. Build and run the app, and follow the next steps in order to check that everything works:

  1. Create a new note.
  2. Create a dynamic link.
  3. Verify that it’s created by long pressing on the app icon.
  4. Update the note title.
  5. Verify that it’s updated in the shortcut list.
  6. Delete the note.
  7. Verify that the shortcut has been deleted from the shortcut list.

Congratulations! You’ve implemented the dynamic shortcut feature! Now, you’re moving to the last type of shortcut.

Creating Pinned Shortcuts

There is only one type of shortcut left to implement. Creating a pinned shortcut is a little bit different than the others.

Find TODO 8: and replace it with this code snippet:


// 1
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
    // 2
    val pinShortcutInfo = ShortcutInfoCompat.Builder(context, note.id)
        .setShortLabel(note.title)
        .setIcon(IconCompat.createWithResource(context, R.drawable.ic_note))
        .setIntents(
            arrayOf(
                NotesActivity.createIntent(context).apply { action = Intent.ACTION_VIEW },
                NoteActivity.createIntent(context, note.id).apply { action = Intent.ACTION_VIEW }
            )
        )
        .build()
    // 3
    ShortcutManagerCompat.requestPinShortcut(context, pinShortcutInfo, null)
}

It’s easier to understand if it’s broken down into smaller pieces:

  1. Verify that the default launcher supports pinned shortcuts.
  2. Create ShortcutInfo with the short label, icon and intent which leads to
    desired Activity.
  3. Request a pin shortcut which will trigger native dialog with the shortcut info on newer Android versions, or create a shortcut instantly on versions below API 26.

Build and run the app, long-press the note, and create your first Quick Notes pinned shortcut.

Go to the launcher and check if it’s there.

Instructions how to create pinned shortcut

You’re just one press away from the tasks you’ll need for that day, shopping cart, or whatever it is you want to note. 🙂

Congratulations! You’re ready to make your app more accessible for the user. Think about the most important features you want to provide and don’t forget about the limited number of shortcuts.

Where to Go From Here?

You can download the complete project by clicking Download Materials at the top or bottom of this tutorial.

In this article, you’ve learned how to create different types of app shortcuts and how to use them.

As mentioned earlier, you can make your app easier to access with Google Assistant. You can find here an awesome article on how to create Actions for Google Assistant.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!

www.hello-android.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Hello android © All rights reserved. | Newsphere by AF themes.