Mark L. Murphy's Blog, page 21

August 19, 2019

"Elements of Kotlin Coroutines Version 0.1 Released

Subscribers now have
access to Version 0.1 of Elements of Kotlin Coroutines,
in PDF, EPUB, and MOBI/Kindle formats. Just log into
your Warescription page to download it,
or set up an account and subscribe!





Originally, I thought that I would just have a chapter on basic coroutines in
Elements of Kotlin. However, I quickly realized that to cover enough
for Android app developers, I would need a lot more than just one chapter.
Elements of Kotlin Coroutines is the result.



As with all my 0.x editions, this one is partially complete, with a number
of placeholders for future chapters. However, it covers the basics of coroutines,
including suspend functions and Flow. It also includes a ���hands-on��� appendix
that walks you through converting a small RxJava-based app to use coroutines.
And most of the samples are in the Klassbook,
so you can run and modify them from the comfort of your favorite Web browser.



This book will get updated every month or two for a while, as I flesh out the
remaining material.

 •  0 comments  •  flag
Share on Twitter
Published on August 19, 2019 06:30

August 13, 2019

Enabling Type Hints in Android Studio

Android Studio offers type hints for Kotlin code. Basically, the IDE adds ���fake���
type declarations where your code does not have them, for places where the compiler
is inferring the type:



Type Hints in Android Studio



The types with the gray backgrounds (e.g., PackageInstaller) are added by the
IDE. Other types (e.g., Uri) are really there in the typed-in code.



This can be handy for helping to ensure that your types are being inferred the
way that you expect. They are also good for educational scenarios, such as
conference presentations, to help make the implicit more
explicit for people spending a limited amount of time in the code.



I got these by default with IntelliJ IDEA, and I wanted to enable them on Android
Studio, particularly for tomorrow���s Android Summit workshop.
This is possible, but you have to dig a bit in Settings
to find them. Or, you can stumble across a helpful Stack Overflow answer.



In Settings > Editor > General > Appearance, you need to check ���Show parameter name hints���:



Type Hints Setting in Android Studio



Then, click the adjacent ���Configure������ button and choose Kotlin from the
���Language��� drop-down in the resulting dialog:



Kotlin Type Hints Configuration in Android Studio



The ���Options��� set of checkboxes are where you indicate the scenarios in which
you want the type hints to show up. The large text field above those checkboxes
are a blacklist, indicating situations where the IDE will skip the type hints,
even if they otherwise would qualify based on your ���Options��� choices.

 •  0 comments  •  flag
Share on Twitter
Published on August 13, 2019 05:16

August 10, 2019

Harmony and Compatibility

Huawei���s rumored operating system
is now less of a rumor and more of a reality. At the Huawei Developer Conference,
they announced Harmony OS,
to be used on the Honor Vision TV and perhaps
the Honor Smart Screen.
They indicated that they would continue to use Android on phones and tablets���
but that is contingent on the current trade ban. As XDA Developers��� Mishaal Rahman noted:




Yet, this new OS is still ���plan B��� for the Chinese technology giant, since Huawei will need to solve the biggest hole in the adoption of Harmony OS: the app ecosystem. Huawei is building up its AppGallery platform as an alternative to the Google Play Store, and this week the company unveiled Huawei Mobile Services as an alternative to Google Play Services. Huawei is in the process of building its own ecosystem, and if the trade ban doesn���t lift by the end of this year or early next year, then Huawei will be forced to switch to Harmony OS for its new devices, including the upcoming Huawei Mate 30 series. In fact, Richard Yu confirmed that the Mate 30 did not receive certification to use Google Play Services before the trade ban was enacted, so Huawei is considering using Harmony OS on the device if the ban isn���t lifted in time.




Little of this shocks me. Even if the trade ban gets relaxed enough that
Huawei can continue with Android internationally, I would expect them to start
shipping Harmony OS devices within China as soon as they decide that it is practical.



However, there were some particularly interesting nuggets in XDA���s coverage
of the announcement, with similarly-interesting follow-on effects.



Open Source?

From the XDA post:




Finally, Huawei announced its plans to open-source Harmony OS, establish an open-source foundation, and create an open-source community for collaboration.




Simply making an operating system open source is insufficient on its own to guarantee
success. If it were, Ubuntu Phone and Firefox OS would be significant players. Unfortunately,
neither ���crossed the chasm���, in part due to lack of manufacturer and carrier
support.



Huawei is a manufacturer, and their moves are likely to result in at least some measure
of carrier support, at least within China. Hence, Harmony OS has a significant advantage
over other attempts to compete with the Android/iOS duopoly.



If Harmony OS actually does wind up in a truly independent foundation, that would make
it easier for other manufacturers to adopt it. On the other hand, it could be that
the foundation is a pleasant fiction, much along the lines of how
the Open Handset Alliance
turned out. And, if you do not recognize the name ���the Open Handset Alliance������ well,
that���s not surprising. It is the closest thing that Android has had to a foundation
for overseeing it. Needless to say, Android is very firmly in Google���s control,
and it remains to be seen how Huawei handles Harmony OS in this regard.



App Compatibility?

From the XDA post:




Developers will be able to use Huawei���s ARK Compiler to compile code from multiple languages like C/C++, Java, and Kotlin for Harmony OS. Huawei will be providing an IDE to support app development across multiple device types, including televisions, car kits, smart speakers, smartphones, smartwatches, and more��� Harmony OS is not compatible with Android apps out-of-the-box, confirms Richard Yu, CEO of Huawei Consumer Business Group. That means you won���t be able to merely side-load any Android app of your choosing. In a press conference, Mr. Yu says that app developers will have to make ���small changes��� to their apps in order to compile them to run on Harmony OS. He states that it is ���very easy��� to transfer Android apps to Harmony OS.




All of this information comes from media events, so we have to assume there is
some amount of ���spin��� here. Certainly, if Harmony OS supports Java and Kotlin,
it would be easier to migrate an Android app to Harmony OS than, say, iOS. However,
���easy��� is quite a high hurdle to reach in terms of the level of effort of app
migration.



One way that it could be ���easy��� is if they take the approach that BlackBerry
did with their early Android efforts. Before BlackBerry retired BlackBerry OS and
moved to Android, they had an Android runtime for BlackBerry OS. Developers could
use some tools to convert an Android APK into a different file (BAR), and a BAR
could be distributed to a BlackBerry OS device. This approach failed for BlackBerry
for several reasons, none of which would preclude Huawei from trying and perhaps
succeeding. It might still require a fair amount of work to port an Android
app to be a native Harmony OS app, though, if this is Huawei���s approach.



Another possibility for this being ���easy��� is if Huawei
basically adopts the Android SDK. Basically, they would have their own SDK
with the same class structure, perhaps with some cosmetic changes (e.g., you
have to convert android. to harmony. in packages). I would be somewhat surprised
if they went this route, as it ties them to Google and Android more than they
might like. It also raises interesting parallels to the Oracle v. Google series
of lawsuits, with Huawei in the role of Google.



Yet another possibility is some sort of a converter, that can take code that
makes Android SDK calls and convert it to making Harmony OS SDK calls instead.
That would be difficult to pull off, since it has to convert both app code
and libraries. But the Jetifier (sorta) accomplished it for converting Android Support Library
references to AndroidX ones, so I certainly cannot rule it out.



Regardless, we would need more details to be able to judge whether moving an
app to Harmony OS will really be ���easy���.



Ratcheting Interest?

However, Huawei does not need getting an app over to Harmony OS to be easy.
It simply needs such a move to be compelling.
Huawei sells more devices than does Apple. If Apple can convince developers to
write apps for iOS, Huawei should be able to convince developers to write apps
for Harmony OS.



The catch is that Apple already has a large installed base of iOS users. Huawei
has zero users of Harmony OS today. And unless Huawei has better success than a
lot of manufacturers have had with smart TVs and smart displays, they will still
have relatively few users by the time that they start shipping Harmony OS phones. Huawei will
only have success selling Harmony OS phones if there is a critical mass of
apps for those devices.



However, once again, Huawei has an advantage: initially, they might not need
the world���s apps. They might only need China���s apps. One imagines that they can
broker deals with major Chinese app brands, and a good developer outreach program
can help pull in apps from ���the long tail��� of the app distribution curve. If they
can get a reasonable Chinese app catalog at the outset, success can breed success, with
Harmony OS device sales convincing more Chinese developers to port their apps to
Harmony OS, helping to improve sales of those devices, etc.



If Huawei is able to convert their existing domestic smartphone sales over to Harmony OS,
non-Chinese developers already distributing to China would need to take notice and
consider Harmony OS ports of their own. This could accelerate if Huawei is open enough
with Harmony OS to convince some other manufacturers to adopt it. And it would
accelerate if Huawei starts selling Harmony OS devices outside of China.



You will know when Huawei thinks that they have succeeded: when they start offering
support for converting Harmony OS apps to Android, believing that there is enough
���Harmony first��� development going on to warrant that kind of support.



What Now?

If you write apps for Android TV, you might peek at the Honor Vision TV and Harmony OS,
to see if there are any ���first-mover��� sorts of advantages that you can
leverage.



For Chinese developers, pay very close attention to what Huawei does. Even if
you do not plan on shipping an app for TVs, you might experiment with Harmony OS
on a TV, just to get a better sense for what Harmony OS development is like.
That will help you decide how to react if and when Huawei starts selling
Harmony OS phones.



And, if you are a ���bleeding edge��� sort of developer anyway, Harmony OS
represents an interesting opportunity, comparable to those poking at Google���s
Fuchsia right now. Fuchsia advocates might scoff at that notion, and right now,
Fuchsia is ahead simply by being publicly available, if not on shipping production
hardware. However, I think that Huawei has an easier path to 250 million
Harmony OS devices than Google does for getting to 250 million Fuchsia devices.
Huawei already sells more devices than that, whereas Google would need to convince
other manufacturers to distribute Fuchsia-powered devices.
Huawei still has to execute, and there are any number of ways that Harmony OS
could wind up being ���a whole lot of nothing���. After all, Samsung���s Tizen was
in a similar position and has not had much success with developers or mobile devices.



For everyone else��� check back in 2020, and let���s see where Huawei and Harmony
OS are.

 •  0 comments  •  flag
Share on Twitter
Published on August 10, 2019 17:13

August 8, 2019

Room and Flow!

At next week���s Android Summit, I will be leading a
workshop, ���From RxJava to Coroutines���. The idea is that we would take a small
Retrofit-and-Room app and rewrite it to use coroutines rather than RxJava.



When writing the app, though, I realized that Room did not yet support channels
or flows. The app relied upon Room���s invalidation tracking to deliver fresh results
when the database changed. The only way that I could get a Flow was to have
the DAO use Flowable, then use coroutines��� Reactive Streams support to convert
the Flowable to a Flow. This worked, but it meant that I had leave RxJava
in the app, to get the Flowable.



And so I prayed to Saint Yi��it
that Room would get Flow support in time for the Summit.



Yesterday, my prayers were answered! Room 2.2.0-alpha02 advertised Flow
support, and in light testing, it works as expected! So now your DAO can have
stuff like:



@Query("SELECT * FROM observations ORDER BY timestamp DESC")
abstract fun loadFlow(): Flow<List<ObservationEntity>>


���and you can consume that Flow from within your favorite coroutine builder
(e.g., launch()) or a suspend function.



Of course, not only is this Room version an alpha, but Flow itself is still
in a release candidate state right now. Experimenting with this stuff is fine,
but be careful about shipping production code using this. At least wait until the beta.



But, if you are ���coroutines-curious��� and are attending the Android Summit,
come to my workshop, and I���ll show you how to nuke RxJava from orbit.





UPDATE: Many thanks to Dany Aguacate,
who implemented the Flow support in Room!

 •  0 comments  •  flag
Share on Twitter
Published on August 08, 2019 07:25

August 6, 2019

ACTION_OPEN_DOCUMENT: May Not Be Read-Write

While I think that the death of external storage in Android Q
is a good move overall, and while I think that
the Storage Access Framework is OK for basic scenarios,
there will be ���growing pains���.



One of those is the realization that not all document providers play fair.



For example, you might want to write to a user-supplied document. So, you
use ACTION_OPEN_DOCUMENT to request that the user choose a document. You
take the Uri that you get and eventually you call openOutputStream()
on a ContentResolver, passing in that Uri. You then try to write content
out to that stream, to be able to store that content in the user-chosen document.



That might not work.



For example, if the user chose the ���Audio��� category in the Storage Access Framework
UI, you will crash on your openOutputStream() call, with an IllegalArgumentException and
an error message of ���Media is read-only���.



The tactical reason for the crash is that MediaDocumentsProvider ��� the implementation
behind that ���Audio��� option ��� universally rejects write access:



@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
final Uri target = getUriForDocumentId(docId);

if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}

// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}


And, in their document metadata, they correctly indicate that the document is not writable
(i.e., they do not have FLAG_SUPPORTS_WRITE in the document���s flags).



The strategic problem, though, is that we have no means of telling ACTION_OPEN_DOCUMENT
that we want a Uri that we can write to
. As a result, ACTION_OPEN_DOCUMENT will happily let
the user choose a piece of content that we cannot use. This gives the user a poor
experience, as they will now get some cryptic error message from the app about not
being able to write to that location.



This is a framework problem, so we are stuck with this implementation for the time
being. With luck, and with your help, perhaps this gets addressed in the Android R timeframe,
so that in several years, this problem will be behind us. Simply put:
we need some
way to stipulate whether we need read-write access to the content in ACTION_OPEN_DOCUMENT,
with the Storage Access Framework UI limiting the user to read-write documents.
The DocumentsContract.Document API already has FLAG_SUPPORTS_WRITE, so the
Storage Access Framework UI has the information necessary to do the filtering.



In the short term, though, we are stuck with a Uri that may or may not work
for writing.



Ideally, we would use DocumentFile to determine if we can write to a document.
Unfortunately, it does not correctly examine the flags,
so its canWrite() method returns true for a document in which we do not have
write access. Instead, you need around 100 lines of code to check to see
whether the flags for this document contain FLAG_SUPPORTS_WRITE, based on the
the DocumentsContractApi19 implementation of canWrite().



One way or another, if you intend to write to a Uri that you get from
ACTION_OPEN_DOCUMENT, confirm that you actually can write there first, before
trying to use the Uri.

 •  0 comments  •  flag
Share on Twitter
Published on August 06, 2019 09:31

August 5, 2019

���Elements of Kotlin Version 0.2 Released

Subscribers now have
access to Version 0.2 of Elements of Kotlin,
in PDF, EPUB, and MOBI/Kindle formats. Just log into
your Warescription page to download it,
or set up an account and subscribe!



There is one new ���main��� chapter, covering: extension functions.
Thera are several more ���Kotlin, WTF?��� short chapters
on advanced syntax. Those cover:








Operator overloading




Infix functions




Destructuring declarations





Also, the chapter on Java interoperability was rewritten.



The biggest change is that most of the samples in the book were put into the Klassbook,
a Web site where you can run Kotlin snippets in your browser. Samples that appear
in the Klassbook have links to the particular Klassbook page underneath the snippets
in the chapters. Or, visit the Klassbook site directly
and browse through the various lessons.



Unfortunately, switching to the Klassbook means that most sections in the book
have some changes. As a result, most of the Table of Contents shows up in bold-italic,
and there are lots of changebars in the book itself.



Oh, and there were a lot of bug fixes.

 •  0 comments  •  flag
Share on Twitter
Published on August 05, 2019 06:35

"Elements of Kotlin Version 0.2 Released

Subscribers now have
access to Version 0.2 of Elements of Kotlin,
in PDF, EPUB, and MOBI/Kindle formats. Just log into
your Warescription page to download it,
or set up an account and subscribe!



There is one new ���main��� chapter, covering: extension functions.
Thera are several more ���Kotlin, WTF?��� short chapters
on advanced syntax. Those cover:








Operator overloading




Infix functions




Destructuring declarations





Also, the chapter on Java interoperability was rewritten.



The biggest change is that most of the samples in the book were put into the Klassbook,
a Web site where you can run Kotlin snippets in your browser. Samples that appear
in the Klassbook have links to the particular Klassbook page underneath the snippets
in the chapters. Or, visit the Klassbook site directly
and browse through the various lessons.



Unfortunately, switching to the Klassbook means that most sections in the book
have some changes. As a result, most of the Table of Contents shows up in bold-italic,
and there are lots of changebars in the book itself.



Oh, and there were a lot of bug fixes.

 •  0 comments  •  flag
Share on Twitter
Published on August 05, 2019 06:35

July 29, 2019

���Elements of Android Q��� Version 0.5 Released

Subscribers now have
access to Version 0.5 of Elements of Android Q,
in PDF, EPUB, and MOBI/Kindle formats. Just log into
your Warescription page to download it,
or set up an account and subscribe!



Since Q Beta 5 did not change any APIs from Q Beta 4, there were few changes
in this update.



A short new chapter was added on how to use PackageInstaller,
now that ACTION_INSTALL_PACKAGE is deprecated.



Most of the remaining changes are bug fixes.



I am expecting two more updates to this book:





One when Android Q ships as Android 10 to existing devices,
to make any tweaks based on the final
shipping versions plus perhaps add a bit more of new material




One when the next generation of Pixel devices ships, to cover any Android Q
things that are at least initially unique to those devices

 •  0 comments  •  flag
Share on Twitter
Published on July 29, 2019 05:19

"Elements of Android Q" Version 0.5 Released

Subscribers now have
access to Version 0.5 of Elements of Android Q,
in PDF, EPUB, and MOBI/Kindle formats. Just log into
your Warescription page to download it,
or set up an account and subscribe!



Since Q Beta 5 did not change any APIs from Q Beta 4, there were few changes
in this update.



A short new chapter was added on how to use PackageInstaller,
now that ACTION_INSTALL_PACKAGE is deprecated.



Most of the remaining changes are bug fixes.



I am expecting two more updates to this book:





One when Android Q ships as Android 10 to existing devices,
to make any tweaks based on the final
shipping versions plus perhaps add a bit more of new material




One when the next generation of Pixel devices ships, to cover any Android Q
things that are at least initially unique to those devices

 •  0 comments  •  flag
Share on Twitter
Published on July 29, 2019 05:19

July 24, 2019

Presenters, Please Use Bigger Fonts!

A decent chunk of the conference presentations that I see have unreadable
content, because the fonts are too small. If designing UIs for TVs is
���the ten-foot view���, designing presentation materials is ���the hundred-foot view���
(or perhaps ���the thirty-meter view���). If your material cannot be read,
it does not matter how ���magic��� your in-slide ���moves��� were.



My rules of thumb:





Bullets and other prose should be readable when viewed on a smartphone held at arm���s length




Code (in-slide, in-IDE, etc.) should be readable when viewed on a smartphone held
at a more natural distance





For a live presentation, you do not necessarily know how big the screen will
be and how far away the attendee might be sitting. If the event is being held at
a hotel, for example, you might have fairly deep rooms with modest-sized screens,
so people at the back have a much smaller effective screen than those at the front.
Even if the event is being held in a dedicated conference space, the main projectors
might be malfunctioning, so you might be stuck using some backup system that is
not designed for the seating space.



Plus, nowadays, the live attendees represent the tip of your audience iceberg.
Most presentations get posted online as videos on YouTube, Vimeo, etc., and many
more people will watch those than will be in the event itself. People
viewing those videos might well be viewing them on a smartphone. So, ensuring that
your materials are readable on a smartphone has direct relevance.



Also bear in mind that videos might not be showing your presentation materials
at full size. For example, they might be showing video of you alongside the
materials, or have persistent event branding consuming some screen space.



For slides, it is easy enough to test ahead of time ��� just use your phone. For code being shown
outside of slides, such as a live look at an IDE, jack up the font size and test
it at the presentation venue to confirm that it is large enough for your circumstances.



But, one way or another, make sure your words are big enough to be read. Your
presentation attendees and viewers will thank you for it.

 •  0 comments  •  flag
Share on Twitter
Published on July 24, 2019 06:43