summaryrefslogtreecommitdiff
path: root/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
blob: 9135c92d58f6161c3c4ca494bfa04ceaf61604ed (plain)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
/*

 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.cts.verifier.sensors.base;

import com.android.cts.verifier.PassFailButtons;
import com.android.cts.verifier.R;
import com.android.cts.verifier.TestResult;
import com.android.cts.verifier.sensors.helpers.SensorFeaturesDeactivator;
import com.android.cts.verifier.sensors.reporting.SensorTestDetails;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.cts.helpers.ActivityResultMultiplexedLatch;
import android.media.MediaPlayer;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import junit.framework.Assert;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * A base Activity that is used to build different methods to execute tests inside CtsVerifier.
 * i.e. CTS tests, and semi-automated CtsVerifier tests.
 *
 * This class provides access to the following flow:
 *      Activity set up
 *          Execute tests (implemented by sub-classes)
 *      Activity clean up
 *
 * Currently the following class structure is available:
 * - BaseSensorTestActivity                 : provides the platform to execute Sensor tests inside
 *      |                                     CtsVerifier, and logging support
 *      |
 *      -- SensorCtsTestActivity            : an activity that can be inherited from to wrap a CTS
 *      |                                     sensor test, and execute it inside CtsVerifier
 *      |                                     these tests do not require any operator interaction
 *      |
 *      -- SensorCtsVerifierTestActivity    : an activity that can be inherited to write sensor
 *                                            tests that require operator interaction
 */
public abstract class BaseSensorTestActivity
        extends PassFailButtons.Activity
        implements View.OnClickListener, Runnable, ISensorTestStateContainer {
    @Deprecated
    protected static final String LOG_TAG = "SensorTest";

    protected final Class mTestClass;

    private final int mLayoutId;
    private final SensorFeaturesDeactivator mSensorFeaturesDeactivator;

    private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
    private final SensorTestLogger mTestLogger = new SensorTestLogger();
    private final ActivityResultMultiplexedLatch mActivityResultMultiplexedLatch =
            new ActivityResultMultiplexedLatch();
    private final ArrayList<CountDownLatch> mWaitForUserLatches = new ArrayList<CountDownLatch>();

    private ScrollView mLogScrollView;
    private LinearLayout mLogLayout;
    private Button mNextButton;
    private Button mPassButton;
    private Button mFailButton;
    private Button mRetryButton;

    private GLSurfaceView mGLSurfaceView;
    private boolean mUsingGlSurfaceView;

    // Flag for Retry button appearance.
    private boolean mShouldRetry = false;
    private int mRetryCount = 0;

    /**
     * Constructor to be used by subclasses.
     *
     * @param testClass The class that contains the tests. It is dependant on test executor
     *                  implemented by subclasses.
     */
    protected BaseSensorTestActivity(Class testClass) {
        this(testClass, R.layout.sensor_test);
    }

    /**
     * Constructor to be used by subclasses. It allows to provide a custom layout for the test UI.
     *
     * @param testClass The class that contains the tests. It is dependant on test executor
     *                  implemented by subclasses.
     * @param layoutId The Id of the layout to use for the test UI. The layout must contain all the
     *                 elements in the base layout {@code R.layout.sensor_test}.
     */
    protected BaseSensorTestActivity(Class testClass, int layoutId) {
        mTestClass = testClass;
        mLayoutId = layoutId;
        mSensorFeaturesDeactivator = new SensorFeaturesDeactivator(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(mLayoutId);

        mLogScrollView = (ScrollView) findViewById(R.id.log_scroll_view);
        mLogLayout = (LinearLayout) findViewById(R.id.log_layout);
        mNextButton = (Button) findViewById(R.id.next_button);
        mNextButton.setOnClickListener(this);
        mPassButton = (Button) findViewById(R.id.pass_button);
        mFailButton = (Button) findViewById(R.id.fail_button);
        mGLSurfaceView = (GLSurfaceView) findViewById(R.id.gl_surface_view);
        mRetryButton = (Button) findViewById(R.id.retry_button);
        mRetryButton.setOnClickListener(new retryButtonListener());

        mRetryButton.setVisibility(View.GONE);
        updateNextButton(false /*enabled*/);
        mExecutorService.execute(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mExecutorService.shutdownNow();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mUsingGlSurfaceView) {
            mGLSurfaceView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mUsingGlSurfaceView) {
            mGLSurfaceView.onResume();
        }
    }

    @Override
    public void onClick(View target) {
        mShouldRetry = false;

        synchronized (mWaitForUserLatches) {
            for (CountDownLatch latch : mWaitForUserLatches) {
                latch.countDown();
            }
            mWaitForUserLatches.clear();
        }
    }

    private class retryButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            mShouldRetry = true;
            ++mRetryCount;

            synchronized (mWaitForUserLatches) {
                for (CountDownLatch latch : mWaitForUserLatches) {
                    latch.countDown();
                }
                mWaitForUserLatches.clear();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mActivityResultMultiplexedLatch.onActivityResult(requestCode, resultCode);
    }

    /**
     * The main execution {@link Thread}.
     *
     * This function executes in a background thread, allowing the test run freely behind the
     * scenes. It provides the following execution hooks:
     *  - Activity SetUp/CleanUp (not available in JUnit)
     *  - executeTests: to implement several execution engines
     */
    @Override
    public void run() {
        long startTimeNs = SystemClock.elapsedRealtimeNanos();
        String testName = getTestClassName();

        SensorTestDetails testDetails;
        try {
            mSensorFeaturesDeactivator.requestDeactivationOfFeatures();
            testDetails = new SensorTestDetails(testName, SensorTestDetails.ResultCode.PASS);
        } catch (Throwable e) {
            testDetails = new SensorTestDetails(testName, "DeactivateSensorFeatures", e);
        }

        SensorTestDetails.ResultCode resultCode = testDetails.getResultCode();
        if (resultCode == SensorTestDetails.ResultCode.SKIPPED) {
            // this is an invalid state at this point of the test setup
            throw new IllegalStateException("Deactivation of features cannot skip the test.");
        }
        if (resultCode == SensorTestDetails.ResultCode.PASS) {
            testDetails = executeActivityTests(testName);
        }

        // we consider all remaining states at this point, because we could have been half way
        // deactivating features
        try {
            mSensorFeaturesDeactivator.requestToRestoreFeatures();
        } catch (Throwable e) {
            testDetails = new SensorTestDetails(testName, "RestoreSensorFeatures", e);
        }

        mTestLogger.logTestDetails(testDetails);
        mTestLogger.logExecutionTime(startTimeNs);

        // because we cannot enforce test failures in several devices, set the test UI so the
        // operator can report the result of the test
        promptUserToSetResult(testDetails);
    }

    /**
     * A general set up routine. It executes only once before the first test case.
     *
     * NOTE: implementers must be aware of the interrupted status of the worker thread, and let
     * {@link InterruptedException} propagate.
     *
     * @throws Throwable An exception that denotes the failure of set up. No tests will be executed.
     */
    protected void activitySetUp() throws Throwable {}

    /**
     * A general clean up routine. It executes upon successful execution of {@link #activitySetUp()}
     * and after all the test cases.
     *
     * NOTE: implementers must be aware of the interrupted status of the worker thread, and handle
     * it in two cases:
     * - let {@link InterruptedException} propagate
     * - if it is invoked with the interrupted status, prevent from showing any UI

     * @throws Throwable An exception that will be logged and ignored, for ease of implementation
     *                   by subclasses.
     */
    protected void activityCleanUp() throws Throwable {}

    /**
     * Performs the work of executing the tests.
     * Sub-classes implementing different execution methods implement this method.
     *
     * @return A {@link SensorTestDetails} object containing information about the executed tests.
     */
    protected abstract SensorTestDetails executeTests() throws InterruptedException;

    /**
     * Get mShouldRetry to check if test is required to retry.
     */
    protected boolean getShouldRetry() {
        return mShouldRetry;
    }

    @Override
    public SensorTestLogger getTestLogger() {
        return mTestLogger;
    }

    @Deprecated
    protected void appendText(int resId) {
        mTestLogger.logInstructions(resId);
    }

    @Deprecated
    protected void appendText(String text) {
        TextAppender textAppender = new TextAppender(R.layout.snsr_instruction);
        textAppender.setText(text);
        textAppender.append();
    }

    @Deprecated
    protected void clearText() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLogLayout.removeAllViews();
            }
        });
    }

    /**
     * Waits for the operator to acknowledge a requested action.
     *
     * @param waitMessageResId The action requested to the operator.
     */
    protected void waitForUser(int waitMessageResId) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        synchronized (mWaitForUserLatches) {
            mWaitForUserLatches.add(latch);
        }

        mTestLogger.logInstructions(waitMessageResId);
        setNextButtonText(waitMessageResId);

        updateRetryButton(true);
        updateNextButton(true);
        latch.await();
        updateRetryButton(false);
        updateNextButton(false);
    }

    /**
     * Waits for the operator to acknowledge to begin execution.
     */
    protected void waitForUserToBegin() throws InterruptedException {
        waitForUser(R.string.snsr_wait_to_begin);
    }

    /**
     * Waits for the operator to acknowledge to retry execution.
     */
    protected void waitForUserToRetry() throws InterruptedException {
        mShouldRetry = true;
        waitForUser(R.string.snsr_wait_to_retry);
    }

    /**
     * Waits for the operator to acknowledge to finish execution.
     */
    protected void waitForUserToFinish() throws InterruptedException {
        mShouldRetry = true;
        waitForUser(R.string.snsr_wait_to_finish);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waitForUserToContinue() throws InterruptedException {
        waitForUser(R.string.snsr_wait_for_user);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int executeActivity(String action) throws InterruptedException {
        return executeActivity(new Intent(action));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int executeActivity(Intent intent) throws InterruptedException {
        ActivityResultMultiplexedLatch.Latch latch = mActivityResultMultiplexedLatch.bindThread();
        try {
            startActivityForResult(intent, latch.getRequestCode());
        } catch (ActivityNotFoundException e) {
            // handle exception gracefully
            // Among all defined activity results, RESULT_CANCELED offers the semantic closest to
            // represent absent setting activity.
            return RESULT_CANCELED;
        }
        return latch.await();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean hasSystemFeature(String feature) {
        PackageManager pm = getPackageManager();
        return pm.hasSystemFeature(feature);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean hasActivity(String action) {
        PackageManager pm = getPackageManager();
        return pm.resolveActivity(new Intent(action), PackageManager.MATCH_DEFAULT_ONLY) != null;
    }

    /**
     * Initializes and shows the {@link GLSurfaceView} available to tests.
     * NOTE: initialization can be performed only once, usually inside {@link #activitySetUp()}.
     */
    protected void initializeGlSurfaceView(final GLSurfaceView.Renderer renderer) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mGLSurfaceView.setVisibility(View.VISIBLE);
                mGLSurfaceView.setRenderer(renderer);
                mUsingGlSurfaceView = true;
            }
        });
    }

    /**
     * Closes and hides the {@link GLSurfaceView}.
     */
    protected void closeGlSurfaceView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!mUsingGlSurfaceView) {
                    return;
                }
                mGLSurfaceView.setVisibility(View.GONE);
                mGLSurfaceView.onPause();
                mUsingGlSurfaceView = false;
            }
        });
    }

    /**
     * Plays a (default) sound as a notification for the operator.
     */
    protected void playSound() throws InterruptedException {
        MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI);
        if (player == null) {
            Log.e(LOG_TAG, "MediaPlayer unavailable.");
            return;
        }
        player.start();
        try {
            Thread.sleep(500);
        } finally {
            player.stop();
        }
    }

    /**
     * Makes the device vibrate for the given amount of time.
     */
    protected void vibrate(int timeInMs) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(timeInMs);
    }

    /**
     * Makes the device vibrate following the given pattern.
     * See {@link Vibrator#vibrate(long[], int)} for more information.
     */
    protected void vibrate(long[] pattern) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(pattern, -1);
    }

    // TODO: move to sensor assertions
    protected String assertTimestampSynchronization(
            long eventTimestamp,
            long receivedTimestamp,
            long deltaThreshold,
            String sensorName) {
        long timestampDelta = Math.abs(eventTimestamp - receivedTimestamp);
        String timestampMessage = getString(
                R.string.snsr_event_time,
                receivedTimestamp,
                eventTimestamp,
                timestampDelta,
                deltaThreshold,
                sensorName);
        Assert.assertTrue(timestampMessage, timestampDelta < deltaThreshold);
        return timestampMessage;
    }

    protected String getTestClassName() {
        if (mTestClass == null) {
            return "<unknown>";
        }
        return mTestClass.getName();
    }

    protected void setLogScrollViewListener(View.OnTouchListener listener) {
        mLogScrollView.setOnTouchListener(listener);
    }

    private void setTestResult(SensorTestDetails testDetails) {
        // the name here, must be the Activity's name because it is what CtsVerifier expects
        String name = super.getClass().getName();
        String summary = mTestLogger.getOverallSummary();
        SensorTestDetails.ResultCode resultCode = testDetails.getResultCode();
        switch(resultCode) {
            case SKIPPED:
                TestResult.setPassedResult(this, name, summary);
                break;
            case PASS:
                TestResult.setPassedResult(this, name, summary);
                break;
            case FAIL:
                TestResult.setFailedResult(this, name, summary);
                break;
            case INTERRUPTED:
                // do not set a result, just return so the test can complete
                break;
            default:
                throw new IllegalStateException("Unknown ResultCode: " + resultCode);
        }
    }

    private SensorTestDetails executeActivityTests(String testName) {
        SensorTestDetails testDetails;
        try {
            activitySetUp();
            testDetails = new SensorTestDetails(testName, SensorTestDetails.ResultCode.PASS);
        } catch (Throwable e) {
            testDetails = new SensorTestDetails(testName, "ActivitySetUp", e);
        }

        SensorTestDetails.ResultCode resultCode = testDetails.getResultCode();
        if (resultCode == SensorTestDetails.ResultCode.PASS) {
            // TODO: implement execution filters:
            //      - execute all tests and report results officially
            //      - execute single test or failed tests only
            try {
                testDetails = executeTests();
            } catch (Throwable e) {
                // we catch and continue because we have to guarantee a proper clean-up sequence
                testDetails = new SensorTestDetails(testName, "TestExecution", e);
            }
        }

        // clean-up executes for all states, even on SKIPPED and INTERRUPTED there might be some
        // intermediate state that needs to be taken care of
        try {
            activityCleanUp();
        } catch (Throwable e) {
            testDetails = new SensorTestDetails(testName, "ActivityCleanUp", e);
        }

        return testDetails;
    }

    private void promptUserToSetResult(SensorTestDetails testDetails) {
        SensorTestDetails.ResultCode resultCode = testDetails.getResultCode();
        if (resultCode == SensorTestDetails.ResultCode.FAIL) {
            mTestLogger.logInstructions(R.string.snsr_test_complete_with_errors);
            enableTestResultButton(
                    mFailButton,
                    R.string.fail_button_text,
                    testDetails.cloneAndChangeResultCode(SensorTestDetails.ResultCode.FAIL));
        } else if (resultCode != SensorTestDetails.ResultCode.INTERRUPTED) {
            mTestLogger.logInstructions(R.string.snsr_test_complete);
            enableTestResultButton(
                    mPassButton,
                    R.string.pass_button_text,
                    testDetails.cloneAndChangeResultCode(SensorTestDetails.ResultCode.PASS));
        }
    }

    private void updateNextButton(final boolean enabled) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mNextButton.setEnabled(enabled);
            }
        });
    }

    /**
     * Set the text for next button by instruction message.
     * During retry, next button text is changed to notify users.
     *
     * @param waitMessageResId The action requested to the operator.
     */
    private void setNextButtonText(int waitMessageResId) {
        int nextButtonText;
        switch (waitMessageResId) {
            case R.string.snsr_wait_to_retry:
                nextButtonText = R.string.fail_and_next_button_text;
                break;
            case R.string.snsr_wait_to_finish:
                nextButtonText = R.string.finish_button_text;
                break;
            default:
                nextButtonText = R.string.next_button_text;
                break;
        }
        mNextButton.setText(nextButtonText);
    }

    /**
     * Update the retry button status.
     * During retry, show retry execution count. If not to retry, make retry button invisible.
     *
     * @param enabled The status of button.
     */
    private void updateRetryButton(final boolean enabled) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mShouldRetry) {
                    String showRetryCount = String.format(
                        "%s (%d)", getResources().getText(R.string.retry_button_text), mRetryCount);
                    mRetryButton.setText(showRetryCount);
                    mRetryButton.setVisibility(View.VISIBLE);
                    mRetryButton.setEnabled(enabled);
                } else {
                    mRetryButton.setVisibility(View.GONE);
                    mRetryCount = 0;
                }
            }
        });
    }

    private void enableTestResultButton(
            final Button button,
            final int textResId,
            final SensorTestDetails testDetails) {
        final View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTestResult(testDetails);
                finish();
            }
        };

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mNextButton.setVisibility(View.GONE);
                button.setText(textResId);
                button.setOnClickListener(listener);
                button.setVisibility(View.VISIBLE);
            }
        });
    }

    // a logger available until sensor reporting is in place
    public class SensorTestLogger {
        private static final String SUMMARY_SEPARATOR = " | ";

        private final StringBuilder mOverallSummaryBuilder = new StringBuilder("\n");

        public void logCustomView(View view) {
            new ViewAppender(view).append();
        }

        void logTestStart(String testName) {
            // TODO: log the sensor information and expected execution time of each test
            TextAppender textAppender = new TextAppender(R.layout.snsr_test_title);
            textAppender.setText(testName);
            textAppender.append();
        }

        public void logInstructions(int instructionsResId, Object ... params) {
            TextAppender textAppender = new TextAppender(R.layout.snsr_instruction);
            textAppender.setText(getString(instructionsResId, params));
            textAppender.append();
        }

        public void logMessage(int messageResId, Object ... params) {
            TextAppender textAppender = new TextAppender(R.layout.snsr_message);
            textAppender.setText(getString(messageResId, params));
            textAppender.append();
        }

        public void logWaitForSound() {
            logInstructions(R.string.snsr_test_play_sound);
        }

        public void logTestDetails(SensorTestDetails testDetails) {
            String name = testDetails.getName();
            String summary = testDetails.getSummary();
            SensorTestDetails.ResultCode resultCode = testDetails.getResultCode();
            switch (resultCode) {
                case SKIPPED:
                    logTestSkip(name, summary);
                    break;
                case PASS:
                    mShouldRetry = false;
                    logTestPass(name, summary);
                    break;
                case FAIL:
                    logTestFail(name, summary);
                    break;
                case INTERRUPTED:
                    // do nothing, the test was interrupted so do we
                    break;
                default:
                    throw new IllegalStateException("Unknown ResultCode: " + resultCode);
            }
        }

        void logTestPass(String testName, String testSummary) {
            testSummary = getValidTestSummary(testSummary, R.string.snsr_test_pass);
            logTestEnd(R.layout.snsr_success, testSummary);
            Log.d(LOG_TAG, testSummary);
            saveResult(testName, SensorTestDetails.ResultCode.PASS, testSummary);
        }

        public void logTestFail(String testName, String testSummary) {
            testSummary = getValidTestSummary(testSummary, R.string.snsr_test_fail);
            logTestEnd(R.layout.snsr_error, testSummary);
            Log.e(LOG_TAG, testSummary);
            saveResult(testName, SensorTestDetails.ResultCode.FAIL, testSummary);
        }

        void logTestSkip(String testName, String testSummary) {
            testSummary = getValidTestSummary(testSummary, R.string.snsr_test_skipped);
            logTestEnd(R.layout.snsr_warning, testSummary);
            Log.i(LOG_TAG, testSummary);
            saveResult(testName, SensorTestDetails.ResultCode.SKIPPED, testSummary);
        }

        String getOverallSummary() {
            return mOverallSummaryBuilder.toString();
        }

        void logExecutionTime(long startTimeNs) {
            if (Thread.currentThread().isInterrupted()) {
                return;
            }
            long executionTimeNs = SystemClock.elapsedRealtimeNanos() - startTimeNs;
            long executionTimeSec = TimeUnit.NANOSECONDS.toSeconds(executionTimeNs);
            // TODO: find a way to format times with nanosecond accuracy and longer than 24hrs
            String formattedElapsedTime = DateUtils.formatElapsedTime(executionTimeSec);
            logMessage(R.string.snsr_execution_time, formattedElapsedTime);
        }

        private void logTestEnd(int textViewResId, String testSummary) {
            TextAppender textAppender = new TextAppender(textViewResId);
            textAppender.setText(testSummary);
            textAppender.append();
        }

        private String getValidTestSummary(String testSummary, int defaultSummaryResId) {
            if (TextUtils.isEmpty(testSummary)) {
                return getString(defaultSummaryResId);
            }
            return testSummary;
        }

        private void saveResult(
                String testName,
                SensorTestDetails.ResultCode resultCode,
                String summary) {
            mOverallSummaryBuilder.append(testName);
            mOverallSummaryBuilder.append(SUMMARY_SEPARATOR);
            mOverallSummaryBuilder.append(resultCode.name());
            mOverallSummaryBuilder.append(SUMMARY_SEPARATOR);
            mOverallSummaryBuilder.append(summary);
            mOverallSummaryBuilder.append("\n");
        }
    }

    private class ViewAppender {
        protected final View mView;

        public ViewAppender(View view) {
            mView = view;
        }

        public void append() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLogLayout.addView(mView);
                    mLogScrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            mLogScrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }
            });
        }
    }

    private class TextAppender extends ViewAppender{
        private final TextView mTextView;

        public TextAppender(int textViewResId) {
            super(getLayoutInflater().inflate(textViewResId, null /* viewGroup */));
            mTextView = (TextView) mView;
        }

        public void setText(String text) {
            mTextView.setText(text);
        }

        public void setText(int textResId) {
            mTextView.setText(textResId);
        }
    }
}