Android Pocket Primer [Notes]

2020-12-30

A collection of random notes from the book Android Pocket Primer. Notes are not exhaustive and very much sporadic.

Chapter 1 - A quick introduciton to Android

  • Dalvik versus ART

  • R.java = basically a java-based “binding” class with static constants that reference the UI in xml activity_main.xml

  • AndroidManifest.xml = master control file
  • activity_main.xml = configuration of UI elements
  • strings.xml = contains text strings that are referenced in app
  • dimens.xml = contains dimension values (e.g 16dp)

  • R.java references all resources

  • Constraint-based layouts are only one-level deep

  • Android prefix is a namespace prefix (in xml file)

  • Android prefix is used for attributes from Android SDK itself.
  • App prefix is often associated with a support library

  • The res/anim subdirectory contains tween animations
  • The res/drawable subdirectory contains frame animations
  • The res/drawable subdirectory also contains bitmaps
  • The res/color subdirectory contains color resources
  • The res/layout subdirectory contains layout files
  • The res/menu subdirectory contains application menus
  • The res/raw subdirectory contains audio/video files
  • The res/values subdirectory contains string definitions
  • The res/xml subdirectory contains XML-based assets

Android Activities

  • Android activity == a screen on a device
  • Run on a single UI thread

  • OnCreate() entry point of the app
  • The onCreate() method invokes its corresponding method in its super-class, followed by the setContentView() method that references an XML file that contains layout details for the view. This method is passed an integer value (automatically generated for you) called R.layout. activity_main (“R” is an abbreviation for “resources”) that is associated with the XML layout file.

  • every UI component is a subclass of the View component.

Intents

  • Activities are independent of each other - One activity cannot directly access instance data of another activity

  • Android intent is essentially a “messaging” object that can request action from another component. Use an intent to start an activity, Service or broadcast reciever.

  • Types of intents, Explicit, implicit, directed vs broadcast

  • Intent Filter is a set of information that defines a specific action; the XML element specifies the data to be acted upon, and the XML element specifies the component that will perform the action.

Chapter 2 - Design and UI Controls

  • Every UI Component is also a view as every UI component is a subclass of the Android View class

  • Android adapters are connected to data sources (such as a database or array)

  • A- dapter is an instance of a class that implements the Adapter interface whereas an adapter view is an instance of a class that extends the abstract adapterview class

Adapter is “link” between dataset and adapter view

  • The purpose of an adapter is twofold: to retrieve data from the data set and to generate View objects based on that data. After the data is retrieved, the adapter view (that is bound to the adapter) is populated with those generated View objects.

  • Units of measure in android
  • in (inches),
  • mm (millimeters),
  • pt (points),
  • dp (density),
  • sp (scale pixels),
  • px (pixels)

  • The dp unit of measure refers to density-independent pixels, which is sometimes abbreviated as dip . This unit of measurement is based on a “baseline” of 160dpi . For example, 1 dp on a 320dpi device is actually two pixels.

  • The sp unit of measure is an abbreviation for scale-independent pixels. Use the sp unit of measure for font sizes. The px unit of measure is the actual screen pixels

  • DO NOT USE ABSOLUTE POSITIONING - density and resolution are not necessarily linked

  • If you define the dimensions of a PNG file in terms of the unit px , that PNG file will be displayed as a small image on screens with higher densi- ties. However, if you define the dimensions of a PNG file in terms of the unit dp (“device independent pixels”) that PNG file will be displayed in the same size, regardless of the density or the physical dimensions of a screen on a mobile device.

  • Whenever users rotate an Android device, Android destroys and then rec- reates the Activity class, which causes the onCreate() method to be executed again. Hence, the values of variables are reinitialized, and so intermediate values are lost.

  • Use savedInstanceState
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putInt("clickCount", clickCount);
super.onSaveInstanceState(outState);
}
in oncreate 
if(savedInstanceState != null)
{
clickCount = savedInstanceState.getInt("clickCount");
}
  • OnClickListener is the interface you need to implement and can be set to a view in Java code. On one hand, OnClickListener is what waits for someone to actually click, whereas onClick determines what happens when someone clicks.

  • An Android application executes the following methods (in the follow- ing order) during the lifecycle of the application: onCreate() , onRe- start() , onStart() , onResume() , onPause() , onStop() , and onResume() .

  • onCreate == when created / init
  • onDestroy == ~Class

  • The onPause() method is invoked when an Activity must be paused (such as reclaiming resources).

  • Android invokes the onPause() method before terminating an application, so the onPause() method is the logical place to include data-saving code.

  • The onRestart() method is invoked when an Activity is being restarted.

  • The main culprits for potential memory leaks are listed here:
  • Inner classes
  • Anonymous classes
  • Static activities or views
  • Subclasses of AsyncTask
  • Handlers
  • Threads
  • Timer tasks
  • Sensor manager

  • https://medium.com/freenet-engineering/memory-leaks-in-android- identify-treat-and-avoid-d0b1233acc8#.y2duxl6dw

  • http://blog.nimbledroid.com/2016/05/23/memory-leaks.html

Chapter 3 - Additional UI Controls

  • Think of a Fragment as a piece of an application’s user interface or behavior that can be placed in an Activity.

  • Activity s and Fragments have a one-to-many relationship: a best prac- tice is to use at most four or five fragments in an Activity (but nothing will stop you from using many more).

  • In general, use an Activity to launch existing Android resources (video player, browser, and so forth), and use a Fragment to modify the UI components of application.

  • Static fragments, placed in activity layout and never change
  • Dynamic framework Fragments
  • Dynamic support Fragments from the v4 support library, which work with AppCompatActivities

  • Fragment, fragmentManager, fragmentTranscation

  • The Recycler view

Chapter 4 - Graphics and Animation

  • The Android package android.graphics provides low-level graphics tools such as canvases, color filters, points, and rectangles that let you handle drawing to the screen directly.

  • Hex values for a color and opacity in Android are of the following form: 0xAARRGGBB .

  • Creating Custom Views or SubViews. The key idea involves defining a subclass of the Android View class and then putting your custom code in the onDraw() method of the subclass.

  • Canvas 2D Transformations

Chapter 5 - User Gestures

  • boolean onTouchEvent(MotionEvent event)
  • boolean onDoubleTap(MotionEvent event)
  • boolean onDoubleTapEvent(MotionEvent event)
  • boolean onSingleTapConfirmed(MotionEvent event)
  • boolean onTouch(View v, MotionEvent event)
  • void onClick(View v)
  • boolean onKey(View v, int keyCode, KeyEvent event)
  • boolean onDown(MotionEvent event)
  • void onLongPress(MotionEvent event)
  • boolean onScroll(MotionEvent e1, MotionEvent e2,…)
  • void onShowPress(MotionEvent event)
  • boolean onSingleTapUp(MotionEvent event)

Chapter 6 - Sensors and Multimedia

  • Android code for sensors starts by instantiating a sensor manager, followed by some code that involves a particular sensor.

  • Checking prescence of a gyroscope

    private SensorManager mSensorManager;
    private Sensor mSensor;
    // some details omitted
    mSensorManager = (SensorManager)
    getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.
    TYPE_GYROSCOPE)
    

Android Permissions

  • Android classifies permissions into three types: normal, dangerous, and system permissions.

  • Normal permissions are those that do not access the file system or built-in sensors, such as those that request access to network state, wifi state, and Bluetooth.

  • “dangerous” permissions are permissions that enable applica- tions to access sensors or to access the file system of a device. A par- tial list of dangerous permissions includes: Calendar, Camera, Contacts, Location, Microphone, Phone, Sensors, SMS, and storage.

  • System permissions include SYSTEM_ALERT_WINDOW and WRITE_ SETTINGS . Applications that require these permissions must declare them in the manifest, and also send an intent requesting author- ization from users.

  • If the device is running Android 6.0 or higher, and the targetSdkVer- sion is 23 or higher, the application will request permissions from the user at runtime. However, since users can revoke the permissions at any time, the application needs to check whether it has the necessary permis- sions every time it runs.

Chapter 7 - Data storage and File I/O

Android Conext

  • The Android package android.app contains the abstract class Context that has numerous concrete subclasses, such as Activity , ApplicationContext , and Intent .

  • Android Context provides information about an Activity or Application to newly created components

  • View.getContext() : returns the context the view is currently run- ning in (usually the currently active Activity )

  • Activity.getApplicationContext() :returns the context for the entire application (the process that contains all the active Activity s).

  • Use this method instead of the current Activity con- text if you need a context tied to the lifecycle of the entire appli- cation, not just the current Activity .

  • The application context enables you to access resources that are shared between Activity instances.

  • Content Provider in Android allows unrelated applications to share data based solely on the names of the tables and fields in the data.

  • An Android ContentProvider (part of the android.content package) shares content among applications. Android built-in ContentProvider s include Contacts and the MediaStore , both of which are in the android.provider package.

Data Storage

  • Shared Preferences is useful for storing private primitive data in key- value pairs.

  • Internal Storage can be used for storing private data on the device memory.

  • External Storage is handy for storing public data on shared external storage.

  • SQLite Databases are convenient for storing structured data in a pri- vate database.

  • Network Connection is good for storing data on the Web with your own network server.

  • Keep in mind that the SharedPreferences APIs are only for reading and writing key-value pairs.

  • By contrast, the Preference APIs are useful for creating a user interface for application settings.

Loaders

  • Loaders load data asynchronously and notify listeners when the results are ready. Loaders involve the following Android classes:

  • LoaderManager
  • LoaderManager.LoaderCallbacks (interface)
  • Loader
  • AsyncTaskLoader
  • CursorLoader

Chapter 8 - Services and Broadcast recievers

  • Android Service example, loading music in background.

  • Android Broadcast receiver involves detecting a change in the battery level of a mobile device.

  • A Service runs in the main UI thread, and you can launch a separate Thread in a Service in order to perform long-running tasks.

  • Intent listeners are good for showing notifications.

  • Services are useful for tasks that require more than a few seconds to complete, or need to run continuously in the background.

  • Broadcast receivers are good for system-related events (e.g., a device has rebooted) or sensor-related events (e.g., the battery level has changed).

  • Android supports Services via a element. Every Service in an Android application must have its associated XML element included in AndroidManifest.xml.

  • Context.startService() , which starts the execution of the task.

  • Context.bindService() , which makes available a long-lasting connection with the Service .

  • The onStartCommand() method is invoked (via the startService() method) when the service is started by another component. This method does not need to be implemented for bound services.

  • The onBind() method is invoked when a component binds to the ser- vice via a call to the bindService() method.

  • A Broadcast Receiver (part of the android.content package) is a pub- lish-and-subscribe system that is based on an Intent .

  • A Broadcast Intent is a system-wide intent that is sent to all applica- tions that have registered an interested Broadcast Receiver.

  • Android Alarm is something that you can schedule to execute at some point in the future.

Chapter 9 - Android Vr, TV, Auto, and things

Android IoT

  • Android Things is a “rebranding” of Android Brillo , to be used with low- power and memory-constrained IoT devices. One key difference: Brillo used C++ as the primary development environment, whereas Android Things targets Java developers.

  • Runtime Permissions are not supported because embed- ded devices aren’t guaranteed to have a UI to accept the runt- ime dialog.

Chapter 10 - Functional Reactive Programming

  • Observables: there are inter-mediate operators (such as map() , filter() , and so forth) that you can chain together, and there are terminal operators (such as subscribe() or forEach ) that you can invoke in order to “make stuff happen”

  • Observable com- prises one or more intermediate operators that transform a stream of data, followed by a terminal operator that actually “kicks off” the Observable in order to generate a stream of data.

  • Lambda Expressions are a replacement for anonymous inner classes in Java. Method must belong to a Java class, whereas a Lambda Expression can exist outside of a Java class. Hence, you will sometimes see a Lambda Expression described as an “anonymous function.”

  • Properties of Lambda Expressions. Single as well as multi-line code for the “body” the body can throw exceptions an explicit return statement is not required round brackets represent a no-argument list curly braces are not required for single-line body

  • A functional interface is a Java interface that contains a single abstract method. For example, the Runnable interface consists only of the run() method

  • A Stream is an abstraction that is a layer above actual data and objects. A Stream involves the flow of data and operators that can be “applied” to a Stream .

  • A Stream supports two types of operators: intermediate (“eager”) opera- tors and terminal (“lazy”) operators.

  • Terminal operators minimize mem- ory consumption, so they are well-suited for large data streams. On the other hand, intermediate operators are well-suited for performance, but they also consume large amounts of memory.

  • Collection is a number of objects defined at one point in time, and they occupy storage in memory. By contrast, streams process on-demand data and do not store data.