Friday, October 28, 2022
HomeProgrammingApp Shortcuts: Getting Began | Kodeco, the brand new raywenderlich.com

App Shortcuts: Getting Began | Kodeco, the brand new raywenderlich.com


Discover ways to implement App Shortcuts in your Android app to make it extra participating to your customers.

Most of the mostly used apps eat App Shortcuts to offer customers with easy accessibility to its most vital options. For instance, Instagram supplies shortcuts to Digital camera, New Submit, View Exercise, and Direct messages, whereas WhatsApp supplies Digital camera and 4 conversations.

All these apps eat the ShortcutManager API for straightforward shortcut creations.

On this tutorial, you’ll discover ways to handle three totally different shortcut varieties:

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

Getting Began

Obtain the starter mission by clicking on the Obtain Supplies button on the high or backside of the tutorial. Then, open the starter mission in Android Studio 3.5 or later.

Check out the code. You’ll discover the starter mission with actions, a format, a shortcut wrapper, and plenty of TODOs.

Construct and run the starter mission. You’ll see an empty display with a FabButton that launches a brand new Exercise the place you’ll be able to create a brand new Be aware.

Starting activity in QuickNotes app

Strive utilizing the app. Faucet the FabButton and create a brand new be aware. A brand new be aware might be seen within the record. Lengthy press the be aware, and BottomSheetDialogFragment will present with two actions.

Actions related to the note

Now you’ll see what sorts of shortcuts are current and see what sort you must use during which case.

Introducing App Shortcuts

Shortcut performs particular motion within the particular app, triggered from the:

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

Android app shortcuts may make your app extra environment friendly in the event that they’re used accurately.

A developer has an obligation to handle which options will present within the app shortcut record, however a consumer wants to find them and discover them useful.

Even for individuals like us, Android builders, it’s laborious to recollect what number of highly effective instruments Android supplies for the simpler use of the machine. One in every of these is app shortcuts performance.

Though app shortcuts are already straightforward to entry by long-pressing the icon on the house display or app record, a consumer can pin all of the shortcuts to the house display for even simpler entry.

Builders ought to all the time think about supporting shortcuts, even when it’s laborious for customers to search out them.

The subsequent part offers you an summary of the app you’ll create on this article.

Varieties of Shortcuts

The way you ship content material with shortcuts is dependent upon your use case and whether or not the shortcut’s context is app-driven or user-driven. Regardless of if the shortcut’s context modifications, each static and dynamic shortcuts are pushed by your app.

In instances the place a consumer chooses how they need your app to ship content material to them, reminiscent of with a pinned shortcut, a consumer defines the context.

The next situations present just a few use instances for every shortcut sort:

  • Static shortcuts: utilized for the content material with the constant construction by the lifetime of a consumer’s interplay. Instagram is utilizing it for fast entry to the Posts, Digital camera, or Direct messages.
  • Dynamic shortcuts: used for the actions which can be context-sensitive. They’re made for the actions customers carry out in an app. For instance, if you happen to’re constructing a sport that permits the consumer to begin from their present stage, you must replace the shortcut typically.
  • Pinned shortcuts: used for particular, user-driven actions. The very best instance is pinning a particular web site out of your favourite browser. That is useful as a result of it permits the consumer to carry out a customized motion. For e.g. fast navigation to the particular web site

Though we have now various kinds of shortcuts that cowl all use instances, there are some limitations that we want to concentrate on.

Limitations

Although customers can create as many dynamic shortcuts as they need, most supported launchers show as much as 4 shortcuts at a time.If the app helps dynamic shortcuts, select static shortcuts fastidiously, so there’s nonetheless some house for a consumer to create dynamic ones.

But, for the dynamic shortcuts used with Google Assistant, use Google Shortcuts Integration Library to keep away from the limitation.

Be aware: If you wish to be taught extra about pushing dynamic shortcuts to Google Assistant comply with this Google Codelabs.

In the event you select to not use the Google Shortcuts Integration Library, your app will help a restricted variety of shortcuts at a time.

Typically you’ll must determine whether or not you need extra static shortcuts or let the consumer create dynamic ones.

To find out what number of shortcuts the launcher helps, use getMaxShortcutCountPerActivity() methodology supplied in ShortcutManagerCompat class.

However, in case your app helps pinned shortcuts, you’re secure from these limitations. Launchers don’t have a most variety of pinned shortcuts.

It’s time to leap in on the actions used to handle shortcuts!

Managing App Shortcuts

As you already know, there are three various kinds of shortcuts, and the consumer manages dynamic ones.

The consumer is ready to do a number of actions with the shortcuts:

  • Push: creates a brand new dynamic shortcut.
  • Replace: updates dynamic shortcuts that exist already.
  • Take away: removes dynamic shortcuts from the record.
  • Take away All: removes all dynamic shortcuts.
  • Reordering: provides/updates dynamic shortcuts with the rank property.

Reordering is an motion that occurs as a aspect impact of Push or Replace actions. Entry these motion on the ShortcutManagerCompat API, they usually’re tremendous straightforward to make use of.

Working With Shortcuts

On this part, you’ll discover all of the actions obtainable for managing the app shortcuts and tips on how to implement them.

Creating Static Shortcuts

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

Firstly, within the res bundle, beneath xml subfolder, discover the shortcuts.xml file and open it.

On this file, you’ll discover TODO 1: which you’ll change with the next 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:motion="android.intent.motion.VIEW"
        android:targetClass="com.yourcompany.quicknotes.display.notes.NotesActivity"
        android:targetPackage="com.yourcompany.quicknotes" />
    
    <intent
        android:motion="android.intent.motion.VIEW"
        android:targetClass="com.yourcompany.quicknotes.display.newnote.NoteActivity"
        android:targetPackage="com.yourcompany.quicknotes" />
        
    <!-- 3 -->
    <classes android:title="com.yourcompany.quicknotes" />
    <!-- 4 -->
    <capability-binding android:key="actions.intent.CREATE_NOTE" />
</shortcut>

That is what you’re code does:

  1. Outline shortcut properties like ID, enabled state, icon, lengthy and quick labels.
  2. Outline screens that opens after a consumer selects the shortcut.
  3. Outline class during which the be aware belongs./li>
  4. Outline the aptitude which hyperlinks the shortcut with the built-in intents.

It’s important to outline the shortcut motion correctly. Once you create a shortcut, enable customers to open the display circulate that defines the characteristic they want.

Be aware: Functionality binding pertains to the Constructed-in intents which provides a consumer the choice to entry the characteristic outlined as a shortcut motion by the Google Assistant. You possibly can see tips on how to obtain that right here.

The next move is to present an app directions to create static shortcuts. Go to the manifests folder and open AndroidManifest.xml file and change TODO 2: with the next code snippet:


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

Your shortcut is able to use. Construct and run the app, go to launcher and lengthy press on the app icon. Press the shortcut, and also you’re able to create a brand new be aware!

Instructions how to create a note with Static shortcut

Okay, that was straightforward. Time to maneuver on to the logic of making dynamic shortcuts.

Creating Dynamic Shortcuts

Dynamic shortcuts are somewhat bit difficult however nonetheless very straightforward to implement.

As earlier than talked about, you’ll want to make use of the ShortcutManager API. It’s a part of the Jetpack Libraries that allows you to handle dynamic shortcuts inside your app. It reduces boilerplate code and, most significantly, ensures that shortcuts behave the identical throughout Android variations.

So as to add the performance which can create a brand new dynamic shortcut, open the ShortcutManagerWrapper.kt file and change TODO 3: with these traces of code:


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

Be aware: It’s possible that it’s important to make some imports for the code to work.

You possibly can see {that a} dynamic shortcut acts the identical because the static one. The distinction is that now you’ve logic for making the shortcut extra context-sensitive.

To completely allow creating dynamic shortcuts, change TODO 4: with these two traces of code:


val shortcut = createShortcutInfo(be aware)
ShortcutManagerCompat.pushDynamicShortcut(context, shortcut)

The tactic pushDynamicShortcut(...) will do:

  1. Verify limitation of the utmost variety of shortcuts.
  2. Put together shortcuts relying on the Android Verson.
  3. Take away shortcut with the bottom rank.
  4. Add a brand new one to the highest of the record.

Superior, you’re now able to create your very first dynamic shortcut. Construct and run the app, long-press the created be aware, after which long-press the app icon to indicate the shortcuts.

Instructions how to create a Dynamic Shortcut

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

Updating Dynamic Shortcuts

Updating a dynamic shortcut is similar as creating a brand new one.

Within the QuickNotes app, your shortcut will replace whenever you open an current be aware and modify the content material by urgent the replace motion within the high proper nook.

Subsequent job for you is to implement it so you’ll be able to replace the shortcut when wanted.

Within the ShortcutManagerWrapper.kt file, discover TODO 5: and change it with the next:


addNoteShortcut(be aware)

That’s it! Straightforward, proper? 🙂

Attempt to replace your current be aware. Open it from the shortcut you’ve added, replace it and ensure that the app has up to date the be aware. Now go and examine the shortcut you beforehand created.

You’ll create one other be aware and the shortcut for it. Shut the app, open the shortcut record, and confirm that the bottom-most shortcut is the one you created first.

Creating a second shortcut

Open the primary be aware, change the title, and press replace. In the event you examine the shortcuts, you’ll see that you just’ve modified the order. The one that you just’ve edited is now on the high. Updating the shortcut additionally modifications the shortcut rank.

Update first shortcut to make a change in order

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

Deleting a Dynamic Shortcut

To delete a dynamic shortcut, the very first thing you’ll must know is that if the shortcut already exists.

Discover TODO 6: and change it with the next block of code:


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

Verify if the shortcut with the requested be aware exists within the record of dynamic shortcuts.

Because you don’t need your consumer to have the choice to entry a be aware as soon as it will get deleted from the database or service, you’ll must delete the shortcut too.

Within the ShortcutManagerWrapper.kt discover TODO 7: and change it with these traces of code:


ShortcutManagerCompat.removeDynamicShortcuts(context, listOf(noteId))

Nice, a consumer is now in a position to create, replace and delete a dynamic shortcut, go forward and take a look at it. Construct and run the app, and comply with the following steps with a purpose to examine that all the pieces works:

  1. Create a brand new be aware.
  2. Create a dynamic hyperlink.
  3. Confirm that it’s created by lengthy urgent on the app icon.
  4. Replace the be aware title.
  5. Confirm that it’s up to date within the shortcut record.
  6. Delete the be aware.
  7. Confirm that the shortcut has been deleted from the shortcut record.

Congratulations! You’ve applied the dynamic shortcut characteristic! Now, you’re shifting to the final sort of shortcut.

Creating Pinned Shortcuts

There is just one sort of shortcut left to implement. Making a pinned shortcut is somewhat bit totally different than the others.

Discover TODO 8: and change it with this code snippet:


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

It’s simpler to grasp if it’s damaged down into smaller items:

  1. Confirm that the default launcher helps pinned shortcuts.
  2. Create ShortcutInfo with the quick label, icon and intent which ends up in
    desired Exercise.
  3. Request a pin shortcut which can set off native dialog with the shortcut data on newer Android variations, or create a shortcut immediately on variations under API 26.

Construct and run the app, long-press the be aware, and create your first Fast Notes pinned shortcut.

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

Instructions how to create pinned shortcut

You’re only one press away from the duties you’ll want for that day, procuring cart, or no matter it’s you need to be aware. 🙂

Congratulations! You’re able to make your app extra accessible for the consumer. Take into consideration crucial options you need to present and don’t overlook in regards to the restricted variety of shortcuts.

The place to Go From Right here?

You possibly can obtain the entire mission by clicking Obtain Supplies on the high or backside of this tutorial.

On this article, you’ve realized tips on how to create various kinds of app shortcuts and tips on how to use them.

As talked about earlier, you can also make your app simpler to entry with Google Assistant. You could find right here an superior article on tips on how to create Actions for Google Assistant.

We hope you loved this tutorial. You probably have any questions or feedback, please be part of the discussion board dialogue under!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments