-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCaptureActivity.java
More file actions
567 lines (484 loc) · 21.3 KB
/
CaptureActivity.java
File metadata and controls
567 lines (484 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package mfulton.drivedata;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.Date;
public class CaptureActivity extends FragmentActivity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
/*
OBJECT VARIABLES
These variables hold information required by the capture activity.
*/
//
private static String appVersion;
private GoogleApiClient googleApiClient; //The connection client for the Google API.
private boolean clientReady; // Is the client ready for capture?
private Handler handler; //The Handler which handles the message que.
//Variables related to the log.
private String logName; //The name of the current capture.
private long timestamp; //The current time.
private boolean isCapturing; //Whether or not the capture is currently taking place
//Variables related to file i/o
private File directory, locationFile, accelFile, imageDir; // The directory, log file for location, and the directory for images.
private OutputStream outLocation, outAccel; //
//Variables for sensor output and sensor managers.
private Location newestLocation;
private boolean locationReady; // Whether or not the location API is ready.
//Variables for handling sensor management.
private SensorManager sManager;
private Sensor lAccel;
private SensorEvent newestAccel;
private boolean accelReady; // Whether or not the acceleration sensors are ready.
//Variables related to camera use.
private Camera cam; //The camera object.
private Preview preview; // The camera preview used to display the current view.
private boolean cameraSafe; //A boolean representing whether or not the camera is safe to use.
private boolean resolvingError; //Is the application currently resolving an error.
//Constants
private static final int REQUEST_RESULT_ERROR = 1001; //Request code for errors.
private static final String DIALOG_ERROR = "dialog_error"; //Tag for the error dialog fragment.
private static final String STATE_RESOLVING_ERROR = "resolving_error"; // Tag for the state resolving state.
private static final String STATE_CRITERIA_MET = "criteria_met"; //Tag for the criteria met state.
/*
FUNCTIONS */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
isCapturing = clientReady = locationReady = accelReady = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
logName = prefs.getString("log_name", "");
handler = new Handler(Looper.getMainLooper());
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
directory = filePrep(null, logName, true);
imageDir = filePrep(directory, "images", true);
locationFile = filePrep(directory, (logName + "_LOCATION.log"), false);
accelFile = filePrep(directory, (logName + "_ACCEL.log"), false);
try{
DateFormat[] formats = new DateFormat[]{
DateFormat.getDateInstance(),
DateFormat.getDateTimeInstance(),
DateFormat.getTimeInstance(),
};
outLocation = new FileOutputStream(locationFile);
outLocation.write((formats[1].format(new Date(0))).getBytes());
outLocation.write(("\nTimestamp || Latitude || Longitude || Bearing || Altitude || Acuracy || Real Time\n").getBytes());
outAccel = new FileOutputStream(accelFile);
outAccel.write((formats[1].format(new Date(0))).getBytes());
outAccel.write(("\nTimestamp || X || Y || Z || Acuracy || Real Time\n").getBytes());
}catch( Exception e){
Log.e("Capture", e.toString());
}
sManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION) != null){
lAccel = sManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sManager.registerListener(accelListener, lAccel, SensorManager.SENSOR_DELAY_FASTEST);
accelReady = true;
}
else{
lAccel = null;
accelReady = false;
}
lAccel = sManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
try{
cam = Camera.open();
preview = new Preview(getApplicationContext(), cam);
FrameLayout camView = (FrameLayout) findViewById(R.id.camPreview);
camView.addView(preview);
cam.startPreview();
}catch(Exception e){
Log.e("Capture", e.toString());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
if (isCapturing){endCapture();}
googleApiClient.disconnect();
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause(){
super.onPause();
}
/*
UI LISTENERS
*/
public void onClick(View view) {
TextView recorder = (TextView)findViewById(R.id.recording_indicator);
if (isCapturing && (recorder.getText().equals("REC"))) {
recorder.setText("Capture Complete");
recorder.setTextColor(getResources().getColor(R.color.green));
endCapture();
Log.i("CaptureActivity", "Stopping CaptureActivity");
}else if(!isCapturing) {
if(clientReady && locationReady && accelReady) {
recorder.setText("REC");
beginCapture();
Log.i("CaptureActivity", "Starting CaptureActivity");
}
else{
Context context = getApplicationContext();
int toast_duration = Toast.LENGTH_LONG;
CharSequence text = "An unkown error is preventing capture beginning.";
Toast toast;
if (!clientReady)
text = "Google Play Services not ready, please wait a moment";
else if (!locationReady)
text = "Google Location Services not ready, please wait a moment";
else if (!accelReady)
text = "Acceleration sensors calibrating, please wait.";
toast = Toast.makeText(context, text, toast_duration);
toast.show();
}
}
else{
return;
}
}
/*
CONNECTION HANDLERS FOR GOOGLE API
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i("CaptureActivity", "onConnected called");
clientReady = true;
//Use a new thread to request location updates for the worker thread.
//This new thread waits until the result of the request for updates is complete.
Runnable r = new Runnable(){
@Override
public void run() {
LocationRequest request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(5000);
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationAvailability(LocationAvailability availability) {
if (!availability.isLocationAvailable()) {
locationReady = false;
}
}
public void onLocationResult(LocationResult result) {
newestLocation = result.getLastLocation();
}
};
PendingResult<Status> requestResult = LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, locationCallback, handler.getLooper());
Status requestStatus = requestResult.await();
locationReady = true;
if(requestStatus.isSuccess()) {
locationReady = true;
Log.i("CaptureActivity", "Location update request result success!");
}else {
Log.i("CaptureActivity", "Location update request result: failure!");
}
}
};
new Thread(r).start();
}
@Override
public void onConnectionSuspended(int cause) {
isCapturing = false;
endCapture();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
if (resolvingError) {
return; //An error is being resolved. We need to wait.
} else if (result.hasResolution()) { //There is a resolution available.
try {
resolvingError = true;
result.startResolutionForResult(this, REQUEST_RESULT_ERROR);
} catch (IntentSender.SendIntentException e) {
//There was an error attempting to resolve. Let's try again.
googleApiClient.connect();
}
} else {
//Show error dialog
resolvingError = true;
showErrorDialog(result.getErrorCode());
}
}
/*
FUNCTIONS THAT ACTUALLY DO THE WORK
*/
public void beginCapture(){
isCapturing = true;
cameraSafe = true;
Log.i("Capture", "Starting the capture.");
handler.postDelayed(
new Runnable() {
@Override
public void run() {
try {
//CaptureActivity image
if(cameraSafe) {
cam.takePicture(null, null, myPicture);
cameraSafe = false;
cam.startPreview();
String logEntry;
if(newestLocation != null) {
//Writing Location updates
logEntry = Long.toString(timestamp) + " , "
+ Double.toString(newestLocation.getLatitude()) + " , "
+ Double.toString(newestLocation.getLongitude()) + " , ";
if (newestLocation.hasBearing())
logEntry = logEntry + Double.toString(newestLocation.getBearing())
+ " , ";
else
logEntry = logEntry + "NA" + " , ";
if (newestLocation.hasAltitude())
logEntry = logEntry + Double.toString(newestLocation.getAltitude())
+ " , ";
else
logEntry = logEntry + "NA" + " , ";
if (newestLocation.hasAccuracy())
logEntry = logEntry + Double.toString(newestLocation.getAccuracy())
+ " , ";
else
logEntry = logEntry + "NA" + " , ";
logEntry = logEntry + Long.toString(newestLocation.getTime());
logEntry = logEntry + "\n";
outLocation.write(logEntry.getBytes());
}
else{
outLocation.write(("LOCATION NULL").getBytes());
}
if(newestAccel != null) {
//Writing Accel Updates
logEntry = "";
logEntry = Long.toString(timestamp) + " , "
+ Double.toString(newestAccel.values[0]) + " , "
+ Double.toString(newestAccel.values[1]) + " , "
+ Double.toString(newestAccel.values[2]) + " , "
+ Integer.toString(newestAccel.accuracy) + " , "
+ Long.toString(newestAccel.timestamp) + "\n";
outAccel.write(logEntry.getBytes());
}
else{
outAccel.write(("ACCELERATION NULL").getBytes());
}
}
} catch (Exception e) {
Log.e("Capture Loop", e.toString());
}
if (isCapturing && locationReady) {
handler.postDelayed(this, 100);
}
}
}, 100);
//Start Camera CaptureActivity.
}
public void endCapture(){
isCapturing = false;
cam.release();
try {
outLocation.close();
}catch (Exception e){
Log.e("Capture", e.toString());
}
}
//Sets up a file with the appropriate path and creates it if ineescary.
public File filePrep(File parent, String filename, boolean isDirectory){
File result = null;
String path;
try {
//Cheack to see if external storage is available. If it is, use it.
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Log.i("Capture", "Using External Storage");
//If no parent is provided, find the documents directory.
if (parent == null) {
path = Environment.getExternalStorageDirectory().getPath();
// path = System.getenv("SECONDARY_STORAGE");
path = path + "/DriveDataCaptures";
}
//Use the provided parent.
else {
path = parent.getPath();
}
//Create a new file.
result = new File(path, filename);
}
//Use the internal storage.
else {
Log.i("Capture", "Using Internal Storage");
//If no parent is provided, get the app file directory.
if (parent == null) {
path = getApplicationContext().getFilesDir().getPath();
}
//Otherwise just use the parent
else {
path = parent.getPath();
}
//Create a new file.
result = new File(path, filename);
}
//Now we're going to check to see if directories and files with these paths exist, and
//create them if nessecary.
//If we need a directory.
if (isDirectory) {
if (!(result.mkdirs()))
Log.i("Capture filePrep", "Directory "
+ filename + " already existed at: " + path);
else
Log.i("Capture filePrep", "Directory "
+ filename + " has been created at: " + path);
}
//If we need a .log file.
else {
if (!(result.createNewFile()))
Log.i("Capture filePrep", "File "
+ filename + " already existed at: " + path);
else
Log.i("Capture filePrep", "File "
+ filename + " has been created at: " + path);
}
//Set file permissions
if(!(result.setReadable(true, true) &&result.setWritable(true, true))) {
throw new IOException(("Access denied to:" + result.getName()));
}
}catch(Exception e){
//If anything happen, just dump the contents of the exception.
Log.e("Capture filePrep", "encountered a problem");
Log.e("Capture filePrep", e.toString());
}
//Return the File, tied to a directory of .log file at the correct path..
return result;
}
//SensorEvent Listener for linear acceleration.
private SensorEventListener accelListener = new SensorEventListener(){
@Override
public void onSensorChanged(SensorEvent event){
newestAccel = event;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
return;
}
};
// Callback for capturing image.
private Camera.PictureCallback myPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
timestamp = SystemClock.elapsedRealtime();
File pictureFile = new File(imageDir.getPath()
+ File.separator + logName + "_IMG_" + timestamp + ".jpg");
cameraSafe = true;
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("Capture", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Capture", "Error accessing file: " + e.getMessage());
} catch (Exception e) {
Log.e("Capture", e.toString());
}
cameraSafe= true;
}
};
/*
ERROR HANDLING FUNCTIONS
*/
//The following functions and inline classes are defined to help resolve connection issues.
public void showErrorDialog(int errorCode) {
//Create a new fragment.
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
//Pass in the error that must be displayed.
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getSupportFragmentManager(), "errordialog");
}
// Called once the ErrorDialogFragment is done.
public void onDialogDismissed() {
resolvingError = false;
}
//Class used to select the correct dialog
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {
}
@Override
public Dialog onCreateDialog(@NonNull Bundle savedInstanceState) {
//Get the error code
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESULT_ERROR
);
}
@Override
public void onDismiss(DialogInterface dialog) {
((MainMenu) getActivity()).onDialogDismissed();
}
}
//Once the error resolution completes, this callback is needed
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESULT_ERROR) {
resolvingError = false;
if (resultCode == RESULT_OK) {
if (!googleApiClient.isConnecting() &&
!googleApiClient.isConnected()) {
googleApiClient.connect();
}
}
}
}
}