1 of 36

Lecture 10:

Hardware, Services,

Odds and Ends

2 of 36

HW 9 Recap

  • Woo persistence #persist

3 of 36

Course Evaluation:

goo.gl/4FzL89

https://uw.iasystem.org/survey/167482

4 of 36

Things to think about

  • PLEASE complete the online eval
  • The department doesn’t teach many courses on a specific technology
  • Android is no different
  • Was 1 hour a week effective? Would you have preferred more?
  • Was the amount of homework right?
  • Would full labs and full projects be preferable?
    • I.e. more structure?
  • Would you recommend it to your friends?
    • If not, what changes would you like to see to do it?

5 of 36

Questions on anything so far?

6 of 36

Odd and End: Demo

7 of 36

WebView

  • Display an HTML file as part of an Android view
  • Can add Java objects as JavaScript interfaces
  • Your JavaScript code can call Java code!

8 of 36

addJavaScriptInterface adds Java object for JS

9 of 36

Why would you do this?

  • Cross platform portability
    • Tools like PhoneGap, Cordova, etc, use this
    • Have to write just a shim layer for primitive functionality
  • Expertise in the web but not Android and not worth learning
  • Kind of a hack, but a good tool to be aware of
  • Problems:
    • Non native feel
    • Testing requires more boilerplate
    • Rotation is even more of a pain
    • Can’t use all platform APIs
    • Solve problems twice--once in JS, once native

10 of 36

Hardware

  • Phones have a lot of cool hardware attached to them
  • Camera
  • Bluetooth
  • Disk
  • Accelerometer
  • Won’t do examples of all of these, but we’ll deal with basic principles

11 of 36

Accessing Hardware

  • Declare a permission to use the network
  • Permissions are declared in AndroidManifest.xml
  • Some hardware you use implicitly (e.g. network with an HTTP request)
  • Most (camera, bluetooth, wifi, etc) you need to access via a system service

12 of 36

Access methods and API varies

  • Object getSystemService(String serviceName)
  • Return object depends on the service name, generally a *Manager
    • Note that this is another chance for a runtime error
  • Context.CAMERA_SERVICE -> CameraManager
  • Context.BLUETOOTH_SERVICE -> BluetoothManager
  • Context.LAYOUT_INFLATER_SERVICE -> LayoutInflater

13 of 36

Almost all are system services

  • WindowManager
  • LayoutInflater
  • ActivityManager
  • PowerManager
  • AlarmManager
  • Vibrator
  • KeyguardManager
  • DownloadManager
  • LocationManager
  • SearchManager
  • ConnectivityManager
  • WiFiManager
  • WifiP2pManager
  • InputMethodManager
  • BatteryManager
  • NetworkStatsManager
  • etc

14 of 36

Network

  • A bit of a special case
  • You need to declare permissions to access it
  • Do NOT access via getSystemService()
  • Instead, standard java APIs and import statements
  • This is extremely common
  • And is extremely annoying in many cases thanks to Java
  • Going to describe some basic design patterns/libraries I’d recommend

15 of 36

Non-network hardware

  • API varies, but always getSystemService() via Context
  • Object getSystemService(String serviceName)
  • Return object depends on the service name, generally a *Manager
    • Note that this is another chance for a runtime error
  • Context.CAMERA_SERVICE -> CameraManager
  • Context.BLUETOOTH_SERVICE -> BluetoothManager
  • Context.LAYOUT_INFLATER_SERVICE -> LayoutInflater

16 of 36

Vibrator: Cause the phone to vibrate

17 of 36

Accelerometer

  • Respond to motion
    • Virtual reality, step counting (though prefer the native API), motion games, etc etc
  • https://developer.android.com/guide/topics/sensors/sensors_motion.html

18 of 36

19 of 36

20 of 36

Services (android.app.Service)

  • (This is a Java class you extend, not talking about a system service)
  • Lots of things on your phone should persist beyond a UI
  • Playing music in the background, syncing messages from an inbox, uploading a giant file, etc
  • All the code we’ve talked about thus far depends on an Activity or some other UI element
  • A Service is an Android construct to get around this

21 of 36

Service Basics

  • Runs in the background
  • No UI (though it can create UI, e.g. via notifications)
  • Not tied to a UI (unlike Activity, etc)
  • Used for long-running operations
  • Not a separate process (unless configured to be so)
  • Not a separate thread (unless configured to be so)

22 of 36

When to use a Service?

  • Uploading a big file
  • Downloading a big file
  • API providing services to other apps
  • Any time you need to do something that could outlive an Activity, it is worth considering a service
    • That said, I’ve never written a service.
    • Though perhaps I should have for long-term syncing.

23 of 36

Using a Service: 2 options

  • Starting: startService(Intent i)
    • One-way communication: Activity -> Service
    • In this case, survives beyond the thing that started it
    • If Activity starts it and Activity is killed, Service can keep running
    • Expected to stop itself when done (stopSelf())
    • Or expected respect request to stop (stopService())
  • Binding: bindService()
    • Two-way communication: Activity <-> Service
    • With appropriate permissions, even other applications can use the service
    • Inter-process communication (IPC) allows native-looking calls
    • Generally define the API via and aidl file

24 of 36

Using via startService()

  • Good for single units of work
  • Expect only semi-regularly, not live connections or very frequently
  • Actions you might make and then expect to tell the user about later
  • For example:
    • Download a file, when complete show notification that they can click on to interact with
    • Tell a media player to start or stop
    • Change the file system

25 of 36

Using via bindService()

  • Long-lived connections
  • The server in a client-server interface
  • Allows two-way communication with Activity
  • For example:
    • Asking for data, which is loaded and provided in a separate process by the service
    • Performing intensive operations and getting results

26 of 36

Creating a Service

  • Declare in manifest
    • No intent filters!
  • Subclass Service or IntentService
  • Implement methods
    • onStartCommand()
    • onBind()
    • onCreate()
    • onDestroy()

27 of 36

Service Lifecycle

28 of 36

Bound Service Lifecycle

29 of 36

Creating unbound Service

  • Prefer subclassing IntentService if possible
  • IntentService does its work in a default worker thread
  • Sets up a work queue and hands them off for you
  • Can only handle a single request at a time
    • This is probably ok, and if not you are working with full concurrency, so be careful
  • Stops itself when queue empty
    • No need to call stopSelf()

30 of 36

Subclassing IntentService

  • Default constructor
  • onHandleIntent(Intent i)
  • Intents passed from startService(intent)
  • Started and stopped as necessary, intents queued and delivered

31 of 36

Creating bound Service

  • Complicated! Lots to get right. Read the docs.
  • Extend Service
  • Implement the the onBind() method
  • Consider which method of communication is appropriate

32 of 36

Ways to bind a Service

  • Extend Binder
    • Only appropriate for a Service within the same application and process
    • Can’t be accessed by other applications
    • Return the Service object itself, which has a public API
    • Return an object that calls the private API
  • Use a Messenger
    • Works across different processes
    • Simplest way to do IPC
    • All requests queued into single thread
    • No need to design to be thread-safe
  • Use Android Interface Definition Language (AIDL)
    • Sophisticated but complex
    • Can handle multiple threads
    • Your code has to be threadsafe
    • Typically do NOT need this method

33 of 36

Extending Binder

34 of 36

Working with AIDL

  • Create an .aidl file
  • .aidl defines interface for talking across processes
  • Build system generates Java interface and implementation
  • Data passed via AIDL is then marshalled from one process to another by the Android system
    • Parameters and return values
    • Only supports primitive types, String, CharSequence, List, Map, and Parcelables with some work

35 of 36

Example of AIDL

36 of 36

HW 10: be free

  • Send me links to how far you got on your projects.
  • Course eval!
    • Please do this. Hugely helpful.
  • goo.gl/4FzL89
  • https://uw.iasystem.org/survey/167482