Reader small image

You're reading from  Expert Delphi - Second Edition

Product typeBook
Published inFeb 2024
Reading LevelExpert
PublisherPackt
ISBN-139781805121107
Edition2nd Edition
Languages
Right arrow
Authors (2):
Marco Cantù
Marco Cantù
author image
Marco Cantù

Marco Cantù is an experienced Delphi expert, who started working with the product since its introduction in 1995. He is currently working as a Product Manager for RAD Studio at Embarcadero Technologies, an Idera company. Prior to that, Marco was a Delphi trainer and consultant for Wintech Italia. Over the years, Marco has written 20 books on Delphi, from the classic Mastering Delphi series to the recent Object Pascal Handbook. Marco has been a speaker at many Delphi and programming conferences worldwide, including over 10 Borland US Conferences, the Software Development Conference, Borland European conferences, EKON (Germany), DCon (UK), Conference to the Max (Holland), DelphiTage, the Italian Delphi Day, and a few editions of Delphi Developer Days. Marco is based in Italy.
Read more about Marco Cantù

Paweł Głowacki
Paweł Głowacki
author image
Paweł Głowacki

Paweł Głowacki was Embarcadero's European Technical Lead for Developer Tools. Previously, Paweł spent over 7 years working as a senior consultant and trainer for Delphi within Borland Education Services and CodeGear. Apart from working with Embarcadero customers across the region, he represented Embarcadero internationally as a conference and seminar speaker. Paweł passed away in mid-December 2017, but he is alive in the hearts of the Delphi developers community, worldwide.
Read more about Paweł Głowacki

View More author details
Right arrow

Working with Mobile Operating Systems

In this chapter, we are going to move from playing with FireMonkey to building useful cross-platform apps that access mobile hardware and operating system features with high-level components, abstracting away the underlying mobile APIs.

This chapter will cover the following topics:

  • James Bond’s toy
  • What am I running on?
  • The life of an app
  • Sensing the world
  • Taking photos
  • Using share sheets
  • Camera, action!
  • Notify me!
  • Navigating the web
  • Delphi language bridges

The objective of this chapter is to learn how to create native cross-platform apps that use different frameworks and functionality provided by mobile operating systems.

James Bond’s toy

Contemporary mobile hardware does not significantly differ in capabilities from secret agent James Bond’s gadgets from just a few years ago. Your mobile phone is equipped with all kinds of sensors that you can use in your mobile apps, including for location, orientation, motion, and ambient light, along with a microphone, speakers, camera, and plenty of other hardware you can control.

An app is immersed in the given operating system it runs on, which is in charge of every aspect of an app’s execution. In your code, you can respond to different app life cycle events such as startup, switching to background execution, moving back to the foreground, and app termination. Ultimately, this interaction is about responding to different events sent by the operating system and invoking operating system APIs. The FireMonkey library encapsulates access to common mobile operating system functionality through specialized types, classes, and components, but...

What am I running on?

Building apps for multiple operating systems from the very same source code imposes unique challenges. Your code might be running on iOS or Android. It only takes two mouse clicks to recompile your app for a different target. Certain features might exist on a given platform and not be there on other platforms. Going further, new functionality is constantly being added to platforms, so you may want to know on which platform and operating system version your app is being executed.

This can be done with the TOSVersion record type defined in the System.SysUtils unit. This record has a class constructor that instantiates all of its fields. The TOSVersion record defines the internal TArchitecture and TPlatform enumerated types and corresponding public class properties to read the current operating system architecture, platform, name, and major and minor numbers.

We can very quickly build a simple app that will log in a memo all of the information from the TOSVersion...

The life of an app

An app is not a lonely island. It is always executed by the operating system within the bounds that it imposes. Depending on the type of the app, we could be interested in responding to different application life cycle events that the operating system sends to it. Every operating system has a slightly different app life cycle model, but in the case of mobile platforms, the trickiest part is properly handling the situation when our apps move from foreground execution to the background and back again.

FireMonkey provides a common abstraction for handling the application life cycle through different types of application events defined in the FMX.Platform unit, as shown in the following code:

type
  TApplicationEvent = (FinishedLaunching, BecameActive,
    WillBecomeInactive, EnteredBackground, WillBecomeForeground,
    WillTerminate, LowMemory, TimeChange, OpenURL);

If we want to receive the app life cycle events...

Sensing the world

Unlike desktop computers, mobile devices have a rich set of sensors. They obviously have cameras, but they also generally have Global Positioning System (GPS), a compass, a gyroscope, possibly light detectors, a torch light, at times humidity and pressure sensors, and even more.

Delphi comes with a System.Sensors unit, where all kinds of possible sensors are defined. Similar to the FMX.Platform unit, the System.Sensors unit also has IFDEF compiler directives in its implementation uses clause for different platforms, including Android and iOS.

In the library, there is the main TSensorManager class that acts as a gateway to all sensor information. The class has a class property called Current: TSensorManager, which is used to expose a global object including all sensor information.

At the top of the System.Sensors unit you can find a TSensorCategory enumerated type, which provides the top-level categorization of all possible types of sensors:

type
 ...

Taking photos

There are many occasions when it is useful to be able to take a photo from an app. The programming model is very easy, but it is not the TCamera component that you need to use. In FireMonkey, taking photos is achieved by executing a special take photo from camera action. The following steps take you through building a demo based on that action:

  1. Create a new blank multi-device FireMonkey application. Save the main form’s unit as uFormCam and the project as CamApp, and change the Name property of the form to FormCam.
  2. Change the Style setting in the combobox above the form to iOS or Android.
  3. Drop a TImage component on the form, rename it to ImagePhoto, and align it to Client.
  4. Add a TToolBar component and drop a TSpeedbutton onto the ToolBar1 control. Change its Name to SpdbtnTakePhoto and the button’s Stylelookup property to cameratoolbutton, align it to Left, and adjust the width so it becomes a square.
  5. Drop a TActionList component...

Using share sheets

Our app is coming along nicely, but it is not very useful. The photo is displayed in the form, but goes away when we stop the app or take another photo. It is a typical functionality in mobile operating systems to be able to share things with other installed apps. For example, we might want to share a photo on social media or send it by email. This can be achieved through share sheets that are also available through actions.

The term share sheet refers to the ability of apps to share data with other apps, such as the common use case of sharing an image with a social network application. We can see this in action by extending our existing app from the previous section as follows:

  1. Drop another TSpeedButton on the toolbar. Rename it to SpdbtnSharePhoto, change its StyleLookup property to actiontoolbutton, adjust its width, and align it to Right.
  2. Expand its Action property in the Object Inspector, and through the context menu, add the TShowShareSheetAction...

Camera, action!

If we can take photos with action components, as we have done in the previous sections, then what is the purpose of the TCameraComponent component that can be found in the Additional category on the Tool Palette? A quick answer could be that it is the way to switch on and off the flashlight that most phones are equipped with. A more elaborate answer would be that it can be used to take videos.

The FireMonkey library has generic support for handling the many types of cameras available across different hardware. The actual access to the underlying video hardware is done through the non-visual TCaptureDeviceManager class defined in the FMX.Media unit.

The programming model follows the same pattern as in other platform services. The class itself is abstract, but it has a Current public class property that returns a reference to the actual TCaptureDeviceManager implementation on a given platform. The TCaptureDeviceManager class has a Devices array property where we...

Notify me!

One of the most common ways of attracting a mobile device user to a particular app is to display a notification. When a new email arrives or a friend posts something on social media, we are typically alerted with a notification. Clicking on it displays the app that sent the notification.

Delphi provides a TNotificationCenter component that can be used to display and react to notifications. A very common use case is displaying a number next to the app icon for the count of new notifications. This can also be used for unread emails and missed calls:

  1. Create a new, blank, multi-device app. Save the main form as uFormNotify and the project as NotifyMe.
  2. Add a toolbar with a label aligned to Client with text reading Delphi Notifications.
  3. Now drop a TNotificationCenter component on the form. As a side effect, the System.Notification unit will be added to the form’s uses clause.
  4. The first class defined in this unit is TNotification, which is used as...

Delphi language bridges

So far, we have seen how to access cross-platform implementations of services including sensors, address books, maps, and other features we have covered so far in this chapter. All of them come out of the box with Delphi. Luckily, Delphi comes with the source code, so it is possible to inspect how Delphi itself is accessing the underlying mobile APIs on Android and iOS. All supported operating systems are different and there are different ways of accessing their raw APIs.

The Delphi language offers “bridges” to call native platforms APIs on all supported platforms, although the technique varies for each target operating system. While in most cases, this is not required, it’s important to know that unlike other cross-platform development tools that offer only a subset of the underlying platform features, with Delphi you have the full power of the device and the entire API available to you. Only, programming for the API takes a bit more...

Summary

In this chapter, we have learned how to work with different platform functionalities provided by the two mobile operating systems, Android and iOS. While the two are quite different, most of the core concepts are the same. We can use high-level components in the FireMonkey library and their cross-platform abstractions. This way, we can just recompile our projects for both OSs with the same source code.

Toward the end of the chapter, we also explored what you need to do to call platform APIs not wrapped by the FireMonkey library. This is significantly more work, but it’s important to realize that it is possible, unlike in cross-platform mobile development tools, which offer a defined set of features without the ability to add others.

While the focus on mobile is particularly relevant, in the next chapter, we’ll spend a little time focusing on desktop, as FireMonkey also supports Windows, macOS, and even Linux (via an add-on library). We’ll cover some...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Expert Delphi - Second Edition
Published in: Feb 2024Publisher: PacktISBN-13: 9781805121107
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Marco Cantù

Marco Cantù is an experienced Delphi expert, who started working with the product since its introduction in 1995. He is currently working as a Product Manager for RAD Studio at Embarcadero Technologies, an Idera company. Prior to that, Marco was a Delphi trainer and consultant for Wintech Italia. Over the years, Marco has written 20 books on Delphi, from the classic Mastering Delphi series to the recent Object Pascal Handbook. Marco has been a speaker at many Delphi and programming conferences worldwide, including over 10 Borland US Conferences, the Software Development Conference, Borland European conferences, EKON (Germany), DCon (UK), Conference to the Max (Holland), DelphiTage, the Italian Delphi Day, and a few editions of Delphi Developer Days. Marco is based in Italy.
Read more about Marco Cantù

author image
Paweł Głowacki

Paweł Głowacki was Embarcadero's European Technical Lead for Developer Tools. Previously, Paweł spent over 7 years working as a senior consultant and trainer for Delphi within Borland Education Services and CodeGear. Apart from working with Embarcadero customers across the region, he represented Embarcadero internationally as a conference and seminar speaker. Paweł passed away in mid-December 2017, but he is alive in the hearts of the Delphi developers community, worldwide.
Read more about Paweł Głowacki