Programming for Mobile IV

A Few Notes

Wrap up of Events in Android

  • We have seen 3 ways events are handled in Android
    • UI Events
    • Sensor Events
    • Location Events
  • The next few slides we will present how they work in a format friendly for comparison

UI Events

  • What is needed
    • UI Object
    • Event Listener Object
  • How to get the UI Object
    • Through calling findViewById directly in the Activity and casting to the correct object

UI Events II

  • How to register
    • Using a method of the UI object named .setOnEVENTNAME()
  • How to make an event listener
    • Implement the interface specific to the event to listen to, ie OnClickListener
  • What is passed to the listener
    • The UI Object that triggered the event

Sensor Events

  • What is needed
    • Sensor Manager Object
    • Sensor Object
    • Sensor Event Listener
  • How to get the Sensor Manager Object
    • From the OS
      mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
      
  • How to get the Sensor Object
    • From the SensorManager
      temp = mSensorManager.getDefaultSensor(
                Sensor.TYPE_TEMPERATURE);
      

Sensor Events II

  • How to Register
    • Using the registerListener method of the manager and passing in both the sensor to listen to and the listener to use
  • How to make an event listener
    • Implement the general SensorEventListener interface
  • What is passed to the listener
    • A SensorEvent object that details both the sensor readins and which sensor caused it

Location Events ( Play Services Version)

  • What is needed
    • Google API Client Object
    • Location Request Object
    • Location Listener Object
  • How to get the Google API Client Object
    mGoogleApiClient = new GoogleApiClient.Builder(this)
          .addConnectionCallbacks(this)
          .addOnConnectionFailedListener(this)
          .addApi(LocationServices.API)
          .build();
    

Location Events II

  • How to register
    • Using the requestLocationUpdates method of the static class LocationServices.FusedLocationAPI which is passed the API Object, the Request Object, and the Listener Object
  • How to make an event Listener
    • Implement the LocationListener interface
  • What is passed to the listener
    • A Location object that contains lat/long along with other location information

Introduction to MIME Types

  • Originally meant as a way to describe email attachments, have evolved into the standard was to indicate file types
  • Seperate from the file extension, this can be thought of as a string constant that programs can use to refer to what type of file they expect or are sending
  • Administered by the Internet Assigned Numbers Authority and more properly known as media types now

Example MIME Types

  • A MIME Type is a string of the format "topLevel/subType"
  • Top levels include:
    • text
    • image
    • video
    • audio
  • The full list can be found here

Examples

  • text/plain
  • text/html
  • audio/mpeg
  • image/png
  • video/mp4

Intents

  • In Android one program can't directly interface with another program or even another activity in the same program
  • Instead a message is sent to the OS asking for something to be done
  • The object that holds this message and what should be done is called the Intent object

Parts of the Intent

  • The main parts of the intent determine what app or part of an app responds to the Intent
  • The main parts are:
    • Component
    • Action
    • Data
    • Category
  • Extras are another part of an intent that can be used to pass additional non-critical data

Component

  • Including a component is the most explicity way to determine what app responds to an inent
    • For this reason, intents including a component value are known as explicit intents
  • It is the actual Java class that will handle the intent
    • Can be set using the .class attribute of a class being passed to the Intent constructor
    • Can be set using a the class name and path name as strings in the method .setComponent(path,class)

Action

  • The action is the a description of what the intent will be doing at a high level
    • ACTION_SEND sends data to another application or part of your application
  • It determines what the input and output of the intent will be
    • ACTION_SEND should be given the MIME type in the data of the intent and the content to send in either EXTRA_TEXT or EXTRA_STREAM
  • Implemented as a string, but should be accessed through a constant of the Intent class
    • The full list can be found here

Data

  • The data part of an intent can be broken down in to the MIME Type and the data itself
  • The MIME Type is set using the method setType(String type) which expects the type in all-lowercase letters
  • The data of an intent is a Uninform Resource Indicator (URI) which is set through setData
    • The data is located at the location the URI refers to
    • This means data must already have been saved somewhere, cant be only in the runtime of your application

Category

  • The category of an intent can specify additional restrictions on where or when the intent may be used
  • They are available as constants of the Intent class just like actions
  • Some example categories are:
    • CATEGORY_LAUNCHER which defines what should be veiwable from the main launcher
    • CATEGORY_CAR_DOCK defines an intent to be available when the phone is docked in a car
    • CATEGORY_DEFAULT the default category of an intent, more useful in Intent Filters

Sending an Intent from an Application

  • First create an new Intent and set the appropriate fields
  • Check if the user has another app ready to handle the intent using the method resolveActivity
    • If the user is able to handle the intent, pass the Intent object to the method startActivity
  • A list of common intent settings can be found here

Sending an Intent Example

  • The example below (from Android docs) shows how to open a web browser and point it to a specific location
    Uri webpage = Uri.parse(url);
      Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
      if (intent.resolveActivity(getPackageManager()) != null) {
          startActivity(intent);
      }
    

Handling the return from an Intent

  • The previous Intent does not have any return value
  • Some Intents are expected to return control back to the original application and provide data
    • An application can get a picture from the camera by using intents
    • The camera will save the picture somewhere are return the location to the original application
  • Two changes are required when a return is expected
    • The Intent needs to be sent with startActivityWithReturn
    • The method onActivityResult(int,int,Intent)

Return from Intent Example

  • From common intents list in Android Documentation
static final int REQUEST_IMAGE_CAPTURE = 1;
  static final Uri mLocationForPhotos;

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.withAppendedPath(mLocationForPhotos, targetFilename));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        // Do other work with full size photo saved in mLocationForPhotos
        ...
    }
}

Intent Filter

  • How does an implicit intent in your app know what application should handle it?
    • ie, in the camera example, only the fact we wanted an image caputre was mentioned.
  • The OS manages this based on the installed applications manifests
    • This specification is known as the intent filter for the application
    • The same parts exists, but now they are placed in the XML tag < intent-filter >

Example Intent Filter

  • This is the intent filter telling the OS how to open the application
    <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    

So how do applications actually handle intents?

  • Every Activity is started by an intent, even if its from the launcher
  • The intent that caused the activity to start can be retrieved from the method getIntent()
    • This is useful to determine how you should respond
  • To send a response
    • Make a new Intent that holds the result data you wish to send back
    • Use the setResult(Intent) function of the activitiy to indicate the new Intent holds the result
    • call finish() to end the responding activity and return control back to the original activity