sensors - cs 4720 · • android sensors as separated into one of three broad categories: ......
TRANSCRIPT
CS4720
Sensors
CS4720– MobileApplicationDevelopment
CS4720
SensorCategories• Androidsensorsasseparatedintooneofthreebroadcategories:– Motionsensors– measureforceandrotation– Environmentalsensors– measureparameterssuchasilluminationairtemperatureandpressure
– Positionsensors– measurephysicalpositioningofthedevice
2
CS4720
Hardwarevs.Software• Althoughitmightbenaturaltothinkofallsensorsashardware,thatisn’tthecase
• AsensorinthecaseofAndroidisanycomponentthatprovidesinformationabouttheoutsideworld
• So,some“sensors”areactuallysoftwarecomponentsthattakedatafromhardwaresensorstogeneratedifferentkindsofdata
• Thesearecalled“virtualsensors”
3
CS4720
Sensors?Whatsensors?• Sensorsaren’tguaranteed!• ThereisnoAndroidspecforrequiredsensors!• So,youhavetocheckforthesensorfirst• Androidregisterssensorsintoparticularcategoriesdefinedbyaglobalfinalvariable
• Youcanaskforthedefaultsensorofanycategorytogetthecurrentlyactiveone(yes,youcanhavemorethanone!)
• Also,differentcapabilitiesanddrivers!4
CS4720
GettingData• Sensorsworksomewhatsimilarlytoaservice• Inasense,theyarealwaysrunninginthebackground
• Youcanallocateasensoreventlistenertomonitorasensorforchangesto:– Data– Availability– Precision/Resolution– PowerConsumption
5
CS4720
SensorEventListener• Toaccessthedatafromasensor,youneedaSensorEventListener
• YoucanimplementthisclassfromyourActivity• InsideonCreate,youcanaskthesensorservicetoprovidethecurrentdefaultsensorforanygivencategory
6
CS4720
SensorEvent• Atregularintervals,asensorreportsaSensorEvent toallregisteredlisteners
• ASensorEvent hasanarrayassociatedwithitcalledvalues
• Foreachsensor,thedataineachslotinthearrayrepresentsdifferentdata
7
CS4720
SensorEvent - Accelerometer• values[0]– accelerationforceonxaxis• values[1]– accelerationforceonyaxis• values[2]– accelerationforceonzaxis
8
CS4720
DifficultyofUsingAnalogData• Howdoyouread“userintent”?• Didtheymeantodosomething,ordidtheydropthedevice?
• Howcould“shaketoshuffle”messthingsupforrunners?
• Also,it’saLOTofdatacomingreallyfast!• Howdoyounotoverwhelmyourprogram?
9
CS4720
AdvancedSensors• Location• Camera• Microphone/Audio
10
CS4720
LocationServices• Locationservicescomeintwoflavors:
– ThelocationservicethatdirectlyprovidestheGPScoordinateinformation
– GoogleMapsAPI
11
CS4720
LocationServices• Locationservicesisbyfartheeasierofthetwomethodstogetasimplelocation
• Workssimilarlytoothersensors• Seeoldexamplecodeforthis!
12
CS4720
GooglePlayServices• GooglePlayServicesencompassallofthepotentialcloudfeaturesthatGoogleprovidesthroughtheirPlaystore
• Hastobemanuallyaddedintoyourmanifestsoitcanbecompiledintoyourapp
• APIkeysmightberequiredforagivenservicesothatGooglecantrackusage(andchargeasneeded)
13
CS4720
SomeGooglePlayServices• Google+• GoogleAccountLogin• GoogleAnalytics• GoogleMessaging• GoogleDrive• GoogleMaps• GoogleAds• GooglePlayGameservices
14
CS4720
ConnectingtoGooglePlayServices• Toutilizemanyofthese,youinstantiateaninstanceoftheGoogleApiClient classinyourapp
• Wheninstantiated,youconnecttoaparticularservice
• Youthenoverride– onConnected()– onConnectionSuspended()– onConnectionFailed()
15
CS4720
Authorization• Insomecases,yourappneedstobeauthorizedinsomewaybeforeitcanaccesstheservice
• Forinstance,inordertodogoodpublic/privatekeyauthenticationforGoogleSign-In,yourappneedstohaveanAPIkeydigitallysignedbyahashofyoursigningcertificate
16
CS4720
Camera• Twowaystogetanimage
– Sendanintenttothedefaultcameraprogram– Writeyourowncamera
17
CS4720
SendinganIntent(akaEasyWay)// create Intent to take a picture and return control to the
// calling applicationIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// create a file to save the image fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// set the image file name intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture IntentstartActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Alsoworksforvideo!
18
CS4720
WritingaCamera(akaHardWay)• VerifythereISacamera• UsetheCameraclass• CreateaCameraPreview classtoshowwhattheCamerasees(theviewfinder)
• Addallbuttonsnecessarytozoom,capture,etc.
• Writecodetograbcurrentpixelsetandwritetofile
• Let’snottalkaboutvideo…19
CS4720
Microphone/Audio• Actually,abitdifferent
mRecorder = new MediaRecorder();mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);mRecorder.setOutputFile(mFileName);mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {mRecorder.prepare();
} catch (IOException e) {Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
20
CS4720
CoreMotion andCoreLocation• First,let’sdothe“howtodothese”• CoreMotion controlsaccesstotheaccelerometerandgyroscope
• CoreLocation controlsaccesstotheGPS
21
CS4720
CoreLocation
22
func createLocationManager(startImmediately startImmediately: Bool){locationManager = CLLocationManager()if let manager = locationManager{
print("Successfully created the location manager")manager.delegate = selfif startImmediately{
manager.startUpdatingLocation()}
}}
CS4720
CoreLocation
23
func locationManager(manager: CLLocationManager, didUpdateLocationslocations: [CLLocation]) {
if locations.count == 0{//handle error herereturn
}
let newLocation = locations[0]
print("Latitude = \(newLocation.coordinate.latitude)")print("Longitude = \(newLocation.coordinate.longitude)")lat.text = String(newLocation.coordinate.latitude)lon.text = String(newLocation.coordinate.longitude)
}
CS4720
CoreLocation
24
/* Are location services available on this device? */if CLLocationManager.locationServicesEnabled(){
/* Do we have authorization to access location services? */switch CLLocationManager.authorizationStatus(){case .AuthorizedAlways:
/* Yes, always */createLocationManager(startImmediately: true)
case .AuthorizedWhenInUse:/* Yes, only when our app is in use */createLocationManager(startImmediately: true)
case .Denied:/* No */displayAlertWithTitle("Not Determined",
message: "Location services are not allowed for thisapp")
CS4720
CoreMotion - Shake
25
// function to allow for detecting a shakeoverride func motionEnded(motion: UIEventSubtype,
withEvent event: UIEvent?) {
if motion == .MotionShake{let controller = UIAlertController(title: "Shake",
message: "The device is shaken",preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK",style: .Default,handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
}
CS4720
CoreMotion - Accelerometer
26
@IBAction func startAccel(sender: UIButton) {if motionManager.accelerometerAvailable{
let queue = NSOperationQueue()motionManager.startAccelerometerUpdatesToQueue(queue,
withHandler:{data, error in
guard let data = data else{return
}
print("X = \(data.acceleration.x)")print("Y = \(data.acceleration.y)")print("Z = \(data.acceleration.z)")}
)} else {
print("Accelerometer is not available")}
}