Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

For the More Curious: StrictMode


In PhotoAdapter.onBindViewHolder(...), you would replace the existing code with a call through to
the new bindGalleryItem(...) method.


Picasso does all of the work of ThumbnailDownloader (along with the
ThumbnailDownloader.ThumbnailDownloadListener callback) and the image-related work of
FlickrFetchr. This means you can remove ThumbnailDownloader if you use Picasso (you will still
need FlickrFetchr for downloading the JSON data). In addition to simplifying your code, Picasso
supports more advanced features such as image transformations and disk caching with minimal effort
on your part.


You can add Picasso to your project as a library dependency using the project structure window, just as
you have done for other dependencies (like RecyclerView).


A downside of Picasso is that it is intentionally limited so that it can remain small. As a result, it
cannot download and display animated images. If you have that need, then check out Google’s Glide
library or Facebook’s Fresco library. Between the two, Glide has the smaller footprint, but Fresco has
the edge on performance.


For the More Curious: StrictMode


There are some things you simply should not do in your Android app – mistakes that lead directly to
crashes and security holes. For example, executing a network request on the main thread will probably
result in an ANR error in poor network conditions.


Instead of Android happily allowing you to invoke a network request on the application’s main thread,
you get a NetworkOnMainThread exception and log message instead. This is because of StrictMode,
which noticed your mistake and helpfully let you know about it. StrictMode was introduced to help
you detect this and many other programming mistakes and security problems in your code.


Without any configuration, networking on the main thread is guarded against. StrictMode can also
help you detect other mistakes that could drag down your application’s performance. To enable all of
StrictMode’s recommended policies, call StrictMode.enableDefaults() (developer.android.com/
reference/android/os/StrictMode.html#enableDefaults()).


Once StrictMode.enableDefaults() has been called, you will hear about the following violations in
Logcat:



  • networking on the main thread

  • disk reads and writes on the main thread

  • activities kept alive beyond their natural lifecycle (also known as an “activity leak”)

  • unclosed SQLite database cursors

  • cleartext network traffic not wrapped in SSL/TLS


For custom control over what happens when policy violations occur, you can configure the
ThreadPolicy.Builder and VmPolicy.Builder classes. You can specify whether you want an
exception to occur, a dialog to be shown, or just a log statement to alert you to the violation.

Free download pdf