resolved conflicts for ed0ccb8a to mnc-dev Change-Id: I0938cf7bf1cfacc29083692907e8be20811d36cb
diff --git a/CtsBuild.mk b/CtsBuild.mk index 1b12293..c745885 100644 --- a/CtsBuild.mk +++ b/CtsBuild.mk
@@ -17,7 +17,7 @@ # Functions to get the paths of the build outputs. define cts-get-lib-paths - $(foreach lib,$(1),$(HOST_OUT_JAVA_LIBRARIES)/$(lib).jar) + $(foreach lib,$(1),$(CTS_TESTCASES_OUT)/$(lib).jar) endef define cts-get-ui-lib-paths @@ -25,7 +25,7 @@ endef define cts-get-native-paths - $(foreach exe,$(1),$(call intermediates-dir-for,EXECUTABLES,$(exe),,,$(3))/$(exe)$(2)) + $(foreach exe,$(1),$(CTS_TESTCASES_OUT)/$(exe)$(2)) endef define cts-get-package-paths
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk index 6f475cc..975ac47 100644 --- a/CtsTestCaseList.mk +++ b/CtsTestCaseList.mk
@@ -19,6 +19,8 @@ CtsDocumentClient \ CtsExternalStorageApp \ CtsInstrumentationAppDiffCert \ + CtsUsePermissionApp \ + CtsUsePermissionAppCompat \ CtsPermissionDeclareApp \ CtsPermissionDeclareAppCompat \ CtsReadExternalStorageApp \ @@ -57,13 +59,33 @@ CtsKeySetSigningBUpgradeB \ CtsKeySetSigningAAndBUpgradeA \ CtsKeySetSigningAAndCUpgradeB \ - CtsKeySetSigningAUpgradeNone + CtsKeySetSigningAUpgradeNone \ + CtsKeySetSharedUserSigningAUpgradeB \ + CtsKeySetSharedUserSigningBUpgradeB \ + CtsKeySetSigningABadUpgradeB \ + CtsKeySetSigningCBadAUpgradeAB \ + CtsKeySetSigningANoDefUpgradeB \ + CtsKeySetSigningAUpgradeEcA \ + CtsKeySetSigningEcAUpgradeA + +cts_account_support_packages := \ + CtsUnaffiliatedAccountAuthenticators cts_support_packages := \ CtsAccelerationTestStubs \ + CtsAlarmClockService \ CtsAppTestStubs \ + CtsAssistService \ + CtsAssistApp \ + CtsAtraceTestApp \ + CtsCertInstallerApp \ CtsDeviceAdmin \ CtsDeviceOpenGl \ + CtsWifiConfigCreator \ + CtsDeviceAndProfileOwnerApp \ + CtsDeviceAppUsageTestApp \ + CtsDeviceInfo \ + CtsDeviceOsTestApp \ CtsDeviceOwnerApp \ CtsDeviceTaskswitchingAppA \ CtsDeviceTaskswitchingAppB \ @@ -74,15 +96,24 @@ CtsIntentSenderApp \ CtsLauncherAppsTests \ CtsLauncherAppsTestsSupport \ + CtsLeanbackJank \ CtsManagedProfileApp \ CtsMonkeyApp \ CtsMonkeyApp2 \ + CtsPackageInstallerApp \ + CtsPermissionApp \ CtsSimpleApp \ + CtsSimplePreMApp \ CtsSomeAccessibilityServices \ CtsThemeDeviceApp \ TestDeviceSetup \ CtsUiAutomatorApp \ CtsUsbSerialTestApp \ + CtsVoiceInteractionService \ + CtsVoiceInteractionApp \ + CtsVoiceSettingsService \ + CtsWidgetProviderApp \ + $(cts_account_support_packages) \ $(cts_security_apps_list) \ $(cts_security_keysets_list) @@ -111,11 +142,14 @@ CtsAccessibilityServiceTestCases \ CtsAccessibilityTestCases \ CtsAdminTestCases \ + CtsAlarmClockTestCases \ CtsAnimationTestCases \ CtsAppTestCases \ CtsAppWidgetTestCases \ + CtsAssistTestCases \ CtsBluetoothTestCases \ CtsCalendarcommon2TestCases \ + CtsCallLogTestCases \ CtsContentTestCases \ CtsDatabaseTestCases \ CtsDisplayTestCases \ @@ -128,16 +162,22 @@ CtsGraphicsTestCases \ CtsGraphics2TestCases \ CtsHardwareTestCases \ + CtsJankTestCases \ + CtsLeanbackJankTestCases \ CtsJobSchedulerDeviceTestCases \ CtsJniTestCases \ CtsKeystoreTestCases \ + CtsLibcoreLegacy22TestCases \ CtsLocationTestCases \ CtsLocation2TestCases \ CtsMediaStressTestCases \ CtsMediaTestCases \ + CtsMidiTestCases \ CtsNativeOpenGLTestCases \ CtsNdefTestCases \ CtsNetTestCases \ + CtsNetTestCasesLegacyApi22 \ + CtsNetTestCasesLegacyPermission22 \ CtsOpenGLTestCases \ CtsOpenGlPerfTestCases \ CtsOsTestCases \ @@ -154,18 +194,23 @@ CtsSecurityTestCases \ CtsSignatureTestCases \ CtsSpeechTestCases \ + CtsSystemUiTestCases \ + CtsTelecomTestCases \ + CtsTelecomTestCases2 \ CtsTelephonyTestCases \ CtsTextTestCases \ CtsTextureViewTestCases \ CtsThemeTestCases \ + CtsTransitionTestCases \ CtsTvTestCases \ CtsUiAutomationTestCases \ CtsUiRenderingTestCases \ CtsUsageStatsTestCases \ CtsUtilTestCases \ CtsViewTestCases \ + CtsVoiceInteractionTestCases \ + CtsVoiceSettingsTestCases \ CtsWebkitTestCases \ - CtsWebGLTestCases \ CtsWidgetTestCases # All APKs that need to be scanned by the coverage utilities. @@ -177,6 +222,7 @@ cts_host_libraries := \ CtsAdbTests \ CtsAppSecurityTests \ + CtsAtraceHostTestCases \ CtsDevicePolicyManagerTestCases \ CtsDumpsysHostTestCases \ CtsHostJank \ @@ -184,7 +230,9 @@ CtsHostUi \ CtsJdwpSecurityHostTestCases \ CtsMonkeyTestCases \ + CtsOsHostTestCases \ CtsThemeHostTestCases \ + CtsUsageHostTestCases \ CtsSecurityHostTestCases \ CtsUsbTests @@ -205,16 +253,14 @@ cts_device_jars := \ CtsDeviceJank \ - CtsJdwpApp \ - CtsPrintInstrument - -cts_device_executables := \ - print-instrument + CtsJdwpApp cts_target_junit_tests := \ CtsJdwp cts_deqp_test_apis := \ + egl \ + gles2 \ gles3 \ gles31 @@ -225,14 +271,8 @@ $(call cts-get-ui-lib-paths,$(cts_ui_tests)) \ $(call cts-get-ui-lib-paths,$(cts_device_jars)) \ $(call cts-get-ui-lib-paths,$(cts_target_junit_tests)) \ - $(call cts-get-executable-paths,$(cts_device_executables)) - -# NOTE: If compiling on a 64 bit target, TARGET_2ND_ARCH will be non-empty -# and will cause the function to expand to the secondary arch object -# directory. If compiling on a 32 bit target, TARGET_2ND_ARCH will be -# empty and will cause the function to expand to the primary arch object -# directory. -CTS_TEST_CASES += $(call cts-get-native-paths,$(cts_native_tests),32,$(TARGET_2ND_ARCH)) + $(call cts-get-executable-paths,$(cts_device_executables)) \ + $(call cts-get-native-paths,$(cts_native_tests),32) ifeq ($(TARGET_IS_64_BIT),true) CTS_TEST_CASES += $(call cts-get-native-paths,$(cts_native_tests),64)
diff --git a/apps/CameraITS/CameraITS.pdf b/apps/CameraITS/CameraITS.pdf index 2430420..8953af9 100644 --- a/apps/CameraITS/CameraITS.pdf +++ b/apps/CameraITS/CameraITS.pdf Binary files differ
diff --git a/apps/CameraITS/pymodules/its/caps.py b/apps/CameraITS/pymodules/its/caps.py index 24f4e75..95f19d9 100644 --- a/apps/CameraITS/pymodules/its/caps.py +++ b/apps/CameraITS/pymodules/its/caps.py
@@ -133,6 +133,17 @@ """ return len(its.objects.get_available_output_sizes("raw10", props)) > 0 +def raw12(props): + """Returns whether a device supports RAW12 output. + + Args: + props: Camera properties object. + + Returns: + Boolean. + """ + return len(its.objects.get_available_output_sizes("raw12", props)) > 0 + def sensor_fusion(props): """Returns whether the camera and motion sensor timestamps for the device are in the same time domain and can be compared directly. @@ -222,6 +233,109 @@ return props.has_key("android.control.aeCompensationRange") and \ props["android.control.aeCompensationRange"] != [0, 0] +def ae_lock(props): + """Returns whether a device supports AE lock + + Args: + props: Camera properties object. + + Return: + Boolean. + """ + return props.has_key("android.control.aeLockAvailable") and \ + props["android.control.aeLockAvailable"] == 1 + +def awb_lock(props): + """Returns whether a device supports AWB lock + + Args: + props: Camera properties object. + + Return: + Boolean. + """ + return props.has_key("android.control.awbLockAvailable") and \ + props["android.control.awbLockAvailable"] == 1 + +def lsc_map(props): + """Returns whether a device supports lens shading map output + + Args: + props: Camera properties object. + + Return: + Boolean. + """ + return props.has_key( + "android.statistics.info.availableLensShadingMapModes") and \ + 1 in props["android.statistics.info.availableLensShadingMapModes"] + +def lsc_off(props): + """Returns whether a device supports disabling lens shading correction + + Args: + props: Camera properties object. + + Return: + Boolean. + """ + return props.has_key( + "android.shading.availableModes") and \ + 0 in props["android.shading.availableModes"] + +def yuv_reprocess(props): + """Returns whether a device supports YUV reprocessing. + + Args: + props: Camera properties object. + + Returns: + Boolean. + """ + return props.has_key("android.request.availableCapabilities") and \ + 7 in props["android.request.availableCapabilities"] + +def private_reprocess(props): + """Returns whether a device supports PRIVATE reprocessing. + + Args: + props: Camera properties object. + + Returns: + Boolean. + """ + return props.has_key("android.request.availableCapabilities") and \ + 4 in props["android.request.availableCapabilities"] + +def noise_reduction_mode(props, mode): + """Returns whether a device supports the noise reduction mode. + + Args: + props: Camera properties objects. + mode: Integer, indicating the noise reduction mode to check for + availability. + + Returns: + Boolean. + """ + return props.has_key( + "android.noiseReduction.availableNoiseReductionModes") and mode \ + in props["android.noiseReduction.availableNoiseReductionModes"]; + +def edge_mode(props, mode): + """Returns whether a device supports the edge mode. + + Args: + props: Camera properties objects. + mode: Integer, indicating the edge mode to check for availability. + + Returns: + Boolean. + """ + return props.has_key( + "android.edge.availableEdgeModes") and mode \ + in props["android.edge.availableEdgeModes"]; + class __UnitTest(unittest.TestCase): """Run a suite of unit tests on this module. """
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py index ad9786e..835a4a4 100644 --- a/apps/CameraITS/pymodules/its/device.py +++ b/apps/CameraITS/pymodules/its/device.py
@@ -41,12 +41,21 @@ sock: The open socket. """ - # Open a connection to localhost:6000, forwarded to port 6000 on the device. - # TODO: Support multiple devices running over different TCP ports. + # Open a connection to localhost:<host_port>, forwarded to port 6000 on the + # device. <host_port> is determined at run-time to support multiple + # connected devices. IPADDR = '127.0.0.1' - PORT = 6000 + REMOTE_PORT = 6000 BUFFER_SIZE = 4096 + # LOCK_PORT is used as a mutex lock to protect the list of forwarded ports + # among all processes. The script assumes LOCK_PORT is available and will + # try to use ports between CLIENT_PORT_START and + # CLIENT_PORT_START+MAX_NUM_PORTS-1 on host for ITS sessions. + CLIENT_PORT_START = 6000 + MAX_NUM_PORTS = 100 + LOCK_PORT = CLIENT_PORT_START + MAX_NUM_PORTS + # Seconds timeout on each socket operation. SOCK_TIMEOUT = 10.0 SEC_TO_NSEC = 1000*1000*1000.0 @@ -58,8 +67,8 @@ EXTRA_SUCCESS = 'camera.its.extra.SUCCESS' EXTRA_SUMMARY = 'camera.its.extra.SUMMARY' - # TODO: Handle multiple connected devices. - ADB = "adb -d" + adb = "adb -d" + device_id = "" # Definitions for some of the common output format options for do_capture(). # Each gets images of full resolution for each requested format. @@ -75,12 +84,83 @@ CAP_RAW_YUV_JPEG = [{"format":"raw"}, {"format":"yuv"}, {"format":"jpeg"}] CAP_DNG_YUV_JPEG = [{"format":"dng"}, {"format":"yuv"}, {"format":"jpeg"}] - # Method to handle the case where the service isn't already running. - # This occurs when a test is invoked directly from the command line, rather - # than as a part of a separate test harness which is setting up the device - # and the TCP forwarding. - def __pre_init(self): + # Initialize the socket port for the host to forward requests to the device. + # This method assumes localhost's LOCK_PORT is available and will try to + # use ports between CLIENT_PORT_START and CLIENT_PORT_START+MAX_NUM_PORTS-1 + def __init_socket_port(self): + NUM_RETRIES = 100 + RETRY_WAIT_TIME_SEC = 0.05 + # Bind a socket to use as mutex lock + socket_lock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + for i in range(NUM_RETRIES): + try: + socket_lock.bind((ItsSession.IPADDR, ItsSession.LOCK_PORT)) + break + except socket.error: + if i == NUM_RETRIES - 1: + raise its.error.Error(self.device_id, + "acquiring socket lock timed out") + else: + time.sleep(RETRY_WAIT_TIME_SEC) + + # Check if a port is already assigned to the device. + command = "adb forward --list" + proc = subprocess.Popen(command.split(), stdout=subprocess.PIPE) + output, error = proc.communicate() + + port = None + used_ports = [] + for line in output.split(os.linesep): + # each line should be formatted as: + # "<device_id> tcp:<host_port> tcp:<remote_port>" + forward_info = line.split() + if len(forward_info) >= 3 and \ + len(forward_info[1]) > 4 and forward_info[1][:4] == "tcp:" and \ + len(forward_info[2]) > 4 and forward_info[2][:4] == "tcp:": + local_p = int(forward_info[1][4:]) + remote_p = int(forward_info[2][4:]) + if forward_info[0] == self.device_id and \ + remote_p == ItsSession.REMOTE_PORT: + port = local_p + break; + else: + used_ports.append(local_p) + + # Find the first available port if no port is assigned to the device. + if port is None: + for p in range(ItsSession.CLIENT_PORT_START, + ItsSession.CLIENT_PORT_START + + ItsSession.MAX_NUM_PORTS): + if p not in used_ports: + # Try to run "adb forward" with the port + command = "%s forward tcp:%d tcp:%d" % \ + (self.adb, p, self.REMOTE_PORT) + proc = subprocess.Popen(command.split(), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + output, error = proc.communicate() + + # Check if there is no error + if error is None or error.find("error") < 0: + port = p + break + + if port is None: + raise its.error.Error(self.device_id, " cannot find an available " + + "port") + + # Release the socket as mutex unlock + socket_lock.close() + + # Connect to the socket + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.connect((self.IPADDR, port)) + self.sock.settimeout(self.SOCK_TIMEOUT) + + # Reboot the device if needed and wait for the service to be ready for + # connection. + def __wait_for_service(self): # This also includes the optional reboot handling: if the user # provides a "reboot" or "reboot=N" arg, then reboot the device, # waiting for N seconds (default 30) before returning. @@ -90,19 +170,19 @@ if len(s) > 7 and s[6] == "=": duration = int(s[7:]) print "Rebooting device" - _run("%s reboot" % (ItsSession.ADB)); - _run("%s wait-for-device" % (ItsSession.ADB)) + _run("%s reboot" % (self.adb)); + _run("%s wait-for-device" % (self.adb)) time.sleep(duration) print "Reboot complete" # TODO: Figure out why "--user 0" is needed, and fix the problem. - _run('%s shell am force-stop --user 0 %s' % (ItsSession.ADB, self.PACKAGE)) + _run('%s shell am force-stop --user 0 %s' % (self.adb, self.PACKAGE)) _run(('%s shell am startservice --user 0 -t text/plain ' - '-a %s') % (ItsSession.ADB, self.INTENT_START)) + '-a %s') % (self.adb, self.INTENT_START)) # Wait until the socket is ready to accept a connection. proc = subprocess.Popen( - ItsSession.ADB.split() + ["logcat"], + self.adb.split() + ["logcat"], stdout=subprocess.PIPE) logcat = proc.stdout while True: @@ -111,15 +191,14 @@ break proc.kill() - # Setup the TCP-over-ADB forwarding. - _run('%s forward tcp:%d tcp:%d' % (ItsSession.ADB,self.PORT,self.PORT)) - def __init__(self): - if "noinit" not in sys.argv: - self.__pre_init() - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.connect((self.IPADDR, self.PORT)) - self.sock.settimeout(self.SOCK_TIMEOUT) + # Initialize device id and adb command. + self.device_id = get_device_id() + self.adb = "adb -s " + self.device_id + + self.__wait_for_service() + self.__init_socket_port() + self.__close_camera() self.__open_camera() @@ -360,7 +439,7 @@ raise its.error.Error('3A failed to converge') return ae_sens, ae_exp, awb_gains, awb_transform, af_dist - def do_capture(self, cap_request, out_surfaces=None): + def do_capture(self, cap_request, out_surfaces=None, reprocess_format=None): """Issue capture request(s), and read back the image(s) and metadata. The main top-level function for capturing one or more images using the @@ -369,8 +448,8 @@ The out_surfaces field can specify the width(s), height(s), and format(s) of the captured image. The formats may be "yuv", "jpeg", - "dng", "raw", or "raw10". The default is a YUV420 frame ("yuv") - corresponding to a full sensor frame. + "dng", "raw", "raw10", "raw12", or "rawStats". The default is a YUV420 + frame ("yuv") corresponding to a full sensor frame. Note that one or more surfaces can be specified, allowing a capture to request images back in multiple formats (e.g.) raw+yuv, raw+jpeg, @@ -379,6 +458,18 @@ surface. At most one output surface can be specified for a given format, and raw+dng, raw10+dng, and raw+raw10 are not supported as combinations. + If reprocess_format is not None, for each request, an intermediate + buffer of the given reprocess_format will be captured from camera and + the intermediate buffer will be reprocessed to the output surfaces. The + following settings will be turned off when capturing the intermediate + buffer and will be applied when reprocessing the intermediate buffer. + 1. android.noiseReduction.mode + 2. android.edge.mode + 3. android.reprocess.effectiveExposureFactor + + Supported reprocess format are "yuv" and "private". Supported output + surface formats when reprocessing is enabled are "yuv" and "jpeg". + Example of a single capture request: { @@ -445,11 +536,32 @@ yuv_caps = do_capture( [req1,req2], yuv_fmt ) yuv_caps, raw_caps = do_capture( [req1,req2], [yuv_fmt,raw_fmt] ) + The "rawStats" format processes the raw image and returns a new image + of statistics from the raw image. The format takes additional keys, + "gridWidth" and "gridHeight" which are size of grid cells in a 2D grid + of the raw image. For each grid cell, the mean and variance of each raw + channel is computed, and the do_capture call returns two 4-element float + images of dimensions (rawWidth / gridWidth, rawHeight / gridHeight), + concatenated back-to-back, where the first iamge contains the 4-channel + means and the second contains the 4-channel variances. + + For the rawStats format, if the gridWidth is not provided then the raw + image width is used as the default, and similarly for gridHeight. With + this, the following is an example of a output description that computes + the mean and variance across each image row: + + { + "gridHeight": 1, + "format": "rawStats" + } + Args: cap_request: The Python dict/list specifying the capture(s), which will be converted to JSON and sent to the device. out_surfaces: (Optional) specifications of the output image formats and sizes to use for each capture. + reprocess_format: (Optional) The reprocessing format. If not None, + reprocessing will be enabled. Returns: An object, list of objects, or list of lists of objects, where each @@ -457,11 +569,16 @@ * data: the image data as a numpy array of bytes. * width: the width of the captured image. * height: the height of the captured image. - * format: image the format, in ["yuv","jpeg","raw","raw10","dng"]. + * format: image the format, in [ + "yuv","jpeg","raw","raw10","raw12","rawStats","dng"]. * metadata: the capture result object (Python dictionary). """ cmd = {} - cmd["cmdName"] = "doCapture" + if reprocess_format != None: + cmd["cmdName"] = "doReprocessCapture" + cmd["reprocessFormat"] = reprocess_format + else: + cmd["cmdName"] = "doCapture" if not isinstance(cap_request, list): cmd["captureRequests"] = [cap_request] else: @@ -480,9 +597,13 @@ nsurf = 1 if out_surfaces is None else len(cmd["outputSurfaces"]) if len(formats) > len(set(formats)): raise its.error.Error('Duplicate format requested') - if "dng" in formats and "raw" in formats or \ - "dng" in formats and "raw10" in formats or \ - "raw" in formats and "raw10" in formats: + raw_formats = 0; + raw_formats += 1 if "dng" in formats else 0 + raw_formats += 1 if "raw" in formats else 0 + raw_formats += 1 if "raw10" in formats else 0 + raw_formats += 1 if "raw12" in formats else 0 + raw_formats += 1 if "rawStats" in formats else 0 + if raw_formats > 1: raise its.error.Error('Different raw formats not supported') # Detect long exposure time and set timeout accordingly @@ -506,14 +627,16 @@ # the burst, however individual images of different formats can come # out in any order for that capture. nbufs = 0 - bufs = {"yuv":[], "raw":[], "raw10":[], "dng":[], "jpeg":[]} + bufs = {"yuv":[], "raw":[], "raw10":[], "raw12":[], + "rawStats":[], "dng":[], "jpeg":[]} mds = [] widths = None heights = None while nbufs < ncap*nsurf or len(mds) < ncap: jsonObj,buf = self.__read_response_from_socket() if jsonObj['tag'] in ['jpegImage', 'yuvImage', 'rawImage', \ - 'raw10Image', 'dngImage'] and buf is not None: + 'raw10Image', 'raw12Image', 'rawStatsImage', 'dngImage'] \ + and buf is not None: fmt = jsonObj['tag'][:-5] bufs[fmt].append(buf) nbufs += 1 @@ -540,10 +663,52 @@ self.sock.settimeout(self.SOCK_TIMEOUT) return rets if len(rets)>1 else rets[0] -def report_result(camera_id, success, summary_path=None): +def get_device_id(): + """ Return the ID of the device that the test is running on. + + Return the device ID provided in the command line if it's connected. If no + device ID is provided in the command line and there is only one device + connected, return the device ID by parsing the result of "adb devices". + + Raise an exception if no device is connected; or the device ID provided in + the command line is not connected; or no device ID is provided in the + command line and there are more than 1 device connected. + + Returns: + Device ID string. + """ + device_id = None + for s in sys.argv[1:]: + if s[:7] == "device=" and len(s) > 7: + device_id = str(s[7:]) + + # Get a list of connected devices + devices = [] + command = "adb devices" + proc = subprocess.Popen(command.split(), stdout=subprocess.PIPE) + output, error = proc.communicate() + for line in output.split(os.linesep): + device_info = line.split() + if len(device_info) == 2 and device_info[1] == "device": + devices.append(device_info[0]) + + if len(devices) == 0: + raise its.error.Error("No device is connected!") + elif device_id is not None and device_id not in devices: + raise its.error.Error(device_id + " is not connected!") + elif device_id is None and len(devices) >= 2: + raise its.error.Error("More than 1 device are connected. " + + "Use device=<device_id> to specify a device to test.") + elif len(devices) == 1: + device_id = devices[0] + + return device_id + +def report_result(device_id, camera_id, success, summary_path=None): """Send a pass/fail result to the device, via an intent. Args: + device_id: The ID string of the device to report the results to. camera_id: The ID string of the camera for which to report pass/fail. success: Boolean, indicating if the result was pass or fail. summary_path: (Optional) path to ITS summary file on host PC @@ -551,18 +716,19 @@ Returns: Nothing. """ + adb = "adb -s " + device_id device_summary_path = "/sdcard/camera_" + camera_id + "_its_summary.txt" if summary_path is not None: _run("%s push %s %s" % ( - ItsSession.ADB, summary_path, device_summary_path)) + adb, summary_path, device_summary_path)) _run("%s shell am broadcast -a %s --es %s %s --es %s %s --es %s %s" % ( - ItsSession.ADB, ItsSession.ACTION_ITS_RESULT, + adb, ItsSession.ACTION_ITS_RESULT, ItsSession.EXTRA_CAMERA_ID, camera_id, ItsSession.EXTRA_SUCCESS, 'True' if success else 'False', ItsSession.EXTRA_SUMMARY, device_summary_path)) else: _run("%s shell am broadcast -a %s --es %s %s --es %s %s --es %s %s" % ( - ItsSession.ADB, ItsSession.ACTION_ITS_RESULT, + adb, ItsSession.ACTION_ITS_RESULT, ItsSession.EXTRA_CAMERA_ID, camera_id, ItsSession.EXTRA_SUCCESS, 'True' if success else 'False', ItsSession.EXTRA_SUMMARY, "null"))
diff --git a/apps/CameraITS/pymodules/its/image.py b/apps/CameraITS/pymodules/its/image.py index b3bdb65..a5ac60b 100644 --- a/apps/CameraITS/pymodules/its/image.py +++ b/apps/CameraITS/pymodules/its/image.py
@@ -64,11 +64,14 @@ if cap["format"] == "raw10": assert(props is not None) cap = unpack_raw10_capture(cap, props) + if cap["format"] == "raw12": + assert(props is not None) + cap = unpack_raw12_capture(cap, props) if cap["format"] == "yuv": y = cap["data"][0:w*h] u = cap["data"][w*h:w*h*5/4] v = cap["data"][w*h*5/4:w*h*6/4] - return convert_yuv420_to_rgb_image(y, u, v, w, h) + return convert_yuv420_planar_to_rgb_image(y, u, v, w, h) elif cap["format"] == "jpeg": return decompress_jpeg_to_rgb_image(cap["data"]) elif cap["format"] == "raw": @@ -78,6 +81,25 @@ else: raise its.error.Error('Invalid format %s' % (cap["format"])) +def unpack_rawstats_capture(cap): + """Unpack a rawStats capture to the mean and variance images. + + Args: + cap: A capture object as returned by its.device.do_capture. + + Returns: + Tuple (mean_image var_image) of float-4 images, with non-normalized + pixel values computed from the RAW16 images on the device + """ + assert(cap["format"] == "rawStats") + w = cap["width"] + h = cap["height"] + img = numpy.ndarray(shape=(2*h*w*4,), dtype='<f', buffer=cap["data"]) + analysis_image = img.reshape(2,h,w,4) + mean_image = analysis_image[0,:,:,:].reshape(h,w,4) + var_image = analysis_image[1,:,:,:].reshape(h,w,4) + return mean_image, var_image + def unpack_raw10_capture(cap, props): """Unpack a raw-10 capture to a raw-16 capture. @@ -114,12 +136,12 @@ raise its.error.Error('Invalid raw-10 buffer width') w = img.shape[1]*4/5 h = img.shape[0] - # Cut out the 4x8b MSBs and shift to bits [10:2] in 16b words. + # Cut out the 4x8b MSBs and shift to bits [9:2] in 16b words. msbs = numpy.delete(img, numpy.s_[4::5], 1) msbs = msbs.astype(numpy.uint16) msbs = numpy.left_shift(msbs, 2) msbs = msbs.reshape(h,w) - # Cut out the 4x2b LSBs and put each in bits [2:0] of their own 8b words. + # Cut out the 4x2b LSBs and put each in bits [1:0] of their own 8b words. lsbs = img[::, 4::5].reshape(h,w/4) lsbs = numpy.right_shift( numpy.packbits(numpy.unpackbits(lsbs).reshape(h,w/4,4,2),3), 6) @@ -128,6 +150,56 @@ img16 = numpy.bitwise_or(msbs, lsbs).reshape(h,w) return img16 +def unpack_raw12_capture(cap, props): + """Unpack a raw-12 capture to a raw-16 capture. + + Args: + cap: A raw-12 capture object. + props: Camera properties object. + + Returns: + New capture object with raw-16 data. + """ + # Data is packed as 4x10b pixels in 5 bytes, with the first 4 bytes holding + # the MSBs of the pixels, and the 5th byte holding 4x2b LSBs. + w,h = cap["width"], cap["height"] + if w % 2 != 0: + raise its.error.Error('Invalid raw-12 buffer width') + cap = copy.deepcopy(cap) + cap["data"] = unpack_raw12_image(cap["data"].reshape(h,w*3/2)) + cap["format"] = "raw" + return cap + +def unpack_raw12_image(img): + """Unpack a raw-12 image to a raw-16 image. + + Output image will have the 12 LSBs filled in each 16b word, and the 4 MSBs + will be set to zero. + + Args: + img: A raw-12 image, as a uint8 numpy array. + + Returns: + Image as a uint16 numpy array, with all row padding stripped. + """ + if img.shape[1] % 3 != 0: + raise its.error.Error('Invalid raw-12 buffer width') + w = img.shape[1]*2/3 + h = img.shape[0] + # Cut out the 2x8b MSBs and shift to bits [11:4] in 16b words. + msbs = numpy.delete(img, numpy.s_[2::3], 1) + msbs = msbs.astype(numpy.uint16) + msbs = numpy.left_shift(msbs, 4) + msbs = msbs.reshape(h,w) + # Cut out the 2x4b LSBs and put each in bits [3:0] of their own 8b words. + lsbs = img[::, 2::3].reshape(h,w/2) + lsbs = numpy.right_shift( + numpy.packbits(numpy.unpackbits(lsbs).reshape(h,w/2,2,4),3), 4) + lsbs = lsbs.reshape(h,w) + # Fuse the MSBs and LSBs back together + img16 = numpy.bitwise_or(msbs, lsbs).reshape(h,w) + return img16 + def convert_capture_to_planes(cap, props=None): """Convert a captured image object to separate image planes. @@ -158,6 +230,9 @@ if cap["format"] == "raw10": assert(props is not None) cap = unpack_raw10_capture(cap, props) + if cap["format"] == "raw12": + assert(props is not None) + cap = unpack_raw12_capture(cap, props) if cap["format"] == "yuv": y = cap["data"][0:w*h] u = cap["data"][w*h:w*h*5/4] @@ -176,6 +251,36 @@ img = numpy.ndarray(shape=(h*w,), dtype='<u2', buffer=cap["data"][0:w*h*2]) img = img.astype(numpy.float32).reshape(h,w) / white_level + # Crop the raw image to the active array region. + if props.has_key("android.sensor.info.activeArraySize") \ + and props["android.sensor.info.activeArraySize"] is not None \ + and props.has_key("android.sensor.info.pixelArraySize") \ + and props["android.sensor.info.pixelArraySize"] is not None: + # Note that the Rect class is defined such that the left,top values + # are "inside" while the right,bottom values are "outside"; that is, + # it's inclusive of the top,left sides only. So, the width is + # computed as right-left, rather than right-left+1, etc. + wfull = props["android.sensor.info.pixelArraySize"]["width"] + hfull = props["android.sensor.info.pixelArraySize"]["height"] + xcrop = props["android.sensor.info.activeArraySize"]["left"] + ycrop = props["android.sensor.info.activeArraySize"]["top"] + wcrop = props["android.sensor.info.activeArraySize"]["right"]-xcrop + hcrop = props["android.sensor.info.activeArraySize"]["bottom"]-ycrop + assert(wfull >= wcrop >= 0) + assert(hfull >= hcrop >= 0) + assert(wfull - wcrop >= xcrop >= 0) + assert(hfull - hcrop >= ycrop >= 0) + if w == wfull and h == hfull: + # Crop needed; extract the center region. + img = img[ycrop:ycrop+hcrop,xcrop:xcrop+wcrop] + w = wcrop + h = hcrop + elif w == wcrop and h == hcrop: + # No crop needed; image is already cropped to the active array. + None + else: + raise its.error.Error('Invalid image size metadata') + # Separate the image planes. imgs = [img[::2].reshape(w*h/2)[::2].reshape(h/2,w/2,1), img[::2].reshape(w*h/2)[1::2].reshape(h/2,w/2,1), img[1::2].reshape(w*h/2)[::2].reshape(h/2,w/2,1), @@ -285,10 +390,10 @@ img = numpy.dot(img.reshape(w*h,3), ccm.T).reshape(h,w,3).clip(0.0,1.0) return img -def convert_yuv420_to_rgb_image(y_plane, u_plane, v_plane, - w, h, - ccm_yuv_to_rgb=DEFAULT_YUV_TO_RGB_CCM, - yuv_off=DEFAULT_YUV_OFFSETS): +def convert_yuv420_planar_to_rgb_image(y_plane, u_plane, v_plane, + w, h, + ccm_yuv_to_rgb=DEFAULT_YUV_TO_RGB_CCM, + yuv_off=DEFAULT_YUV_OFFSETS): """Convert a YUV420 8-bit planar image to an RGB image. Args: @@ -316,16 +421,44 @@ rgb.reshape(w*h*3)[:] = flt.reshape(w*h*3)[:] return rgb.astype(numpy.float32) / 255.0 +def load_rgb_image(fname): + """Load a standard image file (JPG, PNG, etc.). + + Args: + fname: The path of the file to load. + + Returns: + RGB float-3 image array, with pixel values in [0.0, 1.0]. + """ + img = Image.open(fname) + w = img.size[0] + h = img.size[1] + a = numpy.array(img) + if len(a.shape) == 3 and a.shape[2] == 3: + # RGB + return a.reshape(h,w,3) / 255.0 + elif len(a.shape) == 2 or len(a.shape) == 3 and a.shape[2] == 1: + # Greyscale; convert to RGB + return a.reshape(h*w).repeat(3).reshape(h,w,3) / 255.0 + else: + raise its.error.Error('Unsupported image type') + def load_yuv420_to_rgb_image(yuv_fname, w, h, + layout="planar", ccm_yuv_to_rgb=DEFAULT_YUV_TO_RGB_CCM, yuv_off=DEFAULT_YUV_OFFSETS): """Load a YUV420 image file, and return as an RGB image. + Supported layouts include "planar" and "nv21". The "yuv" formatted captures + returned from the device via do_capture are in the "planar" layout; other + layouts may only be needed for loading files from other sources. + Args: yuv_fname: The path of the YUV420 file. w: The width of the image. h: The height of the image. + layout: (Optional) the layout of the YUV data (as a string). ccm_yuv_to_rgb: (Optional) the 3x3 CCM to convert from YUV to RGB. yuv_off: (Optional) offsets to subtract from each of Y,U,V values. @@ -333,13 +466,24 @@ RGB float-3 image array, with pixel values in [0.0, 1.0]. """ with open(yuv_fname, "rb") as f: - y = numpy.fromfile(f, numpy.uint8, w*h, "") - v = numpy.fromfile(f, numpy.uint8, w*h/4, "") - u = numpy.fromfile(f, numpy.uint8, w*h/4, "") - return convert_yuv420_to_rgb_image(y,u,v,w,h,ccm_yuv_to_rgb,yuv_off) + if layout == "planar": + # Plane of Y, plane of V, plane of U. + y = numpy.fromfile(f, numpy.uint8, w*h, "") + v = numpy.fromfile(f, numpy.uint8, w*h/4, "") + u = numpy.fromfile(f, numpy.uint8, w*h/4, "") + elif layout == "nv21": + # Plane of Y, plane of interleaved VUVUVU... + y = numpy.fromfile(f, numpy.uint8, w*h, "") + vu = numpy.fromfile(f, numpy.uint8, w*h/2, "") + v = vu[0::2] + u = vu[1::2] + else: + raise its.error.Error('Unsupported image layout') + return convert_yuv420_planar_to_rgb_image( + y,u,v,w,h,ccm_yuv_to_rgb,yuv_off) -def load_yuv420_to_yuv_planes(yuv_fname, w, h): - """Load a YUV420 image file, and return separate Y, U, and V plane images. +def load_yuv420_planar_to_yuv_planes(yuv_fname, w, h): + """Load a YUV420 planar image file, and return Y, U, and V plane images. Args: yuv_fname: The path of the YUV420 file. @@ -479,6 +623,21 @@ variances.append(numpy.var(img[:,:,i], dtype=numpy.float64)) return variances +def compute_image_snrs(img): + """Calculate the SNR (db) of each color channel in the image. + + Args: + img: Numpy float image array, with pixel values in [0,1]. + + Returns: + A list of SNR value, one per color channel in the image. + """ + means = compute_image_means(img) + variances = compute_image_variances(img) + std_devs = [math.sqrt(v) for v in variances] + snr = [20 * math.log10(m/s) for m,s in zip(means, std_devs)] + return snr + def write_image(img, fname, apply_gamma=False): """Save a float-3 numpy array image to a file. @@ -540,169 +699,24 @@ img = numpy.vstack(chs).T.reshape(h/f,w/f,chans) return img -def __get_color_checker_patch(img, xc,yc, patch_size): - r = patch_size/2 - tile = img[yc-r:yc+r:, xc-r:xc+r:, ::] - return tile - -def __measure_color_checker_patch(img, xc,yc, patch_size): - tile = __get_color_checker_patch(img, xc,yc, patch_size) - means = tile.mean(1).mean(0) - return means - -def get_color_checker_chart_patches(img, debug_fname_prefix=None): - """Return the center coords of each patch in a color checker chart. - - Assumptions: - * Chart is vertical or horizontal w.r.t. camera, but not diagonal. - * Chart is (roughly) planar-parallel to the camera. - * Chart is centered in frame (roughly). - * Around/behind chart is white/grey background. - * The only black pixels in the image are from the chart. - * Chart is 100% visible and contained within image. - * No other objects within image. - * Image is well-exposed. - * Standard color checker chart with standard-sized black borders. - - The values returned are in the coordinate system of the chart; that is, - patch (0,0) is the brown patch that is in the chart's top-left corner when - it is in the normal upright/horizontal orientation. (The chart may be any - of the four main orientations in the image.) +def compute_image_sharpness(img): + """Calculate the sharpness of input image. Args: - img: Input image, as a numpy array with pixels in [0,1]. - debug_fname_prefix: If not None, the (string) name of a file prefix to - use to save a number of debug images for visualizing the output of - this function; can be used to see if the patches are being found - successfully. + img: Numpy float RGB/luma image array, with pixel values in [0,1]. Returns: - 6x4 list of lists of integer (x,y) coords of the center of each patch, - ordered in the "chart order" (6x4 row major). + A sharpness estimation value based on the average of gradient magnitude. + Larger value means the image is sharper. """ + chans = img.shape[2] + assert(chans == 1 or chans == 3) + luma = img + if (chans == 3): + luma = 0.299 * img[:,:,0] + 0.587 * img[:,:,1] + 0.114 * img[:,:,2] - # Shrink the original image. - DOWNSCALE_FACTOR = 4 - img_small = downscale_image(img, DOWNSCALE_FACTOR) - - # Make a threshold image, which is 1.0 where the image is black, - # and 0.0 elsewhere. - BLACK_PIXEL_THRESH = 0.2 - mask_img = scipy.stats.threshold( - img_small.max(2), BLACK_PIXEL_THRESH, 1.1, 0.0) - mask_img = 1.0 - scipy.stats.threshold(mask_img, -0.1, 0.1, 1.0) - - if debug_fname_prefix is not None: - h,w = mask_img.shape - write_image(img, debug_fname_prefix+"_0.jpg") - write_image(mask_img.repeat(3).reshape(h,w,3), - debug_fname_prefix+"_1.jpg") - - # Mask image flattened to a single row or column (by averaging). - # Also apply a threshold to these arrays. - FLAT_PIXEL_THRESH = 0.05 - flat_row = mask_img.mean(0) - flat_col = mask_img.mean(1) - flat_row = [0 if v < FLAT_PIXEL_THRESH else 1 for v in flat_row] - flat_col = [0 if v < FLAT_PIXEL_THRESH else 1 for v in flat_col] - - # Start and end of the non-zero region of the flattened row/column. - flat_row_nonzero = [i for i in range(len(flat_row)) if flat_row[i]>0] - flat_col_nonzero = [i for i in range(len(flat_col)) if flat_col[i]>0] - flat_row_min, flat_row_max = min(flat_row_nonzero), max(flat_row_nonzero) - flat_col_min, flat_col_max = min(flat_col_nonzero), max(flat_col_nonzero) - - # Orientation of chart, and number of grid cells horz. and vertically. - orient = "h" if flat_row_max-flat_row_min>flat_col_max-flat_col_min else "v" - xgrids = 6 if orient=="h" else 4 - ygrids = 6 if orient=="v" else 4 - - # Get better bounds on the patches region, lopping off some of the excess - # black border. - HRZ_BORDER_PAD_FRAC = 0.0138 - VERT_BORDER_PAD_FRAC = 0.0395 - xpad = HRZ_BORDER_PAD_FRAC if orient=="h" else VERT_BORDER_PAD_FRAC - ypad = HRZ_BORDER_PAD_FRAC if orient=="v" else VERT_BORDER_PAD_FRAC - xchart = flat_row_min + (flat_row_max - flat_row_min) * xpad - ychart = flat_col_min + (flat_col_max - flat_col_min) * ypad - wchart = (flat_row_max - flat_row_min) * (1 - 2*xpad) - hchart = (flat_col_max - flat_col_min) * (1 - 2*ypad) - - # Get the colors of the 4 corner patches, in clockwise order, by measuring - # the average value of a small patch at each of the 4 patch centers. - colors = [] - centers = [] - for (x,y) in [(0,0), (xgrids-1,0), (xgrids-1,ygrids-1), (0,ygrids-1)]: - xc = xchart + (x + 0.5)*wchart/xgrids - yc = ychart + (y + 0.5)*hchart/ygrids - xc = int(xc * DOWNSCALE_FACTOR + 0.5) - yc = int(yc * DOWNSCALE_FACTOR + 0.5) - centers.append((xc,yc)) - chan_means = __measure_color_checker_patch(img, xc,yc, 32) - colors.append(sum(chan_means) / len(chan_means)) - - # The brightest corner is the white patch, the darkest is the black patch. - # The black patch should be counter-clockwise from the white patch. - white_patch_index = None - for i in range(4): - if colors[i] == max(colors) and \ - colors[(i-1+4)%4] == min(colors): - white_patch_index = i%4 - assert(white_patch_index is not None) - - # Return the coords of the origin (top-left when the chart is in the normal - # upright orientation) patch's center, and the vector displacement to the - # center of the second patch on the first row of the chart (when in the - # normal upright orientation). - origin_index = (white_patch_index+1)%4 - prev_index = (origin_index-1+4)%4 - next_index = (origin_index+1)%4 - origin_center = centers[origin_index] - prev_center = centers[prev_index] - next_center = centers[next_index] - vec_across = tuple([(next_center[i]-origin_center[i])/5.0 for i in [0,1]]) - vec_down = tuple([(prev_center[i]-origin_center[i])/3.0 for i in [0,1]]) - - # Compute the center of each patch. - patches = [[],[],[],[]] - for yi in range(4): - for xi in range(6): - x0,y0 = origin_center - dxh,dyh = vec_across - dxv,dyv = vec_down - xc = int(x0 + dxh*xi + dxv*yi) - yc = int(y0 + dyh*xi + dyv*yi) - patches[yi].append((xc,yc)) - - # Sanity check: test that the R,G,B,black,white patches are correct. - sanity_failed = False - patch_info = [(2,2,[0]), # Red - (2,1,[1]), # Green - (2,0,[2]), # Blue - (3,0,[0,1,2]), # White - (3,5,[])] # Black - for i in range(len(patch_info)): - yi,xi,high_chans = patch_info[i] - low_chans = [i for i in [0,1,2] if i not in high_chans] - xc,yc = patches[yi][xi] - means = __measure_color_checker_patch(img, xc,yc, 64) - if (min([means[i] for i in high_chans]+[1]) < \ - max([means[i] for i in low_chans]+[0])): - sanity_failed = True - - if debug_fname_prefix is not None: - gridimg = numpy.zeros([4*(32+2), 6*(32+2), 3]) - for yi in range(4): - for xi in range(6): - xc,yc = patches[yi][xi] - tile = __get_color_checker_patch(img, xc,yc, 32) - gridimg[yi*(32+2)+1:yi*(32+2)+1+32, - xi*(32+2)+1:xi*(32+2)+1+32, :] = tile - write_image(gridimg, debug_fname_prefix+"_2.png") - - assert(not sanity_failed) - - return patches + [gy, gx] = numpy.gradient(luma) + return numpy.average(numpy.sqrt(gy*gy + gx*gx)) class __UnitTest(unittest.TestCase): """Run a suite of unit tests on this module.
diff --git a/apps/CameraITS/pymodules/its/objects.py b/apps/CameraITS/pymodules/its/objects.py index 5967599..ac384fb 100644 --- a/apps/CameraITS/pymodules/its/objects.py +++ b/apps/CameraITS/pymodules/its/objects.py
@@ -70,7 +70,8 @@ else: return float(r["numerator"]) / float(r["denominator"]) -def manual_capture_request(sensitivity, exp_time, linear_tonemap=False): +def manual_capture_request( + sensitivity, exp_time, linear_tonemap=False, props=None): """Return a capture request with everything set to manual. Uses identity/unit color correction, and the default tonemap curve. @@ -82,6 +83,9 @@ with. linear_tonemap: [Optional] whether a linear tonemap should be used in this request. + props: [Optional] the object returned from + its.device.get_camera_properties(). Must present when + linear_tonemap is True. Returns: The default manual capture request, ready to be passed to the @@ -105,10 +109,20 @@ "android.shading.mode": 1 } if linear_tonemap: - req["android.tonemap.mode"] = 0 - req["android.tonemap.curveRed"] = [0.0,0.0, 1.0,1.0] - req["android.tonemap.curveGreen"] = [0.0,0.0, 1.0,1.0] - req["android.tonemap.curveBlue"] = [0.0,0.0, 1.0,1.0] + assert(props is not None) + #CONTRAST_CURVE mode + if 0 in props["android.tonemap.availableToneMapModes"]: + req["android.tonemap.mode"] = 0 + req["android.tonemap.curveRed"] = [0.0,0.0, 1.0,1.0] + req["android.tonemap.curveGreen"] = [0.0,0.0, 1.0,1.0] + req["android.tonemap.curveBlue"] = [0.0,0.0, 1.0,1.0] + #GAMMA_VALUE mode + elif 3 in props["android.tonemap.availableToneMapModes"]: + req["android.tonemap.mode"] = 3 + req["android.tonemap.gamma"] = 1.0 + else: + print "Linear tonemap is not supported" + assert(False) return req def auto_capture_request(): @@ -142,7 +156,8 @@ """Return a sorted list of available output sizes for a given format. Args: - fmt: the output format, as a string in ["jpg", "yuv", "raw"]. + fmt: the output format, as a string in + ["jpg", "yuv", "raw", "raw10", "raw12"]. props: the object returned from its.device.get_camera_properties(). max_size: (Optional) A (w,h) tuple. Sizes larger than max_size (either w or h) will be discarded. @@ -154,7 +169,8 @@ A sorted list of (w,h) tuples (sorted large-to-small). """ AR_TOLERANCE = 0.03 - fmt_codes = {"raw":0x20, "raw10":0x25, "yuv":0x23, "jpg":0x100, "jpeg":0x100} + fmt_codes = {"raw":0x20, "raw10":0x25, "raw12":0x26,"yuv":0x23, + "jpg":0x100, "jpeg":0x100} configs = props['android.scaler.streamConfigurationMap']\ ['availableStreamConfigurations'] fmt_configs = [cfg for cfg in configs if cfg['format'] == fmt_codes[fmt]]
diff --git a/apps/CameraITS/tests/dng_noise_model/DngNoiseModel.pdf b/apps/CameraITS/tests/dng_noise_model/DngNoiseModel.pdf index 01389fa..d979a06 100644 --- a/apps/CameraITS/tests/dng_noise_model/DngNoiseModel.pdf +++ b/apps/CameraITS/tests/dng_noise_model/DngNoiseModel.pdf Binary files differ
diff --git a/apps/CameraITS/tests/dng_noise_model/dng_noise_model.py b/apps/CameraITS/tests/dng_noise_model/dng_noise_model.py index 19b6c92..8f4682a 100644 --- a/apps/CameraITS/tests/dng_noise_model/dng_noise_model.py +++ b/apps/CameraITS/tests/dng_noise_model/dng_noise_model.py
@@ -13,144 +13,249 @@ # limitations under the License. import its.device +import its.caps import its.objects import its.image -import pprint -import pylab import os.path +import pylab import matplotlib -import matplotlib.pyplot -import numpy +import matplotlib.pyplot as plt import math +import Image +import time +import numpy as np +import scipy.stats +import scipy.signal + +# Convert a 2D array a to a 4D array with dimensions [tile_size, +# tile_size, row, col] where row, col are tile indices. +def tile(a, tile_size): + tile_rows, tile_cols = a.shape[0]/tile_size, a.shape[1]/tile_size + a = a.reshape([tile_rows, tile_size, tile_cols, tile_size]) + a = a.transpose([1, 3, 0, 2]) + return a def main(): - """Compute the DNG noise model from a color checker chart. - - TODO: Make this more robust; some manual futzing may be needed. + """Capture a set of raw images with increasing gains and measure the noise. """ NAME = os.path.basename(__file__).split(".")[0] - with its.device.ItsSession() as cam: + # How many sensitivities per stop to sample. + steps_per_stop = 2 + # How large of tiles to use to compute mean/variance. + tile_size = 64 + # Exposure bracketing range in stops + bracket_stops = 4 + # How high to allow the mean of the tiles to go. + max_signal_level = 0.5 + # Colors used for plotting the data for each exposure. + colors = 'rygcbm' + # Define a first order high pass filter to eliminate low frequency + # signal content when computing variance. + f = np.array([-1, 1]).astype('float32') + # Make it a higher order filter by convolving the first order + # filter with itself a few times. + f = np.convolve(f, f) + f = np.convolve(f, f) + + # Compute the normalization of the filter to preserve noise + # power. Let a be the normalization factor we're looking for, and + # Let X and X' be the random variables representing the noise + # before and after filtering, respectively. First, compute + # Var[a*X']: + # + # Var[a*X'] = a^2*Var[X*f_0 + X*f_1 + ... + X*f_N-1] + # = a^2*(f_0^2*Var[X] + f_1^2*Var[X] + ... + (f_N-1)^2*Var[X]) + # = sum(f_i^2)*a^2*Var[X] + # + # We want Var[a*X'] to be equal to Var[X]: + # + # sum(f_i^2)*a^2*Var[X] = Var[X] -> a = sqrt(1/sum(f_i^2)) + # + # We can just bake this normalization factor into the high pass + # filter kernel. + f = f/math.sqrt(np.dot(f, f)) + + bracket_factor = math.pow(2, bracket_stops) + + with its.device.ItsSession() as cam: props = cam.get_camera_properties() - white_level = float(props['android.sensor.info.whiteLevel']) + # Get basic properties we need. + sens_min, sens_max = props['android.sensor.info.sensitivityRange'] + sens_max_analog = props['android.sensor.maxAnalogSensitivity'] + white_level = props['android.sensor.info.whiteLevel'] black_levels = props['android.sensor.blackLevelPattern'] idxs = its.image.get_canonical_cfa_order(props) black_levels = [black_levels[i] for i in idxs] - # Expose for the scene with min sensitivity - sens_min, sens_max = props['android.sensor.info.sensitivityRange'] - s_ae,e_ae,awb_gains,awb_ccm,_ = cam.do_3a(get_results=True) - s_e_prod = s_ae * e_ae + print "Sensitivity range: [%f, %f]" % (sens_min, sens_max) + print "Max analog sensitivity: %f" % (sens_max_analog) - # Make the image brighter since the script looks at linear Bayer - # raw patches rather than gamma-encoded YUV patches (and the AE - # probably under-exposes a little for this use-case). - s_e_prod *= 2 + # Do AE to get a rough idea of where we are. + s_ae,e_ae,_,_,_ = \ + cam.do_3a(get_results=True, do_awb=False, do_af=False) + # Underexpose to get more data for low signal levels. + auto_e = s_ae*e_ae/bracket_factor - # Capture raw frames across the full sensitivity range. - NUM_SENS_STEPS = 9 - sens_step = int((sens_max - sens_min - 1) / float(NUM_SENS_STEPS)) - reqs = [] - sens = [] - for s in range(sens_min, sens_max, sens_step): - e = int(s_e_prod / float(s)) - req = its.objects.manual_capture_request(s, e) - req["android.colorCorrection.transform"] = \ - its.objects.float_to_rational(awb_ccm) - req["android.colorCorrection.gains"] = awb_gains - reqs.append(req) - sens.append(s) + # If the auto-exposure result is too bright for the highest + # sensitivity or too dark for the lowest sensitivity, report + # an error. + min_exposure_ns, max_exposure_ns = \ + props['android.sensor.info.exposureTimeRange'] + if auto_e < min_exposure_ns*sens_max: + raise its.error.Error("Scene is too bright to properly expose \ + at the highest sensitivity") + if auto_e*bracket_factor > max_exposure_ns*sens_min: + raise its.error.Error("Scene is too dark to properly expose \ + at the lowest sensitivity") - caps = cam.do_capture(reqs, cam.CAP_RAW) + # Start the sensitivities at the minimum. + s = sens_min - # A list of the (x,y) coords of the center pixel of a collection of - # patches of a color checker chart. Each patch should be uniform, - # however the actual color doesn't matter. Note that the coords are - # relative to the *converted* RGB image, which is 1/2 x 1/2 of the - # full size; convert back to full. - img = its.image.convert_capture_to_rgb_image(caps[0], props=props) - patches = its.image.get_color_checker_chart_patches(img, NAME+"_debug") - patches = [(2*x,2*y) for (x,y) in sum(patches,[])] + samples = [] + plots = [] + measured_models = [] + while s <= sens_max + 1: + print "ISO %d" % round(s) + fig = plt.figure() + plt_s = fig.gca() + plt_s.set_title("ISO %d" % round(s)) + plt_s.set_xlabel("Mean signal level") + plt_s.set_ylabel("Variance") - lines = [] - for iouter, (s,cap) in enumerate(zip(sens,caps)): - # For each capture, compute the mean value in each patch, for each - # Bayer plane; discard patches where pixels are close to clamped. - # Also compute the variance. - CLAMP_THRESH = 0.2 - planes = its.image.convert_capture_to_planes(cap, props) - points = [] - for i,plane in enumerate(planes): - plane = (plane * white_level - black_levels[i]) / ( - white_level - black_levels[i]) - for j,(x,y) in enumerate(patches): - tile = plane[y/2-16:y/2+16:,x/2-16:x/2+16:,::] - mean = its.image.compute_image_means(tile)[0] - var = its.image.compute_image_variances(tile)[0] - if (mean > CLAMP_THRESH and mean < 1.0-CLAMP_THRESH): - # Each point is a (mean,variance) tuple for a patch; - # for a given ISO, there should be a linear - # relationship between these values. - points.append((mean,var)) + samples_s = [] + for b in range(0, bracket_stops + 1): + # Get the exposure for this sensitivity and exposure time. + e = int(math.pow(2, b)*auto_e/float(s)) + req = its.objects.manual_capture_request(round(s), e) + cap = cam.do_capture(req, cam.CAP_RAW) + planes = its.image.convert_capture_to_planes(cap, props) - # Fit a line to the points, with a line equation: y = mx + b. - # This line is the relationship between mean and variance (i.e.) - # between signal level and noise, for this particular sensor. - # In the DNG noise model, the gradient (m) is "S", and the offset - # (b) is "O". - points.sort() - xs = [x for (x,y) in points] - ys = [y for (x,y) in points] - m,b = numpy.polyfit(xs, ys, 1) - lines.append((s,m,b)) - print s, "->", m, b + samples_e = [] + for (pidx, p) in enumerate(planes): + p = p.squeeze() - # TODO: Clean up these checks (which currently fail in some cases). - # Some sanity checks: - # * Noise levels should increase with brightness. - # * Extrapolating to a black image, the noise should be positive. - # Basically, the "b" value should correspond to the read noise, - # which is the noise level if the sensor was operating in zero - # light. - #assert(m > 0) - #assert(b >= 0) + # Crop the plane to be a multiple of the tile size. + p = p[0:p.shape[0] - p.shape[0]%tile_size, + 0:p.shape[1] - p.shape[1]%tile_size] - if iouter == 0: - pylab.plot(xs, ys, 'r', label="Measured") - pylab.plot([0,xs[-1]],[b,m*xs[-1]+b],'b', label="Fit") - else: - pylab.plot(xs, ys, 'r') - pylab.plot([0,xs[-1]],[b,m*xs[-1]+b],'b') + # convert_capture_to_planes normalizes the range + # to [0, 1], but without subtracting the black + # level. + black_level = black_levels[pidx] + p = p*white_level + p = (p - black_level)/(white_level - black_level) - pylab.xlabel("Mean") - pylab.ylabel("Variance") - pylab.legend() - matplotlib.pyplot.savefig("%s_plot_mean_vs_variance.png" % (NAME)) + # Use our high pass filter to filter this plane. + hp = scipy.signal.sepfir2d(p, f, f).astype('float32') - # Now fit a line across the (m,b) line parameters for each sensitivity. - # The gradient (m) params are fit to the "S" line, and the offset (b) - # params are fit to the "O" line, both as a function of sensitivity. - gains = [d[0] for d in lines] - Ss = [d[1] for d in lines] - Os = [d[2] for d in lines] - mS,bS = numpy.polyfit(gains, Ss, 1) - mO,bO = numpy.polyfit(gains, Os, 1) + means_tiled = \ + np.mean(tile(p, tile_size), axis=(0, 1)).flatten() + vars_tiled = \ + np.var(tile(hp, tile_size), axis=(0, 1)).flatten() - # Plot curve "O" as 10x, so it fits in the same scale as curve "S". - fig = matplotlib.pyplot.figure() - pylab.plot(gains, [10*o for o in Os], 'r', label="Measured") - pylab.plot([gains[0],gains[-1]], - [10*mO*gains[0]+10*bO, 10*mO*gains[-1]+10*bO],'r--',label="Fit") - pylab.plot(gains, Ss, 'b', label="Measured") - pylab.plot([gains[0],gains[-1]], [mS*gains[0]+bS,mS*gains[-1]+bS],'b--', - label="Fit") - pylab.xlabel("Sensitivity") - pylab.ylabel("Model parameter: S (blue), O x10 (red)") - pylab.legend() - matplotlib.pyplot.savefig("%s_plot_S_O.png" % (NAME)) + for (mean, var) in zip(means_tiled, vars_tiled): + # Don't include the tile if it has samples that might + # be clipped. + if mean + 2*math.sqrt(var) < max_signal_level: + samples_e.append([mean, var]) + means_e, vars_e = zip(*samples_e) + plt_s.plot(means_e, vars_e, colors[b%len(colors)] + ',') + + samples_s.extend(samples_e) + + [S, O, R, p, stderr] = scipy.stats.linregress(samples_s) + measured_models.append([round(s), S, O]) + print "Sensitivity %d: %e*y + %e (R=%f)" % (round(s), S, O, R) + + # Add the samples for this sensitivity to the global samples list. + samples.extend([(round(s), mean, var) for (mean, var) in samples_s]) + + # Add the linear fit to the plot for this sensitivity. + plt_s.plot([0, max_signal_level], [O, O + S*max_signal_level], 'r-', + label="Linear fit") + xmax = max([x for (x, _) in samples_s])*1.25 + plt_s.set_xlim(xmin=0, xmax=xmax) + plt_s.set_ylim(ymin=0, ymax=(O + S*xmax)*1.25) + fig.savefig("%s_samples_iso%04d.png" % (NAME, round(s))) + plots.append([round(s), fig]) + + # Move to the next sensitivity. + s = s*math.pow(2, 1.0/steps_per_stop) + + # Grab the sensitivities and line parameters from each sensitivity. + S_measured = [e[1] for e in measured_models] + O_measured = [e[2] for e in measured_models] + sens = np.asarray([e[0] for e in measured_models]) + sens_sq = np.square(sens) + + # Use a global linear optimization to fit the noise model. + gains = np.asarray([s[0] for s in samples]) + means = np.asarray([s[1] for s in samples]) + vars_ = np.asarray([s[2] for s in samples]) + + # Define digital gain as the gain above the max analog gain + # per the Camera2 spec. Also, define a corresponding C + # expression snippet to use in the generated model code. + digital_gains = np.maximum(gains/sens_max_analog, 1) + digital_gain_cdef = "(sens / %d.0) < 1.0 ? 1.0 : (sens / %d.0)" % \ + (sens_max_analog, sens_max_analog) + + # Find the noise model parameters via least squares fit. + ad = gains*means + bd = means + cd = gains*gains + dd = digital_gains*digital_gains + a = np.asarray([ad, bd, cd, dd]).T + b = vars_ + + # To avoid overfitting to high ISOs (high variances), divide the system + # by the gains. + a = a/(np.tile(gains, (a.shape[1], 1)).T) + b = b/gains + + [A, B, C, D], _, _, _ = np.linalg.lstsq(a, b) + + # Plot the noise model components with the values predicted by the + # noise model. + S_model = A*sens + B + O_model = \ + C*sens_sq + D*np.square(np.maximum(sens/sens_max_analog, 1)) + + (fig, (plt_S, plt_O)) = plt.subplots(2, 1) + plt_S.set_title("Noise model") + plt_S.set_ylabel("S") + plt_S.loglog(sens, S_measured, 'r+', basex=10, basey=10, + label="Measured") + plt_S.loglog(sens, S_model, 'bx', basex=10, basey=10, label="Model") + plt_S.legend(loc=2) + + plt_O.set_xlabel("ISO") + plt_O.set_ylabel("O") + plt_O.loglog(sens, O_measured, 'r+', basex=10, basey=10, + label="Measured") + plt_O.loglog(sens, O_model, 'bx', basex=10, basey=10, label="Model") + fig.savefig("%s.png" % (NAME)) + + for [s, fig] in plots: + plt_s = fig.gca() + + dg = max(s/sens_max_analog, 1) + S = A*s + B + O = C*s*s + D*dg*dg + plt_s.plot([0, max_signal_level], [O, O + S*max_signal_level], 'b-', + label="Model") + plt_s.legend(loc=2) + + plt.figure(fig.number) + + # Re-save the plot with the global model. + fig.savefig("%s_samples_iso%04d.png" % (NAME, round(s))) + + # Generate the noise model implementation. print """ /* Generated test code to dump a table of data for external validation * of the noise model parameters. @@ -176,11 +281,13 @@ double s = %e * sens + %e; return s < 0.0 ? 0.0 : s; } + double compute_noise_model_entry_O(int sens) { - double o = %e * sens + %e; + double digital_gain = %s; + double o = %e * sens * sens + %e * digital_gain * digital_gain; return o < 0.0 ? 0.0 : o; } - """%(sens_min,sens_max,mS,bS,mO,bO) + """ % (sens_min, sens_max, A, B, digital_gain_cdef, C, D) if __name__ == '__main__': main()
diff --git a/apps/CameraITS/tests/inprog/test_burst_sameness_auto.py b/apps/CameraITS/tests/inprog/test_burst_sameness_auto.py index 87500c7..6629df8 100644 --- a/apps/CameraITS/tests/inprog/test_burst_sameness_auto.py +++ b/apps/CameraITS/tests/inprog/test_burst_sameness_auto.py
@@ -39,7 +39,8 @@ # Capture at the smallest resolution. props = cam.get_camera_properties() - its.caps.skip_unless(its.caps.manual_sensor(props)) + its.caps.skip_unless(its.caps.manual_sensor(props) and + its.caps.awb_lock(props)) _, fmt = its.objects.get_fastest_manual_capture_settings(props) w,h = fmt["width"], fmt["height"]
diff --git a/apps/CameraITS/tests/inprog/test_burst_sameness_fullres_auto.py b/apps/CameraITS/tests/inprog/test_burst_sameness_fullres_auto.py index 932c051..fa37174 100644 --- a/apps/CameraITS/tests/inprog/test_burst_sameness_fullres_auto.py +++ b/apps/CameraITS/tests/inprog/test_burst_sameness_fullres_auto.py
@@ -15,6 +15,7 @@ import its.image import its.device import its.objects +import its.caps import os.path import numpy import pylab @@ -41,6 +42,8 @@ # Capture at full resolution. props = cam.get_camera_properties() + its.caps.skip_unless(its.caps.manual_sensor(props) and + its.caps.awb_lock(props)) w,h = its.objects.get_available_output_sizes("yuv", props)[0] # Converge 3A prior to capture.
diff --git a/apps/CameraITS/tests/inprog/test_faces.py b/apps/CameraITS/tests/inprog/test_faces.py deleted file mode 100644 index 228dac8..0000000 --- a/apps/CameraITS/tests/inprog/test_faces.py +++ /dev/null
@@ -1,41 +0,0 @@ -# Copyright 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. - -import its.image -import its.device -import its.objects -import os.path - -def main(): - """Test face detection. - """ - NAME = os.path.basename(__file__).split(".")[0] - - with its.device.ItsSession() as cam: - cam.do_3a() - req = its.objects.auto_capture_request() - req['android.statistics.faceDetectMode'] = 2 - caps = cam.do_capture([req]*5) - for i,cap in enumerate(caps): - md = cap['metadata'] - print "Frame %d face metadata:" % i - print " Ids:", md['android.statistics.faceIds'] - print " Landmarks:", md['android.statistics.faceLandmarks'] - print " Rectangles:", md['android.statistics.faceRectangles'] - print " Scores:", md['android.statistics.faceScores'] - print "" - -if __name__ == '__main__': - main() -
diff --git a/apps/CameraITS/tests/inprog/test_rawstats.py b/apps/CameraITS/tests/inprog/test_rawstats.py new file mode 100644 index 0000000..8083f0b --- /dev/null +++ b/apps/CameraITS/tests/inprog/test_rawstats.py
@@ -0,0 +1,48 @@ +# Copyright 2015 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. + +import its.image +import its.caps +import its.device +import its.objects +import its.target +import os.path +import math + +def main(): + """Test capturing some rawstats data. + """ + NAME = os.path.basename(__file__).split(".")[0] + + with its.device.ItsSession() as cam: + + cam.do_3a(do_af=False); + req = its.objects.auto_capture_request() + + for (gw,gh) in [(16,16)]:#,(4080,1)]: + cap = cam.do_capture(req, + {"format":"rawStats","gridWidth":gw,"gridHeight":gh}) + mean_image, var_image = its.image.unpack_rawstats_capture(cap) + + if gw > 1 and gh > 1: + h,w,_ = mean_image.shape + for ch in range(4): + m = mean_image[:,:,ch].reshape(h,w,1)/1023.0 + v = var_image[:,:,ch].reshape(h,w,1) + its.image.write_image(m, "%s_mean_ch%d.jpg" % (NAME,ch), True) + its.image.write_image(v, "%s_var_ch%d.jpg" % (NAME,ch), True) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tests/scene1/test_crop_region_raw.py b/apps/CameraITS/tests/scene1/test_crop_region_raw.py index 189e987..7973755 100644 --- a/apps/CameraITS/tests/scene1/test_crop_region_raw.py +++ b/apps/CameraITS/tests/scene1/test_crop_region_raw.py
@@ -64,7 +64,7 @@ # Use a manual request with a linear tonemap so that the YUV and RAW # should look the same (once converted by the its.image module). e, s = its.target.get_target_exposure_combos(cam)["minSensitivity"] - req = its.objects.manual_capture_request(s,e, True) + req = its.objects.manual_capture_request(s,e, True, props) cap1_raw, cap1_yuv = cam.do_capture(req, cam.CAP_RAW_YUV) # Capture with a crop region.
diff --git a/apps/CameraITS/tests/scene1/test_ev_compensation_advanced.py b/apps/CameraITS/tests/scene1/test_ev_compensation_advanced.py index 9b43a74..5fd8f73 100644 --- a/apps/CameraITS/tests/scene1/test_ev_compensation_advanced.py +++ b/apps/CameraITS/tests/scene1/test_ev_compensation_advanced.py
@@ -41,10 +41,12 @@ range_max = ev_compensation_range[1] ev_per_step = its.objects.rational_to_float( props['android.control.aeCompensationStep']) - steps_per_ev = int(1.0 / ev_per_step) - evs = range(range_min, range_max + 1, steps_per_ev) + steps_per_ev = int(round(1.0 / ev_per_step)) + ev_steps = range(range_min, range_max + 1, steps_per_ev) + imid = len(ev_steps) / 2 + ev_shifts = [pow(2, step * ev_per_step) for step in ev_steps] lumas = [] - for ev in evs: + for ev in ev_steps: # Re-converge 3A, and lock AE once converged. skip AF trigger as # dark/bright scene could make AF convergence fail and this test # doesn't care the image sharpness. @@ -65,19 +67,16 @@ tile = its.image.get_image_patch(y, 0.45,0.45,0.1,0.1) lumas.append(its.image.compute_image_means(tile)[0]) - luma_increase_per_step = pow(2, ev_per_step) print "ev_step_size_in_stops", ev_per_step - imid = len(lumas) / 2 - expected_lumas = [lumas[imid] / pow(luma_increase_per_step, i) - for i in range(imid , 0, -1)] + \ - [lumas[imid] * pow(luma_increase_per_step, i-imid) - for i in range(imid, len(evs))] + shift_mid = ev_shifts[imid] + luma_normal = lumas[imid] / shift_mid + expected_lumas = [luma_normal * ev_shift for ev_shift in ev_shifts] - pylab.plot(evs, lumas, 'r') - pylab.plot(evs, expected_lumas, 'b') + pylab.plot(ev_steps, lumas, 'r') + pylab.plot(ev_steps, expected_lumas, 'b') matplotlib.pyplot.savefig("%s_plot_means.png" % (NAME)) - luma_diffs = [expected_lumas[i] - lumas[i] for i in range(len(evs))] + luma_diffs = [expected_lumas[i] - lumas[i] for i in range(len(ev_steps))] max_diff = max(abs(i) for i in luma_diffs) avg_diff = abs(numpy.array(luma_diffs)).mean() print "Max delta between modeled and measured lumas:", max_diff
diff --git a/apps/CameraITS/tests/scene1/test_ev_compensation_basic.py b/apps/CameraITS/tests/scene1/test_ev_compensation_basic.py index d09f2fd..e3755eb 100644 --- a/apps/CameraITS/tests/scene1/test_ev_compensation_basic.py +++ b/apps/CameraITS/tests/scene1/test_ev_compensation_basic.py
@@ -29,7 +29,8 @@ with its.device.ItsSession() as cam: props = cam.get_camera_properties() - its.caps.skip_unless(its.caps.ev_compensation(props)) + its.caps.skip_unless(its.caps.ev_compensation(props) and + its.caps.ae_lock(props)) ev_per_step = its.objects.rational_to_float( props['android.control.aeCompensationStep'])
diff --git a/apps/CameraITS/tests/scene1/test_exposure.py b/apps/CameraITS/tests/scene1/test_exposure.py index d217bdb..89bc724 100644 --- a/apps/CameraITS/tests/scene1/test_exposure.py +++ b/apps/CameraITS/tests/scene1/test_exposure.py
@@ -35,12 +35,16 @@ THRESHOLD_MAX_OUTLIER_DIFF = 0.1 THRESHOLD_MIN_LEVEL = 0.1 THRESHOLD_MAX_LEVEL = 0.9 - THRESHOLD_MAX_LEVEL_DIFF = 0.025 + THRESHOLD_MAX_LEVEL_DIFF = 0.03 + THRESHOLD_MAX_LEVEL_DIFF_WIDE_RANGE = 0.05 + THRESHOLD_ROUND_DOWN_GAIN = 0.1 + THRESHOLD_ROUND_DOWN_EXP = 0.05 mults = [] r_means = [] g_means = [] b_means = [] + threshold_max_level_diff = THRESHOLD_MAX_LEVEL_DIFF with its.device.ItsSession() as cam: props = cam.get_camera_properties() @@ -48,27 +52,44 @@ its.caps.per_frame_control(props)) e,s = its.target.get_target_exposure_combos(cam)["minSensitivity"] + s_e_product = s*e expt_range = props['android.sensor.info.exposureTimeRange'] sens_range = props['android.sensor.info.sensitivityRange'] - m = 1 + m = 1.0 while s*m < sens_range[1] and e/m > expt_range[0]: mults.append(m) - req = its.objects.manual_capture_request(s*m, e/m) + s_test = round(s*m) + e_test = s_e_product / s_test + print "Testsing s:", s_test, "e:", e_test + req = its.objects.manual_capture_request(s_test, e_test) cap = cam.do_capture(req) + s_res = cap["metadata"]["android.sensor.sensitivity"] + e_res = cap["metadata"]["android.sensor.exposureTime"] + assert(0 <= s_test - s_res < s_test * THRESHOLD_ROUND_DOWN_GAIN) + assert(0 <= e_test - e_res < e_test * THRESHOLD_ROUND_DOWN_EXP) + s_e_product_res = s_res * e_res + request_result_ratio = s_e_product / s_e_product_res + print "Capture result s:", s_test, "e:", e_test img = its.image.convert_capture_to_rgb_image(cap) - its.image.write_image(img, "%s_mult=%02d.jpg" % (NAME, m)) + its.image.write_image(img, "%s_mult=%3.2f.jpg" % (NAME, m)) tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1) rgb_means = its.image.compute_image_means(tile) - r_means.append(rgb_means[0]) - g_means.append(rgb_means[1]) - b_means.append(rgb_means[2]) - m = m + 4 + # Adjust for the difference between request and result + r_means.append(rgb_means[0] * request_result_ratio) + g_means.append(rgb_means[1] * request_result_ratio) + b_means.append(rgb_means[2] * request_result_ratio) + # Test 3 steps per 2x gain + m = m * pow(2, 1.0 / 3) + + # Allow more threshold for devices with wider exposure range + if m >= 64.0: + threshold_max_level_diff = THRESHOLD_MAX_LEVEL_DIFF_WIDE_RANGE # Draw a plot. - pylab.plot(mults, r_means, 'r') - pylab.plot(mults, g_means, 'g') - pylab.plot(mults, b_means, 'b') + pylab.plot(mults, r_means, 'r.-') + pylab.plot(mults, g_means, 'g.-') + pylab.plot(mults, b_means, 'b.-') pylab.ylim([0,1]) matplotlib.pyplot.savefig("%s_plot_means.png" % (NAME)) @@ -83,7 +104,7 @@ max_diff = max_val - min_val print "Channel %d line fit (y = mx+b): m = %f, b = %f" % (chan, m, b) print "Channel max %f min %f diff %f" % (max_val, min_val, max_diff) - assert(max_diff < THRESHOLD_MAX_LEVEL_DIFF) + assert(max_diff < threshold_max_level_diff) assert(b > THRESHOLD_MIN_LEVEL and b < THRESHOLD_MAX_LEVEL) for v in values: assert(v > THRESHOLD_MIN_LEVEL and v < THRESHOLD_MAX_LEVEL)
diff --git a/apps/CameraITS/tests/scene1/test_jpeg.py b/apps/CameraITS/tests/scene1/test_jpeg.py index 25c2038..7bc038d 100644 --- a/apps/CameraITS/tests/scene1/test_jpeg.py +++ b/apps/CameraITS/tests/scene1/test_jpeg.py
@@ -33,7 +33,7 @@ its.caps.per_frame_control(props)) e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) # YUV size = its.objects.get_available_output_sizes("yuv", props)[0]
diff --git a/apps/CameraITS/tests/scene1/test_latching.py b/apps/CameraITS/tests/scene1/test_latching.py index 3bc4356..176f01b 100644 --- a/apps/CameraITS/tests/scene1/test_latching.py +++ b/apps/CameraITS/tests/scene1/test_latching.py
@@ -45,20 +45,20 @@ b_means = [] reqs = [ - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s*2,e, True), - its.objects.manual_capture_request(s*2,e, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s, e*2, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s*2,e, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s, e*2, True), - its.objects.manual_capture_request(s, e, True), - its.objects.manual_capture_request(s, e*2, True), - its.objects.manual_capture_request(s, e*2, True), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s*2,e, True, props), + its.objects.manual_capture_request(s*2,e, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s, e*2, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s*2,e, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s, e*2, True, props), + its.objects.manual_capture_request(s, e, True, props), + its.objects.manual_capture_request(s, e*2, True, props), + its.objects.manual_capture_request(s, e*2, True, props), ] caps = cam.do_capture(reqs, fmt)
diff --git a/apps/CameraITS/tests/scene1/test_locked_burst.py b/apps/CameraITS/tests/scene1/test_locked_burst.py index a33a9f8..6552c73 100644 --- a/apps/CameraITS/tests/scene1/test_locked_burst.py +++ b/apps/CameraITS/tests/scene1/test_locked_burst.py
@@ -38,6 +38,8 @@ with its.device.ItsSession() as cam: props = cam.get_camera_properties() + its.caps.skip_unless(its.caps.ae_lock(props) and + its.caps.awb_lock(props)) # Converge 3A prior to capture. cam.do_3a(do_af=True, lock_ae=True, lock_awb=True)
diff --git a/apps/CameraITS/tests/scene1/test_param_color_correction.py b/apps/CameraITS/tests/scene1/test_param_color_correction.py index b7fdc7b..09b3707 100644 --- a/apps/CameraITS/tests/scene1/test_param_color_correction.py +++ b/apps/CameraITS/tests/scene1/test_param_color_correction.py
@@ -42,7 +42,7 @@ # Baseline request e, s = its.target.get_target_exposure_combos(cam)["midSensitivity"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) req["android.colorCorrection.mode"] = 0 # Transforms:
diff --git a/apps/CameraITS/tests/scene1/test_param_exposure_time.py b/apps/CameraITS/tests/scene1/test_param_exposure_time.py index e6078d9..0c0aab1 100644 --- a/apps/CameraITS/tests/scene1/test_param_exposure_time.py +++ b/apps/CameraITS/tests/scene1/test_param_exposure_time.py
@@ -39,7 +39,7 @@ e,s = its.target.get_target_exposure_combos(cam)["midExposureTime"] for i,e_mult in enumerate([0.8, 0.9, 1.0, 1.1, 1.2]): - req = its.objects.manual_capture_request(s, e * e_mult, True) + req = its.objects.manual_capture_request(s, e * e_mult, True, props) cap = cam.do_capture(req) img = its.image.convert_capture_to_rgb_image(cap) its.image.write_image(
diff --git a/apps/CameraITS/tests/scene1/test_param_flash_mode.py b/apps/CameraITS/tests/scene1/test_param_flash_mode.py index aae56aa..38f864f 100644 --- a/apps/CameraITS/tests/scene1/test_param_flash_mode.py +++ b/apps/CameraITS/tests/scene1/test_param_flash_mode.py
@@ -39,7 +39,7 @@ # linear tonemap. e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] e /= 4 - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) for f in [0,1,2]: req["android.flash.mode"] = f
diff --git a/apps/CameraITS/tests/scene1/test_param_noise_reduction.py b/apps/CameraITS/tests/scene1/test_param_noise_reduction.py index 219927d..1072684 100644 --- a/apps/CameraITS/tests/scene1/test_param_noise_reduction.py +++ b/apps/CameraITS/tests/scene1/test_param_noise_reduction.py
@@ -17,10 +17,11 @@ import its.device import its.objects import its.target -import pylab -import os.path import matplotlib import matplotlib.pyplot +import numpy +import os.path +import pylab def main(): """Test that the android.noiseReduction.mode param is applied when set. @@ -34,18 +35,21 @@ """ NAME = os.path.basename(__file__).split(".")[0] - # List of variances for R,G,B. - variances = [[],[],[]] + NUM_SAMPLES_PER_MODE = 4 + SNR_TOLERANCE = 3 # unit in db + # List of SNRs for R,G,B. + snrs = [[], [], []] - # Reference (baseline) variance for each of R,G,B. - ref_variance = [] + # Reference (baseline) SNR for each of R,G,B. + ref_snr = [] nr_modes_reported = [] with its.device.ItsSession() as cam: props = cam.get_camera_properties() its.caps.skip_unless(its.caps.compute_target_exposure(props) and - its.caps.per_frame_control(props)) + its.caps.per_frame_control(props) and + its.caps.noise_reduction_mode(props, 0)) # NR mode 0 with low gain e, s = its.target.get_target_exposure_combos(cam)["minSensitivity"] @@ -57,41 +61,84 @@ rgb_image, "%s_low_gain.jpg" % (NAME)) rgb_tile = its.image.get_image_patch(rgb_image, 0.45, 0.45, 0.1, 0.1) - ref_variance = its.image.compute_image_variances(rgb_tile) - print "Ref variances:", ref_variance + ref_snr = its.image.compute_image_snrs(rgb_tile) + print "Ref SNRs:", ref_snr e, s = its.target.get_target_exposure_combos(cam)["maxSensitivity"] - for i in range(3): - # NR modes 0, 1, 2 with high gain - req = its.objects.manual_capture_request(s, e) - req["android.noiseReduction.mode"] = i - cap = cam.do_capture(req) - rgb_image = its.image.convert_capture_to_rgb_image(cap) - nr_modes_reported.append( - cap["metadata"]["android.noiseReduction.mode"]) - its.image.write_image( - rgb_image, - "%s_high_gain_nr=%d.jpg" % (NAME, i)) - rgb_tile = its.image.get_image_patch( - rgb_image, 0.45, 0.45, 0.1, 0.1) - rgb_vars = its.image.compute_image_variances(rgb_tile) + # NR modes 0, 1, 2, 3, 4 with high gain + for mode in range(5): + # Skip unavailable modes + if not its.caps.noise_reduction_mode(props, mode): + nr_modes_reported.append(mode) + for channel in range(3): + snrs[channel].append(0) + continue; + + rgb_snr_list = [] + # Capture several images to account for per frame noise variations + for n in range(NUM_SAMPLES_PER_MODE): + req = its.objects.manual_capture_request(s, e) + req["android.noiseReduction.mode"] = mode + cap = cam.do_capture(req) + rgb_image = its.image.convert_capture_to_rgb_image(cap) + if n == 0: + nr_modes_reported.append( + cap["metadata"]["android.noiseReduction.mode"]) + its.image.write_image( + rgb_image, + "%s_high_gain_nr=%d.jpg" % (NAME, mode)) + rgb_tile = its.image.get_image_patch( + rgb_image, 0.45, 0.45, 0.1, 0.1) + rgb_snrs = its.image.compute_image_snrs(rgb_tile) + rgb_snr_list.append(rgb_snrs) + + r_snrs = [rgb[0] for rgb in rgb_snr_list] + g_snrs = [rgb[1] for rgb in rgb_snr_list] + b_snrs = [rgb[2] for rgb in rgb_snr_list] + rgb_snrs = [numpy.mean(r_snrs), numpy.mean(g_snrs), numpy.mean(b_snrs)] + print "NR mode", mode, "SNRs:" + print " R SNR:", rgb_snrs[0],\ + "Min:", min(r_snrs), "Max:", max(r_snrs) + print " G SNR:", rgb_snrs[1],\ + "Min:", min(g_snrs), "Max:", max(g_snrs) + print " B SNR:", rgb_snrs[2],\ + "Min:", min(b_snrs), "Max:", max(b_snrs) + for chan in range(3): - variance = rgb_vars[chan] - variances[chan].append(variance / ref_variance[chan]) - print "Variances with NR mode [0,1,2]:", variances + snrs[chan].append(rgb_snrs[chan]) # Draw a plot. for j in range(3): - pylab.plot(range(3), variances[j], "rgb"[j]) - matplotlib.pyplot.savefig("%s_plot_variances.png" % (NAME)) + pylab.plot(range(5), snrs[j], "rgb"[j]) + matplotlib.pyplot.savefig("%s_plot_SNRs.png" % (NAME)) - assert(nr_modes_reported == [0,1,2]) + assert(nr_modes_reported == [0,1,2,3,4]) - # Check that the variance of the NR=0 image is higher than for the - # NR=1 and NR=2 images. for j in range(3): - for i in range(1,3): - assert(variances[j][i] < variances[j][0]) + # Larger SNR is better + # Verify OFF(0) is not better than FAST(1) + assert(snrs[j][0] < + snrs[j][1] + SNR_TOLERANCE) + # Verify FAST(1) is not better than HQ(2) + assert(snrs[j][1] < + snrs[j][2] + SNR_TOLERANCE) + # Verify HQ(2) is better than OFF(0) + assert(snrs[j][0] < snrs[j][2]) + if its.caps.noise_reduction_mode(props, 3): + # Verify OFF(0) is not better than MINIMAL(3) + assert(snrs[j][0] < + snrs[j][3] + SNR_TOLERANCE) + # Verify MINIMAL(3) is not better than HQ(2) + assert(snrs[j][3] < + snrs[j][2] + SNR_TOLERANCE) + if its.caps.noise_reduction_mode(props, 4): + # Verify ZSL(4) is close to MINIMAL(3) + assert(numpy.isclose(snrs[j][4], snrs[j][3], + atol=SNR_TOLERANCE)) + elif its.caps.noise_reduction_mode(props, 4): + # Verify ZSL(4) is close to OFF(0) + assert(numpy.isclose(snrs[j][4], snrs[j][0], + atol=SNR_TOLERANCE)) if __name__ == '__main__': main()
diff --git a/apps/CameraITS/tests/scene1/test_param_shading_mode.py b/apps/CameraITS/tests/scene1/test_param_shading_mode.py new file mode 100644 index 0000000..8538675 --- /dev/null +++ b/apps/CameraITS/tests/scene1/test_param_shading_mode.py
@@ -0,0 +1,115 @@ +# Copyright 2015 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. + +import its.caps +import its.device +import its.objects +import matplotlib +import numpy +import os +import os.path +import pylab + +def main(): + """Test that the android.shading.mode param is applied. + + Switching shading modes and checks that the lens shading maps are + modified as expected. + """ + NAME = os.path.basename(__file__).split(".")[0] + + NUM_SHADING_MODE_SWITCH_LOOPS = 3 + THRESHOLD_DIFF_RATIO = 0.15 + + with its.device.ItsSession() as cam: + props = cam.get_camera_properties() + + its.caps.skip_unless(its.caps.per_frame_control(props) and + its.caps.lsc_map(props) and + its.caps.lsc_off(props)) + + assert(props.has_key("android.lens.info.shadingMapSize") and + props["android.lens.info.shadingMapSize"] != None) + + # lsc_off devices should always support OFF(0), FAST(1), and HQ(2) + assert(props.has_key("android.shading.availableModes") and + set(props["android.shading.availableModes"]) == set([0, 1, 2])) + + num_map_gains = props["android.lens.info.shadingMapSize"]["width"] * \ + props["android.lens.info.shadingMapSize"]["height"] * 4 + + # Test 1: Switching shading modes several times and verify: + # 1. Lens shading maps with mode OFF are all 1.0 + # 2. Lens shading maps with mode FAST are similar after switching + # shading modes. + # 3. Lens shading maps with mode HIGH_QUALITY are similar after + # switching shading modes. + cam.do_3a(); + + # Get the reference lens shading maps for OFF, FAST, and HIGH_QUALITY + # in different sessions. + # reference_maps[mode] + reference_maps = [[] for mode in range(3)] + reference_maps[0] = [1.0] * num_map_gains + for mode in range(1, 3): + req = its.objects.auto_capture_request(); + req["android.statistics.lensShadingMapMode"] = 1 + req["android.shading.mode"] = mode + reference_maps[mode] = cam.do_capture(req)["metadata"] \ + ["android.statistics.lensShadingMap"] + + # Get the lens shading maps while switching modes in one session. + reqs = [] + for i in range(NUM_SHADING_MODE_SWITCH_LOOPS): + for mode in range(3): + req = its.objects.auto_capture_request(); + req["android.statistics.lensShadingMapMode"] = 1 + req["android.shading.mode"] = mode + reqs.append(req); + + caps = cam.do_capture(reqs) + + # shading_maps[mode][loop] + shading_maps = [[[] for loop in range(NUM_SHADING_MODE_SWITCH_LOOPS)] + for mode in range(3)] + + # Get the shading maps out of capture results + for i in range(len(caps)): + shading_maps[i % 3][i / 3] = \ + caps[i]["metadata"]["android.statistics.lensShadingMap"] + + # Draw the maps + for mode in range(3): + for i in range(NUM_SHADING_MODE_SWITCH_LOOPS): + pylab.clf() + pylab.plot(range(num_map_gains), shading_maps[mode][i], 'r') + pylab.plot(range(num_map_gains), reference_maps[mode], 'g') + pylab.xlim([0, num_map_gains]) + pylab.ylim([0.9, 4.0]) + matplotlib.pyplot.savefig("%s_ls_maps_mode_%d_loop_%d.png" % + (NAME, mode, i)) + + print "Verifying lens shading maps with mode OFF are all 1.0" + for i in range(NUM_SHADING_MODE_SWITCH_LOOPS): + assert(numpy.allclose(shading_maps[0][i], reference_maps[0])) + + for mode in range(1, 3): + print "Verifying lens shading maps with mode", mode, "are similar" + for i in range(NUM_SHADING_MODE_SWITCH_LOOPS): + assert(numpy.allclose(shading_maps[mode][i], + reference_maps[mode], + THRESHOLD_DIFF_RATIO)) + +if __name__ == '__main__': + main()
diff --git a/apps/CameraITS/tests/scene1/test_reprocess_noise_reduction.py b/apps/CameraITS/tests/scene1/test_reprocess_noise_reduction.py new file mode 100644 index 0000000..f0a6fbe --- /dev/null +++ b/apps/CameraITS/tests/scene1/test_reprocess_noise_reduction.py
@@ -0,0 +1,168 @@ +# Copyright 2015 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. + +import its.image +import its.caps +import its.device +import its.objects +import its.target +import math +import matplotlib +import matplotlib.pyplot +import numpy +import os.path +import pylab + +def main(): + """Test that the android.noiseReduction.mode param is applied when set for + reprocessing requests. + + Capture reprocessed images with the camera dimly lit. Uses a high analog + gain to ensure the captured image is noisy. + + Captures three reprocessed images, for NR off, "fast", and "high quality". + Also captures a reprocessed image with low gain and NR off, and uses the + variance of this as the baseline. + """ + + NAME = os.path.basename(__file__).split(".")[0] + + NUM_SAMPLES_PER_MODE = 4 + SNR_TOLERANCE = 3 # unit in db + + with its.device.ItsSession() as cam: + props = cam.get_camera_properties() + + its.caps.skip_unless(its.caps.compute_target_exposure(props) and + its.caps.per_frame_control(props) and + its.caps.noise_reduction_mode(props, 0) and + (its.caps.yuv_reprocess(props) or + its.caps.private_reprocess(props))) + + # If reprocessing is supported, ZSL NR mode must be avaiable. + assert(its.caps.noise_reduction_mode(props, 4)) + + reprocess_formats = [] + if (its.caps.yuv_reprocess(props)): + reprocess_formats.append("yuv") + if (its.caps.private_reprocess(props)): + reprocess_formats.append("private") + + for reprocess_format in reprocess_formats: + # List of variances for R, G, B. + snrs = [[], [], []] + nr_modes_reported = [] + + # NR mode 0 with low gain + e, s = its.target.get_target_exposure_combos(cam)["minSensitivity"] + req = its.objects.manual_capture_request(s, e) + req["android.noiseReduction.mode"] = 0 + + # Test reprocess_format->JPEG reprocessing + # TODO: Switch to reprocess_format->YUV when YUV reprocessing is + # supported. + size = its.objects.get_available_output_sizes("jpg", props)[0] + out_surface = {"width":size[0], "height":size[1], "format":"jpg"} + cap = cam.do_capture(req, out_surface, reprocess_format) + img = its.image.decompress_jpeg_to_rgb_image(cap["data"]) + its.image.write_image(img, "%s_low_gain_fmt=jpg.jpg" % (NAME)) + tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1) + ref_snr = its.image.compute_image_snrs(tile) + print "Ref SNRs:", ref_snr + + e, s = its.target.get_target_exposure_combos(cam)["maxSensitivity"] + for nr_mode in range(5): + # Skip unavailable modes + if not its.caps.noise_reduction_mode(props, nr_mode): + nr_modes_reported.append(nr_mode) + for channel in range(3): + snrs[channel].append(0) + continue + + rgb_snr_list = [] + # Capture several images to account for per frame noise + # variations + for n in range(NUM_SAMPLES_PER_MODE): + req = its.objects.manual_capture_request(s, e) + req["android.noiseReduction.mode"] = nr_mode + cap = cam.do_capture(req, out_surface, reprocess_format) + + img = its.image.decompress_jpeg_to_rgb_image(cap["data"]) + if n == 0: + its.image.write_image( + img, + "%s_high_gain_nr=%d_fmt=jpg.jpg" + %(NAME, nr_mode)) + nr_modes_reported.append( + cap["metadata"]["android.noiseReduction.mode"]) + + tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1) + # Get the variances for R, G, and B channels + rgb_snrs = its.image.compute_image_snrs(tile) + rgb_snr_list.append(rgb_snrs) + + r_snrs = [rgb[0] for rgb in rgb_snr_list] + g_snrs = [rgb[1] for rgb in rgb_snr_list] + b_snrs = [rgb[2] for rgb in rgb_snr_list] + rgb_snrs = [numpy.mean(r_snrs), + numpy.mean(g_snrs), + numpy.mean(b_snrs)] + print "NR mode", nr_mode, "SNRs:" + print " R SNR:", rgb_snrs[0],\ + "Min:", min(r_snrs), "Max:", max(r_snrs) + print " G SNR:", rgb_snrs[1],\ + "Min:", min(g_snrs), "Max:", max(g_snrs) + print " B SNR:", rgb_snrs[2],\ + "Min:", min(b_snrs), "Max:", max(b_snrs) + + for chan in range(3): + snrs[chan].append(rgb_snrs[chan]) + + # Draw a plot. + for channel in range(3): + pylab.plot(range(5), snrs[channel], "rgb"[channel]) + + matplotlib.pyplot.savefig("%s_plot_%s_SNRs.png" % + (NAME, reprocess_format)) + + assert(nr_modes_reported == [0,1,2,3,4]) + + for j in range(3): + # Larger is better + # Verify OFF(0) is not better than FAST(1) + assert(snrs[j][0] < + snrs[j][1] + SNR_TOLERANCE) + # Verify FAST(1) is not better than HQ(2) + assert(snrs[j][1] < + snrs[j][2] + SNR_TOLERANCE) + # Verify HQ(2) is better than OFF(0) + assert(snrs[j][0] < snrs[j][2]) + if its.caps.noise_reduction_mode(props, 3): + # Verify OFF(0) is not better than MINIMAL(3) + assert(snrs[j][0] < + snrs[j][3] + SNR_TOLERANCE) + # Verify MINIMAL(3) is not better than HQ(2) + assert(snrs[j][3] < + snrs[j][2] + SNR_TOLERANCE) + # Verify ZSL(4) is close to MINIMAL(3) + assert(numpy.isclose(snrs[j][4], snrs[j][3], + atol=SNR_TOLERANCE)) + else: + # Verify ZSL(4) is close to OFF(0) + assert(numpy.isclose(snrs[j][4], snrs[j][0], + atol=SNR_TOLERANCE)) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tests/scene1/test_tonemap_sequence.py b/apps/CameraITS/tests/scene1/test_tonemap_sequence.py index 18ca506..7c87ca2 100644 --- a/apps/CameraITS/tests/scene1/test_tonemap_sequence.py +++ b/apps/CameraITS/tests/scene1/test_tonemap_sequence.py
@@ -40,7 +40,7 @@ means = [] # Capture 3 manual shots with a linear tonemap. - req = its.objects.manual_capture_request(sens, exp_time, True) + req = its.objects.manual_capture_request(sens, exp_time, True, props) for i in [0,1,2]: cap = cam.do_capture(req) img = its.image.convert_capture_to_rgb_image(cap)
diff --git a/apps/CameraITS/tests/scene1/test_yuv_jpeg_all.py b/apps/CameraITS/tests/scene1/test_yuv_jpeg_all.py index 1b278ef..0c428fc 100644 --- a/apps/CameraITS/tests/scene1/test_yuv_jpeg_all.py +++ b/apps/CameraITS/tests/scene1/test_yuv_jpeg_all.py
@@ -35,7 +35,7 @@ # Use a manual request with a linear tonemap so that the YUV and JPEG # should look the same (once converted by the its.image module). e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) rgbs = []
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_jpeg.py b/apps/CameraITS/tests/scene1/test_yuv_plus_jpeg.py index e58cb1d..78378eb 100644 --- a/apps/CameraITS/tests/scene1/test_yuv_plus_jpeg.py +++ b/apps/CameraITS/tests/scene1/test_yuv_plus_jpeg.py
@@ -41,7 +41,7 @@ # Use a manual request with a linear tonemap so that the YUV and JPEG # should look the same (once converted by the its.image module). e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) cap_yuv, cap_jpeg = cam.do_capture(req, [fmt_yuv, fmt_jpeg])
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py b/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py index 2e7804b..bfa6a28 100644 --- a/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py +++ b/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py
@@ -36,7 +36,7 @@ # Use a manual request with a linear tonemap so that the YUV and RAW # should look the same (once converted by the its.image module). e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) max_raw_size = \ its.objects.get_available_output_sizes("raw", props)[0]
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py b/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py index d02f84e..322af10 100644 --- a/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py +++ b/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py
@@ -36,7 +36,7 @@ # Use a manual request with a linear tonemap so that the YUV and RAW # should look the same (once converted by the its.image module). e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] - req = its.objects.manual_capture_request(s, e, True) + req = its.objects.manual_capture_request(s, e, True, props) max_raw10_size = \ its.objects.get_available_output_sizes("raw10", props)[0]
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_raw12.py b/apps/CameraITS/tests/scene1/test_yuv_plus_raw12.py new file mode 100644 index 0000000..b3cca0b --- /dev/null +++ b/apps/CameraITS/tests/scene1/test_yuv_plus_raw12.py
@@ -0,0 +1,68 @@ +# Copyright 2015 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. + +import its.image +import its.caps +import its.device +import its.objects +import its.target +import os.path +import math + +def main(): + """Test capturing a single frame as both RAW12 and YUV outputs. + """ + NAME = os.path.basename(__file__).split(".")[0] + + THRESHOLD_MAX_RMS_DIFF = 0.035 + + with its.device.ItsSession() as cam: + props = cam.get_camera_properties() + its.caps.skip_unless(its.caps.compute_target_exposure(props) and + its.caps.raw12(props) and + its.caps.per_frame_control(props)) + + # Use a manual request with a linear tonemap so that the YUV and RAW + # should look the same (once converted by the its.image module). + e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"] + req = its.objects.manual_capture_request(s, e, True, props) + + max_raw12_size = \ + its.objects.get_available_output_sizes("raw12", props)[0] + w,h = its.objects.get_available_output_sizes( + "yuv", props, (1920, 1080), max_raw12_size)[0] + cap_raw, cap_yuv = cam.do_capture(req, + [{"format":"raw12"}, + {"format":"yuv", "width":w, "height":h}]) + + img = its.image.convert_capture_to_rgb_image(cap_yuv) + its.image.write_image(img, "%s_yuv.jpg" % (NAME), True) + tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1) + rgb0 = its.image.compute_image_means(tile) + + # Raw shots are 1/2 x 1/2 smaller after conversion to RGB, so scale the + # tile appropriately. + img = its.image.convert_capture_to_rgb_image(cap_raw, props=props) + its.image.write_image(img, "%s_raw.jpg" % (NAME), True) + tile = its.image.get_image_patch(img, 0.475, 0.475, 0.05, 0.05) + rgb1 = its.image.compute_image_means(tile) + + rms_diff = math.sqrt( + sum([pow(rgb0[i] - rgb1[i], 2.0) for i in range(3)]) / 3.0) + print "RMS difference:", rms_diff + assert(rms_diff < THRESHOLD_MAX_RMS_DIFF) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tests/scene2/SampleTarget.jpg b/apps/CameraITS/tests/scene2/SampleTarget.jpg new file mode 100644 index 0000000..c054f7e --- /dev/null +++ b/apps/CameraITS/tests/scene2/SampleTarget.jpg Binary files differ
diff --git a/apps/CameraITS/tests/scene2/test_faces.py b/apps/CameraITS/tests/scene2/test_faces.py new file mode 100644 index 0000000..cce74e7 --- /dev/null +++ b/apps/CameraITS/tests/scene2/test_faces.py
@@ -0,0 +1,102 @@ +# Copyright 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. + +import its.image +import its.device +import its.objects +import os.path + +def main(): + """Test face detection. + """ + NAME = os.path.basename(__file__).split(".")[0] + NUM_TEST_FRAMES = 20 + FD_MODE_OFF = 0 + FD_MODE_SIMPLE = 1 + FD_MODE_FULL = 2 + + with its.device.ItsSession() as cam: + props = cam.get_camera_properties() + fd_modes = props['android.statistics.info.availableFaceDetectModes'] + a = props['android.sensor.info.activeArraySize'] + aw, ah = a['right'] - a['left'], a['bottom'] - a['top'] + cam.do_3a() + for fd_mode in fd_modes: + assert(FD_MODE_OFF <= fd_mode <= FD_MODE_FULL) + req = its.objects.auto_capture_request() + req['android.statistics.faceDetectMode'] = fd_mode + caps = cam.do_capture([req]*NUM_TEST_FRAMES) + for i,cap in enumerate(caps): + md = cap['metadata'] + assert(md['android.statistics.faceDetectMode'] == fd_mode) + faces = md['android.statistics.faces'] + + # 0 faces should be returned for OFF mode + if fd_mode == FD_MODE_OFF: + assert(len(faces) == 0) + continue + # Face detection could take several frames to warm up, + # but it should detect at least one face in last frame + if i == NUM_TEST_FRAMES - 1: + if len(faces) == 0: + print "Error: no face detected in mode", fd_mode + assert(0) + if len(faces) == 0: + continue + + print "Frame %d face metadata:" % i + print " Faces:", faces + print "" + + face_scores = [face['score'] for face in faces] + face_rectangles = [face['bounds'] for face in faces] + for score in face_scores: + assert(score >= 1 and score <= 100) + # Face bounds should be within active array + for rect in face_rectangles: + assert(rect['top'] < rect['bottom']) + assert(rect['left'] < rect['right']) + assert(0 <= rect['top'] <= ah) + assert(0 <= rect['bottom'] <= ah) + assert(0 <= rect['left'] <= aw) + assert(0 <= rect['right'] <= aw) + + # Face landmarks are reported if and only if fd_mode is FULL + # Face ID should be -1 for SIMPLE and unique for FULL + if fd_mode == FD_MODE_SIMPLE: + for face in faces: + assert('leftEye' not in face) + assert('rightEye' not in face) + assert('mouth' not in face) + assert(face['id'] == -1) + elif fd_mode == FD_MODE_FULL: + face_ids = [face['id'] for face in faces] + assert(len(face_ids) == len(set(face_ids))) + # Face landmarks should be within face bounds + for face in faces: + left_eye = face['leftEye'] + right_eye = face['rightEye'] + mouth = face['mouth'] + l, r = face['bounds']['left'], face['bounds']['right'] + t, b = face['bounds']['top'], face['bounds']['bottom'] + assert(l <= left_eye['x'] <= r) + assert(t <= left_eye['y'] <= b) + assert(l <= right_eye['x'] <= r) + assert(t <= right_eye['y'] <= b) + assert(l <= mouth['x'] <= r) + assert(t <= mouth['y'] <= b) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tests/scene3/test_reprocess_edge_enhancement.py b/apps/CameraITS/tests/scene3/test_reprocess_edge_enhancement.py new file mode 100644 index 0000000..e96a9ee --- /dev/null +++ b/apps/CameraITS/tests/scene3/test_reprocess_edge_enhancement.py
@@ -0,0 +1,208 @@ +# Copyright 2015 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. + +import its.image +import its.caps +import its.device +import its.objects +import its.target +import math +import matplotlib +import matplotlib.pyplot +import numpy +import os.path +import pylab + + +def test_edge_mode(cam, edge_mode, sensitivity, exp, fd, out_surface, + reprocess_format=None): + """Return sharpness of the output image and the capture result metadata + for a capture request with the given edge mode, sensitivity, exposure + time, focus distance, output surface parameter, and reprocess format + (None for a regular request.) + + Args: + cam: An open device session. + edge_mode: Edge mode for the request as defined in android.edge.mode + sensitivity: Sensitivity for the request as defined in + android.sensor.sensitivity + exp: Exposure time for the request as defined in + android.sensor.exposureTime. + fd: Focus distance for the request as defined in + android.lens.focusDistance + output_surface: Specifications of the output image format and size. + reprocess_format: (Optional) The reprocessing format. If not None, + reprocessing will be enabled. + + Returns: + Object containing reported edge mode and the sharpness of the output + image, keyed by the following strings: + "edge_mode" + "sharpness" + """ + + NAME = os.path.basename(__file__).split(".")[0] + NUM_SAMPLES = 4 + + req = its.objects.manual_capture_request(sensitivity, exp) + req["android.lens.focusDistance"] = fd + req["android.edge.mode"] = edge_mode + if (reprocess_format != None): + req["android.reprocess.effectiveExposureFactor"] = 1.0 + + sharpness_list = [] + for n in range(NUM_SAMPLES): + cap = cam.do_capture(req, out_surface, reprocess_format) + img = its.image.decompress_jpeg_to_rgb_image(cap["data"]) + if n == 0: + its.image.write_image(img, "%s_reprocess_fmt_%s_edge=%d.jpg" % + (NAME, reprocess_format, edge_mode)) + res_edge_mode = cap["metadata"]["android.edge.mode"] + tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1) + sharpness_list.append(its.image.compute_image_sharpness(tile)) + + ret = {} + ret["edge_mode"] = res_edge_mode + ret["sharpness"] = numpy.mean(sharpness_list) + + return ret + +def main(): + """Test that the android.edge.mode param is applied when set for + reprocessing requests. + + Capture non-reprocess images for each edge mode and calculate their + sharpness as a baseline. + + Capture reprocessed images for each supported reprocess format and edge_mode + mode. Calculate the sharpness of reprocessed images and compare them against + the sharpess of non-reprocess images. + """ + + THRESHOLD_RELATIVE_SHARPNESS_DIFF = 0.1 + + with its.device.ItsSession() as cam: + props = cam.get_camera_properties() + + its.caps.skip_unless(its.caps.read_3a(props) and + its.caps.per_frame_control(props) and + its.caps.edge_mode(props, 0) and + (its.caps.yuv_reprocess(props) or + its.caps.private_reprocess(props))) + + # If reprocessing is supported, ZSL EE mode must be avaiable. + assert(its.caps.edge_mode(props, 3)) + + reprocess_formats = [] + if (its.caps.yuv_reprocess(props)): + reprocess_formats.append("yuv") + if (its.caps.private_reprocess(props)): + reprocess_formats.append("private") + + size = its.objects.get_available_output_sizes("jpg", props)[0] + out_surface = {"width":size[0], "height":size[1], "format":"jpg"} + + # Get proper sensitivity, exposure time, and focus distance. + s,e,_,_,fd = cam.do_3a(get_results=True) + + # Get the sharpness for each edge mode for regular requests + sharpness_regular = [] + edge_mode_reported_regular = [] + for edge_mode in range(4): + # Skip unavailable modes + if not its.caps.edge_mode(props, edge_mode): + edge_mode_reported_regular.append(edge_mode) + sharpness_regular.append(0) + continue + ret = test_edge_mode(cam, edge_mode, s, e, fd, out_surface) + edge_mode_reported_regular.append(ret["edge_mode"]) + sharpness_regular.append(ret["sharpness"]) + + print "Reported edge modes:", edge_mode_reported_regular + print "Sharpness with EE mode [0,1,2,3]:", sharpness_regular + + # Get the sharpness for each reprocess format and edge mode for + # reprocess requests. + sharpnesses_reprocess = [] + edge_mode_reported_reprocess = [] + + for reprocess_format in reprocess_formats: + # List of sharpness + sharpnesses = [] + edge_mode_reported = [] + for edge_mode in range(4): + # Skip unavailable modes + if not its.caps.edge_mode(props, edge_mode): + edge_mode_reported.append(edge_mode) + sharpnesses.append(0) + continue + + ret = test_edge_mode(cam, edge_mode, s, e, fd, out_surface, + reprocess_format) + edge_mode_reported.append(ret["edge_mode"]) + sharpnesses.append(ret["sharpness"]) + + sharpnesses_reprocess.append(sharpnesses) + edge_mode_reported_reprocess.append(edge_mode_reported) + + print "Reported edge modes:", edge_mode_reported + print "Sharpness with EE mode [0,1,2,3] for %s reprocess:" % \ + (reprocess_format) , sharpnesses + + + # Verify HQ(2) is sharper than OFF(0) + assert(sharpness_regular[2] > sharpness_regular[0]) + + # Verify ZSL(3) is similar to OFF(0) + assert(numpy.isclose(sharpness_regular[3], sharpness_regular[0], + THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + # Verify OFF(0) is not sharper than FAST(1) + assert(sharpness_regular[1] > + sharpness_regular[0] * (1.0 - THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + # Verify FAST(1) is not sharper than HQ(2) + assert(sharpness_regular[2] > + sharpness_regular[1] * (1.0 - THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + for reprocess_format in range(len(reprocess_formats)): + # Verify HQ(2) is sharper than OFF(0) + assert(sharpnesses_reprocess[reprocess_format][2] > + sharpnesses_reprocess[reprocess_format][0]) + + # Verify ZSL(3) is similar to OFF(0) + assert(numpy.isclose(sharpnesses_reprocess[reprocess_format][3], + sharpnesses_reprocess[reprocess_format][0], + THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + # Verify OFF(0) is not sharper than FAST(1) + assert(sharpnesses_reprocess[reprocess_format][1] > + sharpnesses_reprocess[reprocess_format][0] * + (1.0 - THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + # Verify FAST(1) is not sharper than HQ(2) + assert(sharpnesses_reprocess[reprocess_format][2] > + sharpnesses_reprocess[reprocess_format][1] * + (1.0 - THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + + # Verify reprocessing HQ(2) is similar to regular HQ(2) relative to + # OFF(0) + assert(numpy.isclose(sharpnesses_reprocess[reprocess_format][2] / + sharpnesses_reprocess[reprocess_format][0], + sharpness_regular[2] / sharpness_regular[0], + THRESHOLD_RELATIVE_SHARPNESS_DIFF)) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tools/config.py b/apps/CameraITS/tools/config.py index 6e83412..52929aa 100644 --- a/apps/CameraITS/tools/config.py +++ b/apps/CameraITS/tools/config.py
@@ -44,7 +44,7 @@ # Command line args, ignoring any args that will be passed down to the # ItsSession constructor. args = [s for s in sys.argv if s[:6] not in \ - ["reboot", "camera", "target", "noinit"]] + ["reboot", "camera", "target", "device"]] if len(args) == 1: with its.device.ItsSession() as cam:
diff --git a/apps/CameraITS/tools/convert_yuv_to_jpg.py b/apps/CameraITS/tools/convert_yuv_to_jpg.py new file mode 100644 index 0000000..4498c2a --- /dev/null +++ b/apps/CameraITS/tools/convert_yuv_to_jpg.py
@@ -0,0 +1,37 @@ +# Copyright 2015 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. + +import its.image +import sys + +def main(): + """Open a YUV420 file and save it as a JPEG. + + Command line args: + filename.yuv: The YUV420 file to open. + w: The width of the image. + h: The height of the image. + layout: The layout of the data, in ["planar", "nv21"]. + """ + if len(sys.argv) != 5: + print "Usage: python %s <filename.yuv> <w> <h> <layout>"%(sys.argv[0]) + else: + fname, w,h = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) + layout = sys.argv[4] + img = its.image.load_yuv420_to_rgb_image(fname, w,h, layout=layout) + its.image.write_image(img, fname.replace(".yuv",".jpg"), False) + +if __name__ == '__main__': + main() +
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py index 2bbd387..dd12512 100644 --- a/apps/CameraITS/tools/run_all_tests.py +++ b/apps/CameraITS/tools/run_all_tests.py
@@ -41,12 +41,20 @@ "test_ev_compensation_advanced", "test_ev_compensation_basic", "test_yuv_plus_jpeg" - ] + ], + "scene2":[], + "scene3":[] } # Get all the scene0 and scene1 tests, which can be run using the same # physical setup. - scenes = ["scene0", "scene1"] + scenes = ["scene0", "scene1", "scene2", "scene3"] + scene_req = { + "scene0" : None, + "scene1" : "A grey card covering at least the middle 30% of the scene", + "scene2" : "A picture containing human faces", + "scene3" : "A chart containing sharp edges like ISO 12233" + } tests = [] for d in scenes: tests += [(d,s[:-3],os.path.join("tests", d, s)) @@ -58,6 +66,10 @@ topdir = tempfile.mkdtemp() print "Saving output files to:", topdir, "\n" + device_id = its.device.get_device_id() + device_id_arg = "device=" + device_id + print "Testing device " + device_id + camera_ids = [] for s in sys.argv[1:]: if s[:7] == "camera=" and len(s) > 7: @@ -68,7 +80,8 @@ camera_ids_path = os.path.join(topdir, "camera_ids.txt") out_arg = "out=" + camera_ids_path cmd = ['python', - os.path.join(os.getcwd(),"tools/get_camera_ids.py"), out_arg] + os.path.join(os.getcwd(),"tools/get_camera_ids.py"), out_arg, + device_id_arg] retcode = subprocess.call(cmd,cwd=topdir) assert(retcode == 0) with open(camera_ids_path, "r") as f: @@ -86,14 +99,6 @@ for d in scenes: os.mkdir(os.path.join(topdir, camera_id, d)) - out_path = os.path.join(topdir, camera_id, "scene.jpg") - out_arg = "out=" + out_path - cmd = ['python', - os.path.join(os.getcwd(),"tools/validate_scene.py"), - camera_id_arg, out_arg] - retcode = subprocess.call(cmd,cwd=topdir) - assert(retcode == 0) - print "Start running ITS on camera: ", camera_id # Run each test, capturing stdout and stderr. summary = "ITS test result summary for camera " + camera_id + "\n" @@ -102,7 +107,19 @@ numnotmandatedfail = 0 numfail = 0 + prev_scene = "" for (scene,testname,testpath) in tests: + if scene != prev_scene and scene_req[scene] != None: + out_path = os.path.join(topdir, camera_id, scene+".jpg") + out_arg = "out=" + out_path + scene_arg = "scene=" + scene_req[scene] + cmd = ['python', + os.path.join(os.getcwd(),"tools/validate_scene.py"), + camera_id_arg, out_arg, scene_arg, device_id_arg] + retcode = subprocess.call(cmd,cwd=topdir) + assert(retcode == 0) + print "Start running tests for", scene + prev_scene = scene cmd = ['python', os.path.join(os.getcwd(),testpath)] + \ sys.argv[1:] + [camera_id_arg] outdir = os.path.join(topdir,camera_id,scene) @@ -158,7 +175,7 @@ summary_path = os.path.join(topdir, camera_id, "summary.txt") with open(summary_path, "w") as f: f.write(summary) - its.device.report_result(camera_id, result, summary_path) + its.device.report_result(device_id, camera_id, result, summary_path) print "ITS tests finished. Please go back to CtsVerifier and proceed"
diff --git a/apps/CameraITS/tools/validate_scene.py b/apps/CameraITS/tools/validate_scene.py index e1e89f2..1f35163 100644 --- a/apps/CameraITS/tools/validate_scene.py +++ b/apps/CameraITS/tools/validate_scene.py
@@ -16,17 +16,26 @@ import its.device import its.objects import its.image +import its.caps +import re def main(): """capture a yuv image and save it to argv[1] """ camera_id = -1 out_path = "" + scene_name = "" + scene_desc = "No requirement" for s in sys.argv[1:]: if s[:7] == "camera=" and len(s) > 7: camera_id = s[7:] elif s[:4] == "out=" and len(s) > 4: out_path = s[4:] + elif s[:6] == "scene=" and len(s) > 6: + scene_desc = s[6:] + + if out_path != "": + scene_name = re.split("/|\.", out_path)[-2] if camera_id == -1: print "Error: need to specify which camera to use" @@ -34,13 +43,16 @@ with its.device.ItsSession() as cam: raw_input("Press Enter after placing camera " + camera_id + - " to frame the test scene") + " to frame the test scene: " + scene_name + + "\nThe scene setup should be: " + scene_desc ) # Converge 3A prior to capture. cam.do_3a(do_af=True, lock_ae=True, lock_awb=True) props = cam.get_camera_properties() req = its.objects.fastest_auto_capture_request(props) - req["android.control.awbLock"] = True - req["android.control.aeLock"] = True + if its.caps.ae_lock(props): + req["android.control.awbLock"] = True + if its.caps.awb_lock(props): + req["android.control.aeLock"] = True while True: print "Capture an image to check the test scene" cap = cam.do_capture(req) @@ -49,7 +61,8 @@ its.image.write_image(img, out_path) print "Please check scene setup in", out_path choice = raw_input( - "Is the image okay for ITS scene1? (Y/N)").lower() + "Is the image okay for ITS " + scene_name +\ + "? (Y/N)").lower() if choice == "y": break else:
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk index dc5fda5..8cec7ea 100644 --- a/apps/CtsVerifier/Android.mk +++ b/apps/CtsVerifier/Android.mk
@@ -30,11 +30,20 @@ compatibility-common-util-devicesidelib_v2 \ cts-sensors-tests \ ctstestrunner \ + apache-commons-math \ + androidplot \ + ctsverifier-opencv \ + core-tests \ + android-support-v4 \ + mockito-target \ + mockwebserver \ + compatibility-device-util_v2 \ LOCAL_PACKAGE_NAME := CtsVerifier -LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni \ - #libcameraanalyzer # Needed for the disabled CameraAnalyzer tests +LOCAL_AAPT_FLAGS += --version-name "6.0_r0 $(BUILD_NUMBER)" + +LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni libaudioloopback_jni LOCAL_PROGUARD_FLAG_FILES := proguard.flags @@ -44,13 +53,25 @@ include $(BUILD_PACKAGE) + +# opencv library +include $(CLEAR_VARS) + +LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := \ + ctsverifier-opencv:libs/opencv-android.jar + +include $(BUILD_MULTI_PREBUILT) + + notification-bot := $(call intermediates-dir-for,APPS,NotificationBot)/package.apk +permission-app := $(call intermediates-dir-for,APPS,CtsPermissionApp)/package.apk # Builds and launches CTS Verifier on a device. .PHONY: cts-verifier -cts-verifier: CtsVerifier adb NotificationBot +cts-verifier: CtsVerifier adb NotificationBot CtsPermissionApp adb install -r $(PRODUCT_OUT)/data/app/CtsVerifier/CtsVerifier.apk \ && adb install -r $(notification-bot) \ + && adb install -r $(permission-app) \ && adb shell "am start -n com.android.cts.verifier/.CtsVerifierActivity" # @@ -87,10 +108,12 @@ endif $(verifier-zip) : $(HOST_OUT)/CameraITS $(verifier-zip) : $(notification-bot) +$(verifier-zip) : $(permission-app) $(verifier-zip) : $(call intermediates-dir-for,APPS,CtsVerifier)/package.apk | $(ACP) $(hide) mkdir -p $(verifier-dir) $(hide) $(ACP) -fp $< $(verifier-dir)/CtsVerifier.apk $(ACP) -fp $(notification-bot) $(verifier-dir)/NotificationBot.apk + $(ACP) -fp $(permission-app) $(verifier-dir)/CtsPermissionApp.apk ifeq ($(HOST_OS),linux) $(hide) $(ACP) -fp $(HOST_OUT)/bin/cts-usb-accessory $(verifier-dir)/cts-usb-accessory endif
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml index aa1063d..e1d4eb0 100644 --- a/apps/CtsVerifier/AndroidManifest.xml +++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -17,10 +17,9 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.cts.verifier" - android:versionCode="5" - android:versionName="5.1_r1"> + android:versionCode="5"> - <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="21"/> + <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> @@ -57,6 +56,7 @@ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="com.android.providers.tv.permission.READ_EPG_DATA" /> <uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA" /> + <uses-permission android:name="android.permission.USE_FINGERPRINT"/> <!-- Needed by the Audio Quality Verifier to store the sound samples that will be mailed. --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> @@ -353,6 +353,29 @@ <meta-data android:name="test_category" android:value="@string/test_category_security" /> </activity> + <activity android:name=".security.FingerprintBoundKeysTest" + android:label="@string/sec_fingerprint_bound_key_test" + android:configChanges="keyboardHidden|orientation|screenSize" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_security" /> + <meta-data android:name="test_excluded_features" + android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" /> + <meta-data android:name="test_required_features" android:value="android.hardware.fingerprint" /> + </activity> + <activity android:name=".security.ScreenLockBoundKeysTest" + android:label="@string/sec_lock_bound_key_test" + android:configChanges="keyboardHidden|orientation|screenSize" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_security" /> + <meta-data android:name="test_excluded_features" + android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" /> + </activity> <activity android:name=".security.LockConfirmBypassTest" android:label="@string/lock_confirm_test_title" android:configChanges="keyboardHidden|orientation|screenSize" > @@ -430,6 +453,10 @@ android:label="@string/nfc_ndef_push_receiver" android:configChanges="keyboardHidden|orientation|screenSize" /> + <activity android:name=".nfc.LlcpVersionActivity" + android:label="@string/nfc_llcp_version_check" + android:configChanges="keyboardHidden|orientation|screenSize" /> + <activity android:name=".nfc.TagVerifierActivity" android:label="@string/nfc_tag_verifier" android:configChanges="keyboardHidden|orientation|screenSize" /> @@ -720,6 +747,31 @@ android:value="android.hardware.sensor.compass" /> </activity> + <activity + android:name=".sensors.RVCVXCheckTestActivity" + android:keepScreenOn="true" + android:label="@string/snsr_rvcvxchk_test" + android:screenOrientation="locked" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST_disabled"/> + </intent-filter> + + <meta-data + android:name="test_category" + android:value="@string/test_category_sensors" /> + <meta-data + android:name="test_required_features" + android:value="android.hardware.sensor.accelerometer:android.hardware.sensor.gyroscope:android.hardware.sensor.compass:android.hardware.camera.any" /> + </activity> + <activity + android:name=".sensors.RVCVRecordActivity" + android:keepScreenOn="true" + android:label="@string/snsr_rvcvxchk_test_rec" + android:screenOrientation="locked" > + </activity> + + <!-- TODO: enable when a full set of verifications can be implemented --> <!--activity android:name=".sensors.RotationVectorTestActivity" android:label="@string/snsr_rot_vec_test" @@ -872,23 +924,6 @@ <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/> </activity> -<!-- Experimental. If re-enabling, libcameraanalyzer must be included in the build - <activity android:name=".camera.analyzer.CameraAnalyzerActivity" - android:label="@string/camera_analyzer" - android:screenOrientation="landscape"> - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.cts.intent.category.MANUAL_TEST" /> - </intent-filter> - <meta-data android:name="test_category" android:value="@string/test_category_camera" /> - - <intent-filter> - <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" /> - </intent-filter> - <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" - android:resource="@xml/accessory_filter_adk" /> - </activity> ---> <activity android:name=".camera.intents.CameraIntentsActivity" android:label="@string/camera_intents"> @@ -962,6 +997,17 @@ <meta-data android:name="test_required_features" android:value="android.hardware.camera.any" /> </activity> + <activity android:name=".camera.flashlight.CameraFlashlightActivity" + android:label="@string/camera_flashlight_test" + android:configChanges="keyboardHidden|orientation|screenSize"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_camera" /> + <meta-data android:name="test_required_features" android:value="android.hardware.camera.flash" /> + </activity> + <activity android:name=".usb.UsbAccessoryTestActivity" android:label="@string/usb_accessory_test" android:configChanges="keyboardHidden|orientation|screenSize"> @@ -1069,6 +1115,22 @@ android:value="android.software.leanback" /> </activity> + <activity android:name=".security.KeyChainTest" + android:label="@string/keychain_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_security" /> + <!-- KeyChain is only installed on communication-oriented devices inheriting core.mk --> + <meta-data android:name="test_excluded_features" + android:value="android.hardware.type.watch" /> + <meta-data android:name="test_excluded_features" + android:value="android.hardware.type.television" /> + <meta-data android:name="test_excluded_features" + android:value="android.software.leanback" /> + </activity> + <activity android:name=".p2p.GoNegRequesterTestListActivity" android:label="@string/p2p_go_neg_requester" android:configChanges="keyboardHidden|orientation|screenSize" /> @@ -1133,8 +1195,6 @@ <meta-data android:name="test_category" android:value="@string/test_category_other" /> <meta-data android:name="test_required_features" android:value="android.software.app_widgets" /> - <meta-data android:name="test_excluded_features" - android:value="android.software.leanback" /> </activity> <activity android:name=".deskclock.DeskClockTestsActivity" @@ -1166,6 +1226,23 @@ android:value="android.hardware.type.television:android.software.leanback" /> </activity> --> + <activity + android:name="com.android.cts.verifier.sensors.DeviceSuspendTestActivity" + android:label="@string/snsr_device_suspend_test" + android:screenOrientation="nosensor" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_sensors" /> + </activity> + + <receiver android:name="com.android.cts.verifier.sensors.DeviceSuspendTestActivity$AlarmReceiver"> + </receiver> + + <receiver android:name="com.android.cts.verifier.sensors.SignificantMotionTestActivity$AlarmReceiver"> + </receiver> + <activity android:name="com.android.cts.verifier.sensors.SignificantMotionTestActivity" android:label="@string/snsr_significant_motion_test" @@ -1266,16 +1343,65 @@ android:label="@string/projection_service_name" android:process=":projectionservice" /> - <activity android:name=".managedprovisioning.DeviceOwnerTestActivity" + <activity android:name=".managedprovisioning.DeviceOwnerNegativeTestActivity" android:label="@string/provisioning_device_owner"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.cts.intent.category.MANUAL_TEST" /> </intent-filter> <meta-data android:name="test_category" android:value="@string/test_category_managed_provisioning" /> - <meta-data android:name="test_required_features" android:value="android.software.managed_users:android.software.device_admin" /> + <meta-data android:name="test_required_features" android:value="android.software.device_admin" /> </activity> + <activity android:name=".managedprovisioning.DeviceOwnerPositiveTestActivity" + android:label="@string/positive_device_owner"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_managed_provisioning" /> + <meta-data android:name="test_required_features" android:value="android.software.device_admin" /> + </activity> + + <activity android:name=".managedprovisioning.DeviceOwnerPositiveTestActivity$CommandReceiver" + android:exported="false" + android:theme="@android:style/Theme.NoDisplay" + android:noHistory="true" + android:autoRemoveFromRecents="true" + android:stateNotNeeded="true"> + </activity> + + <activity android:name=".managedprovisioning.KeyguardDisabledFeaturesActivity" + android:label="@string/provisioning_byod_keyguard_disabled_features"> + </activity> + + <activity android:name=".managedprovisioning.WifiLockdownTestActivity" + android:label="@string/device_owner_wifi_lockdown_test"> + </activity> + + <activity android:name=".managedprovisioning.PermissionLockdownTestActivity" + android:label="@string/device_profile_owner_permission_lockdown_test"> + <intent-filter> + <action android:name="com.android.cts.verifier.managedprovisioning.action.CHECK_PERMISSION_LOCKDOWN" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + + <activity-alias + android:name=".managedprovisioning.ManagedProfilePermissionLockdownTestActivity" + android:targetActivity=".managedprovisioning.PermissionLockdownTestActivity"> + <intent-filter> + <action android:name="com.android.cts.verifier.managedprovisioning.action.MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity-alias> + + <activity android:name=".managedprovisioning.AuthenticationBoundKeyTestActivity"> + <intent-filter> + <action android:name="com.android.cts.verifier.managedprovisioning.action.AUTH_BOUND_KEY_TEST" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> <activity android:name=".managedprovisioning.ByodFlowTestActivity" android:launchMode="singleTask" @@ -1297,10 +1423,15 @@ <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_QUERY" /> <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_REMOVE" /> <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_INSTALL_APK" /> + <action android:name="com.android.cts.verifier.managedprovisioning.action.CHECK_INTENT_FILTERS" /> <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_IMAGE" /> <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_VIDEO" /> <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_AUDIO" /> + <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_KEYGUARD_DISABLED_FEATURES" /> + <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_LOCKNOW" /> <action android:name="com.android.cts.verifier.managedprovisioning.TEST_NFC_BEAM" /> + <action android:name="com.android.cts.verifier.managedprovisioning.action.TEST_CROSS_PROFILE_INTENTS_DIALOG" /> + <action android:name="com.android.cts.verifier.managedprovisioning.action.TEST_APP_LINKING_DIALOG" /> <category android:name="android.intent.category.DEFAULT"></category> </intent-filter> </activity> @@ -1328,7 +1459,94 @@ <activity android:name=".managedprovisioning.CrossProfileTestActivity"> <intent-filter> - <action android:name="com.android.cts.verifier.managedprovisioning.CROSS_PROFILE" /> + <action android:name="com.android.cts.verifier.managedprovisioning.CROSS_PROFILE_TO_PERSONAL" /> + <action android:name="com.android.cts.verifier.managedprovisioning.CROSS_PROFILE_TO_WORK" /> + <!-- We need to have at least one activity listening to these intents on the device + to test if these are forwarded from the managed profile to the parent or + the other way around. --> + <action android:name="android.provider.MediaStore.RECORD_SOUND" /> + <action android:name="android.speech.action.RECOGNIZE_SPEECH" /> + <action android:name="android.app.action.SET_NEW_PASSWORD" /> + <action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" /> + <action android:name="android.intent.action.WEB_SEARCH" /> + <action android:name="android.intent.action.VIEW_DOWNLOADS" /> + <action android:name="android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL" /> + <action android:name="android.settings.SHOW_INPUT_METHOD_PICKER" /> + <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" /> + <action android:name="com.android.settings.TTS_SETTINGS" /> + <action android:name="android.settings.ZEN_MODE_SETTINGS" /> + <action android:name="android.settings.BATTERY_SAVER_SETTINGS" /> + <action android:name="android.settings.INPUT_METHOD_SETTINGS" /> + <action android:name="android.settings.INPUT_METHOD_SUBTYPE_SETTINGS" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.SEND" /> + <action android:name="android.intent.action.SEND_MULTIPLE" /> + <data android:mimeType="*/*" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.GET_CONTENT" /> + <action android:name="android.intent.action.OPEN_DOCUMENT" /> + <data android:mimeType="*/*" /> + <category android:name="android.intent.category.OPENABLE" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.SENDTO" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="sms" /> + <data android:scheme="smsto" /> + <data android:scheme="mms" /> + <data android:scheme="mmsto" /> + <data android:scheme="mailto" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.CALL" /> + <action android:name="android.intent.action.DIAL" /> + <action android:name="android.intent.action.CALL_PRIVILEGED" /> + <action android:name="android.intent.action.CALL_EMERGENCY" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="tel" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.INSERT" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="content" /> + <data android:mimeType="*/*" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="http" android:host="com.android.cts.verifier" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="http" /> + <data android:mimeType="video/mp4" /> + <data android:mimeType="audio/*" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <category android:name="android.intent.category.BROWSABLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:scheme="http" /> + <data android:scheme="geo" /> + <data android:scheme="market" /> + </intent-filter> + </activity> + + <activity android:name=".managedprovisioning.WorkStatusTestActivity"> + <intent-filter> + <action android:name="com.android.cts.verifier.managedprovisioning.WORK_STATUS_ICON" /> + <action android:name="com.android.cts.verifier.managedprovisioning.WORK_STATUS_TOAST" /> <category android:name="android.intent.category.DEFAULT"></category> </intent-filter> </activity> @@ -1336,13 +1554,14 @@ <activity android:name=".managedprovisioning.WorkNotificationTestActivity"> <intent-filter> <action android:name="com.android.cts.verifier.managedprovisioning.WORK_NOTIFICATION" /> + <action android:name="com.android.cts.verifier.managedprovisioning.LOCKSCREEN_NOTIFICATION" /> <action android:name="com.android.cts.verifier.managedprovisioning.CLEAR_WORK_NOTIFICATION" /> <category android:name="android.intent.category.DEFAULT"></category> </intent-filter> </activity> <receiver android:name=".managedprovisioning.DeviceAdminTestReceiver" - android:label="@string/provisioning_byod_device_admin" + android:label="@string/afw_device_admin" android:permission="android.permission.BIND_DEVICE_ADMIN"> <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_byod" /> @@ -1427,6 +1646,29 @@ android:value="android.software.live_tv" /> </activity> + <activity android:name=".tv.TimeShiftTestActivity" + android:label="@string/tv_time_shift_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_tv" /> + <meta-data android:name="test_required_features" + android:value="android.software.live_tv" /> + </activity> + + <activity android:name=".tv.AppLinkTestActivity" + android:label="@string/tv_app_link_test" + android:launchMode="singleTask"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_tv" /> + <meta-data android:name="test_required_features" + android:value="android.software.live_tv" /> + </activity> + <activity android:name=".screenpinning.ScreenPinningTestActivity" android:label="@string/screen_pinning_test"> <intent-filter> @@ -1434,12 +1676,8 @@ <category android:name="android.cts.intent.category.MANUAL_TEST" /> </intent-filter> <meta-data android:name="test_category" android:value="@string/test_category_other" /> - </activity> - - <activity android:name=".tv.MockTvInputSettingsActivity"> - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - </intent-filter> + <meta-data android:name="test_excluded_features" + android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" /> </activity> <activity android:name=".tv.MockTvInputSetupActivity"> @@ -1448,6 +1686,99 @@ </intent-filter> </activity> + <activity android:name=".audio.HifiUltrasoundTestActivity" + android:label="@string/hifi_ultrasound_test" + android:screenOrientation="locked"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + </activity> + + <activity android:name=".audio.HifiUltrasoundSpeakerTestActivity" + android:label="@string/hifi_ultrasound_speaker_test" + android:screenOrientation="locked"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + </activity> + + <activity android:name=".audio.AudioDeviceNotificationsActivity" + android:label="@string/audio_devices_notifications_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <!-- + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + --> + </activity> + + <activity android:name=".audio.AudioRoutingNotificationsActivity" + android:label="@string/audio_routingnotifications_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <!-- + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + --> + </activity> + + <activity android:name=".audio.AudioLoopbackActivity" + android:label="@string/audio_loopback_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" /> + <meta-data android:name="test_excluded_features" android:value="android.hardware.type.watch" /> + <meta-data android:name="test_excluded_features" android:value="android.hardware.type.television" /> + </activity> + + <activity android:name=".audio.AudioFrequencyLineActivity" + android:label="@string/audio_frequency_line_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" /> + </activity> + + <activity android:name=".audio.AudioFrequencySpeakerActivity" + android:label="@string/audio_frequency_speaker_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" /> + <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" /> + </activity> + + <activity android:name=".audio.AudioFrequencyMicActivity" + android:label="@string/audio_frequency_mic_test"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.cts.intent.category.MANUAL_TEST" /> + </intent-filter> + <meta-data android:name="test_category" android:value="@string/test_category_audio" /> + <meta-data android:name="test_required_features" android:value="android.hardware.microphone" /> + <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" /> + <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" /> + </activity> + <service android:name=".tv.MockTvInputService" android:permission="android.permission.BIND_TV_INPUT"> <intent-filter>
diff --git a/apps/CtsVerifier/create_test_certs.sh b/apps/CtsVerifier/create_test_certs.sh new file mode 100755 index 0000000..b59974a --- /dev/null +++ b/apps/CtsVerifier/create_test_certs.sh
@@ -0,0 +1,85 @@ +#!/bin/bash + +# +# Creates or overwrites 3 files in ./res/raw: +# - cacert.der +# - userkey.der +# - usercert.der +# + +tmpdir=$(mktemp -d './XXXXXXXX') +trap 'rm -r ${tmpdir}; echo; exit 1' EXIT INT QUIT + +# CA_default defined in openssl.cnf +CA_DIR='demoCA' + +SUBJECT=\ +'/C=US'\ +'/ST=CA'\ +'/L=Mountain View'\ +'/O=Android'\ +'/CN=localhost' +PASSWORD='androidtest' + +echo "Creating directory '$CA_DIR'..." +mkdir -p "$tmpdir"/"$CA_DIR"/newcerts \ + && echo '01' > "$tmpdir"/"$CA_DIR"/serial \ + && touch "$tmpdir"/"$CA_DIR"/index.txt + +echo "Generating CA certificate..." +(cd "$tmpdir" \ + && openssl req \ + -new \ + -x509 \ + -days 3650 \ + -extensions v3_ca \ + -keyout 'cakey.pem' \ + -out 'cacert.pem' \ + -subj "$SUBJECT" \ + -passout 'pass:'"$PASSWORD" \ + && openssl x509 \ + -outform DER \ + -in 'cacert.pem' \ + -out 'cacert.der') + +echo "Generating user key..." +(cd "$tmpdir" \ + && openssl req \ + -newkey rsa:2048 \ + -sha256 \ + -keyout 'userkey.pem' \ + -nodes \ + -days 3650 \ + -out 'userkey.req' \ + -subj "$SUBJECT" \ + && openssl pkcs8 \ + -topk8 \ + -outform DER \ + -in 'userkey.pem' \ + -out 'userkey.der' \ + -nocrypt) + +echo "Generating user certificate..." +(cd "$tmpdir" \ + && openssl ca \ + -out 'usercert.pem' \ + -in 'userkey.req' \ + -cert 'cacert.pem' \ + -keyfile 'cakey.pem' \ + -days 3650 \ + -passin 'pass:'"$PASSWORD" \ + -batch \ + && openssl x509 \ + -outform DER \ + -in 'usercert.pem' \ + -out 'usercert.der') + +# Copy important files to raw resources directory +cp \ + "$tmpdir"/cacert.der \ + "$tmpdir"/userkey.der \ + "$tmpdir"/usercert.der \ + 'res/raw/' + +echo "Finished" +exit
diff --git a/apps/CtsVerifier/jni/audio_loopback/Android.mk b/apps/CtsVerifier/jni/audio_loopback/Android.mk new file mode 100644 index 0000000..3dfbc34 --- /dev/null +++ b/apps/CtsVerifier/jni/audio_loopback/Android.mk
@@ -0,0 +1,28 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := libaudioloopback_jni +LOCAL_MODULE_TAGS := optional +LOCAL_SRC_FILES := \ + sles.cpp \ + jni_sles.c + +LOCAL_C_INCLUDES := \ + system/media/audio_utils/include \ + frameworks/wilhelm/include + +LOCAL_SHARED_LIBRARIES := \ + libutils \ + libcutils \ + libOpenSLES \ + libnbaio \ + liblog \ + libaudioutils + +LOCAL_PRELINK_MODULE := false + +LOCAL_LDFLAGS := -Wl,--hash-style=sysv +LOCAL_CFLAGS := -DSTDC_HEADERS + +include $(BUILD_SHARED_LIBRARY)
diff --git a/apps/CtsVerifier/jni/audio_loopback/jni_sles.c b/apps/CtsVerifier/jni/audio_loopback/jni_sles.c new file mode 100644 index 0000000..a865078 --- /dev/null +++ b/apps/CtsVerifier/jni/audio_loopback/jni_sles.c
@@ -0,0 +1,64 @@ +/* + * Copyright (C) 2015 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. + */ + +#include <android/log.h> +#include "sles.h" +#include "jni_sles.h" +#include <stdio.h> +#include <stddef.h> + +///// +JNIEXPORT jlong JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesInit + (JNIEnv *env __unused, jobject obj __unused, jint samplingRate, jint frameCount, jint micSource) { + + sles_data * pSles = NULL; + + if (slesInit(&pSles, samplingRate, frameCount, micSource) != SLES_FAIL) { + + return (long)pSles; + } + // FIXME This should be stored as a (long) field in the object, + // so that incorrect Java code could not synthesize a bad sles pointer. + return 0; +} + +JNIEXPORT jint JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesProcessNext + (JNIEnv *env __unused, jobject obj __unused, jlong sles, jdoubleArray samplesArray, + jlong offset) { + sles_data * pSles= (sles_data*) ((long)sles); + + long maxSamples = (*env)->GetArrayLength(env, samplesArray); + double *pSamples = (*env)->GetDoubleArrayElements(env, samplesArray,0); + + long availableSamples = maxSamples-offset; + double *pCurrentSample = pSamples+offset; + + SLES_PRINTF("jni slesProcessNext pSles:%p, currentSample %p, availableSamples %ld ", pSles, + pCurrentSample, availableSamples); + + int samplesRead = slesProcessNext(pSles, pCurrentSample, availableSamples); + + return samplesRead; +} + +JNIEXPORT jint JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesDestroy + (JNIEnv *env __unused, jobject obj __unused, jlong sles) { + sles_data * pSles= (sles_data*) ((long) sles); + + int status = slesDestroy(&pSles); + + return status; +}
diff --git a/apps/CtsVerifier/jni/audio_loopback/jni_sles.h b/apps/CtsVerifier/jni/audio_loopback/jni_sles.h new file mode 100644 index 0000000..7bff040 --- /dev/null +++ b/apps/CtsVerifier/jni/audio_loopback/jni_sles.h
@@ -0,0 +1,40 @@ +/* + * Copyright (C) 2015 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. + */ + +#include <jni.h> + +#ifndef _Included_org_drrickorang_loopback_jni +#define _Included_org_drrickorang_loopback_jni +#ifdef __cplusplus +extern "C" { +#endif + + +//////////////////////// +JNIEXPORT jlong JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesInit + (JNIEnv *, jobject, jint, jint, jint ); + +JNIEXPORT jint JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesProcessNext + (JNIEnv *, jobject , jlong, jdoubleArray, jlong ); + +JNIEXPORT jint JNICALL Java_com_android_cts_verifier_audio_NativeAudioThread_slesDestroy + (JNIEnv *, jobject , jlong ); + + +#ifdef __cplusplus +} +#endif +#endif //_Included_org_drrickorang_loopback_jni
diff --git a/apps/CtsVerifier/jni/audio_loopback/sles.cpp b/apps/CtsVerifier/jni/audio_loopback/sles.cpp new file mode 100644 index 0000000..7859d35 --- /dev/null +++ b/apps/CtsVerifier/jni/audio_loopback/sles.cpp
@@ -0,0 +1,655 @@ +/* + * Copyright (C) 2015 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. + */ + + +//////////////////////////////////////////// +/// Actual sles functions. + + +// Test program to record from default audio input and playback to default audio output. +// It will generate feedback (Larsen effect) if played through on-device speakers, +// or acts as a delay if played through headset. + +#include "sles.h" +#include <stdio.h> +#include <stdlib.h> +#include <stddef.h> + +#include <assert.h> +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +int slesInit(sles_data ** ppSles, int samplingRate, int frameCount, int micSource) { + int status = SLES_FAIL; + if (ppSles != NULL) { + sles_data * pSles = (sles_data*) calloc(1, sizeof (sles_data)); + + SLES_PRINTF("malloc %d bytes at %p",sizeof(sles_data), pSles); + *ppSles = pSles; + if (pSles != NULL) + { + SLES_PRINTF("creating server. Sampling rate =%d, frame count = %d",samplingRate, + frameCount); + status = slesCreateServer(pSles, samplingRate, frameCount, micSource); + SLES_PRINTF("slesCreateServer =%d",status); + } + } + return status; +} +int slesDestroy(sles_data ** ppSles) { + int status = SLES_FAIL; + if (ppSles != NULL) { + slesDestroyServer(*ppSles); + + if (*ppSles != NULL) + { + free(*ppSles); + *ppSles = 0; + } + status = SLES_SUCCESS; + } + return status; +} + +#define ASSERT_EQ(x, y) do { if ((x) == (y)) ; else { fprintf(stderr, "0x%x != 0x%x\n", \ + (unsigned) (x), (unsigned) (y)); assert((x) == (y)); } } while (0) + + +// Called after audio recorder fills a buffer with data +static void recorderCallback(SLAndroidSimpleBufferQueueItf caller __unused, void *context) { + sles_data *pSles = (sles_data*) context; + if (pSles != NULL) { + + + + SLresult result; + + pthread_mutex_lock(&(pSles->mutex)); + //ee SLES_PRINTF("<R"); + + // We should only be called when a recording buffer is done + assert(pSles->rxFront <= pSles->rxBufCount); + assert(pSles->rxRear <= pSles->rxBufCount); + assert(pSles->rxFront != pSles->rxRear); + char *buffer = pSles->rxBuffers[pSles->rxFront]; + + // Remove buffer from record queue + if (++pSles->rxFront > pSles->rxBufCount) { + pSles->rxFront = 0; + } + + ssize_t actual = audio_utils_fifo_write(&(pSles->fifo), buffer, + (size_t) pSles->bufSizeInFrames); + if (actual != (ssize_t) pSles->bufSizeInFrames) { + write(1, "?", 1); + } + + // This is called by a realtime (SCHED_FIFO) thread, + // and it is unsafe to do I/O as it could block for unbounded time. + // Flash filesystem is especially notorious for blocking. + if (pSles->fifo2Buffer != NULL) { + actual = audio_utils_fifo_write(&(pSles->fifo2), buffer, + (size_t) pSles->bufSizeInFrames); + if (actual != (ssize_t) pSles->bufSizeInFrames) { + write(1, "?", 1); + } + } + + // Enqueue this same buffer for the recorder to fill again. + result = (*(pSles->recorderBufferQueue))->Enqueue(pSles->recorderBufferQueue, buffer, + pSles->bufSizeInBytes); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Update our model of the record queue + SLuint32 rxRearNext = pSles->rxRear+1; + if (rxRearNext > pSles->rxBufCount) { + rxRearNext = 0; + } + assert(rxRearNext != pSles->rxFront); + pSles->rxBuffers[pSles->rxRear] = buffer; + pSles->rxRear = rxRearNext; + + + + //ee SLES_PRINTF("r>"); + pthread_mutex_unlock(&(pSles->mutex)); + + } //pSles not null +} + + +// Called after audio player empties a buffer of data +static void playerCallback(SLBufferQueueItf caller __unused, void *context) { + sles_data *pSles = (sles_data*) context; + if (pSles != NULL) { + + SLresult result; + + pthread_mutex_lock(&(pSles->mutex)); + //ee SLES_PRINTF("<P"); + + // Get the buffer that just finished playing + assert(pSles->txFront <= pSles->txBufCount); + assert(pSles->txRear <= pSles->txBufCount); + assert(pSles->txFront != pSles->txRear); + char *buffer = pSles->txBuffers[pSles->txFront]; + if (++pSles->txFront > pSles->txBufCount) { + pSles->txFront = 0; + } + + + ssize_t actual = audio_utils_fifo_read(&(pSles->fifo), buffer, pSles->bufSizeInFrames); + if (actual != (ssize_t) pSles->bufSizeInFrames) { + write(1, "/", 1); + // on underrun from pipe, substitute silence + memset(buffer, 0, pSles->bufSizeInFrames * pSles->channels * sizeof(short)); + } + + if (pSles->injectImpulse == -1) { + // Experimentally, a single frame impulse was insufficient to trigger feedback. + // Also a Nyquist frequency signal was also insufficient, probably because + // the response of output and/or input path was not adequate at high frequencies. + // This short burst of a few cycles of square wave at Nyquist/4 was found to work well. + for (unsigned i = 0; i < pSles->bufSizeInFrames / 8; i += 8) { + for (int j = 0; j < 8; j++) { + for (unsigned k = 0; k < pSles->channels; k++) { + ((short *)buffer)[(i+j)*pSles->channels+k] = j < 4 ? 0x7FFF : 0x8000; + } + } + } + pSles->injectImpulse = 0; + } + + // Enqueue the filled buffer for playing + result = (*(pSles->playerBufferQueue))->Enqueue(pSles->playerBufferQueue, buffer, + pSles->bufSizeInBytes); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Update our model of the player queue + assert(pSles->txFront <= pSles->txBufCount); + assert(pSles->txRear <= pSles->txBufCount); + SLuint32 txRearNext = pSles->txRear+1; + if (txRearNext > pSles->txBufCount) { + txRearNext = 0; + } + assert(txRearNext != pSles->txFront); + pSles->txBuffers[pSles->txRear] = buffer; + pSles->txRear = txRearNext; + + + //ee SLES_PRINTF("p>"); + pthread_mutex_unlock(&(pSles->mutex)); + + } //pSles not null +} + +int slesCreateServer(sles_data *pSles, int samplingRate, int frameCount, int micSource) { + int status = SLES_FAIL; + + if (pSles == NULL) { + return status; + } + + // adb shell slesTest_feedback -r1 -t1 -s48000 -f240 -i300 -e3 -o/sdcard/log.wav + // r1 and t1 are the receive and transmit buffer counts, typically 1 + // s is the sample rate, typically 48000 or 44100 + // f is the frame count per buffer, typically 240 or 256 + // i is the number of milliseconds before impulse. You may need to adjust this. + // e is number of seconds to record + // o is output .wav file name + + + // // default values + // SLuint32 rxBufCount = 1; // -r# + // SLuint32 txBufCount = 1; // -t# + // SLuint32 bufSizeInFrames = 240; // -f# + // SLuint32 channels = 1; // -c# + // SLuint32 sampleRate = 48000; // -s# + // SLuint32 exitAfterSeconds = 3; // -e# + // SLuint32 freeBufCount = 0; // calculated + // SLuint32 bufSizeInBytes = 0; // calculated + // int injectImpulse = 300; // -i#i + // + // // Storage area for the buffer queues + // char **rxBuffers; + // char **txBuffers; + // char **freeBuffers; + // + // // Buffer indices + // SLuint32 rxFront; // oldest recording + // SLuint32 rxRear; // next to be recorded + // SLuint32 txFront; // oldest playing + // SLuint32 txRear; // next to be played + // SLuint32 freeFront; // oldest free + // SLuint32 freeRear; // next to be freed + // + // audio_utils_fifo fifo; //(*) + // SLAndroidSimpleBufferQueueItf recorderBufferQueue; + // SLBufferQueueItf playerBufferQueue; + + // default values + pSles->rxBufCount = 1; // -r# + pSles->txBufCount = 1; // -t# + pSles->bufSizeInFrames = frameCount;//240; // -f# + pSles->channels = 1; // -c# + pSles->sampleRate = samplingRate;//48000; // -s# + pSles->exitAfterSeconds = 3; // -e# + pSles->freeBufCount = 0; // calculated + pSles->bufSizeInBytes = 0; // calculated + pSles->injectImpulse = 300; // -i#i + + // Storage area for the buffer queues + // char **rxBuffers; + // char **txBuffers; + // char **freeBuffers; + + // Buffer indices + pSles->rxFront; // oldest recording + pSles->rxRear; // next to be recorded + pSles->txFront; // oldest playing + pSles->txRear; // next to be played + pSles->freeFront; // oldest free + pSles->freeRear; // next to be freed + + pSles->fifo; //(*) + pSles->fifo2Buffer = NULL; + pSles->recorderBufferQueue; + pSles->playerBufferQueue; + + // compute total free buffers as -r plus -t + pSles->freeBufCount = pSles->rxBufCount + pSles->txBufCount; + // compute buffer size + pSles->bufSizeInBytes = pSles->channels * pSles->bufSizeInFrames * sizeof(short); + + // Initialize free buffers + pSles->freeBuffers = (char **) calloc(pSles->freeBufCount+1, sizeof(char *)); + unsigned j; + for (j = 0; j < pSles->freeBufCount; ++j) { + pSles->freeBuffers[j] = (char *) malloc(pSles->bufSizeInBytes); + } + pSles->freeFront = 0; + pSles->freeRear = pSles->freeBufCount; + pSles->freeBuffers[j] = NULL; + + // Initialize record queue + pSles->rxBuffers = (char **) calloc(pSles->rxBufCount+1, sizeof(char *)); + pSles->rxFront = 0; + pSles->rxRear = 0; + + // Initialize play queue + pSles->txBuffers = (char **) calloc(pSles->txBufCount+1, sizeof(char *)); + pSles->txFront = 0; + pSles->txRear = 0; + + size_t frameSize = pSles->channels * sizeof(short); +#define FIFO_FRAMES 1024 + pSles->fifoBuffer = new short[FIFO_FRAMES * pSles->channels]; + audio_utils_fifo_init(&(pSles->fifo), FIFO_FRAMES, frameSize, pSles->fifoBuffer); + + // SNDFILE *sndfile; + // if (outFileName != NULL) { + // create .wav writer + // SF_INFO info; + // info.frames = 0; + // info.samplerate = sampleRate; + // info.channels = channels; + // info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; + // sndfile = sf_open(outFileName, SFM_WRITE, &info); + // if (sndfile != NULL) { +#define FIFO2_FRAMES 65536 + pSles->fifo2Buffer = new short[FIFO2_FRAMES * pSles->channels]; + audio_utils_fifo_init(&(pSles->fifo2), FIFO2_FRAMES, frameSize, pSles->fifo2Buffer); + // } else { + // fprintf(stderr, "sf_open failed\n"); + // } + // } else { + // sndfile = NULL; + // } + + SLresult result; + + // create engine + pSles->engineObject; + result = slCreateEngine(&(pSles->engineObject), 0, NULL, 0, NULL, NULL); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->engineObject))->Realize(pSles->engineObject, SL_BOOLEAN_FALSE); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + SLEngineItf engineEngine; + result = (*(pSles->engineObject))->GetInterface(pSles->engineObject, SL_IID_ENGINE, + &engineEngine); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // create output mix + pSles->outputmixObject; + result = (*engineEngine)->CreateOutputMix(engineEngine, &(pSles->outputmixObject), 0, NULL, + NULL); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->outputmixObject))->Realize(pSles->outputmixObject, SL_BOOLEAN_FALSE); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // create an audio player with buffer queue source and output mix sink + SLDataSource audiosrc; + SLDataSink audiosnk; + SLDataFormat_PCM pcm; + SLDataLocator_OutputMix locator_outputmix; + SLDataLocator_BufferQueue locator_bufferqueue_tx; + locator_bufferqueue_tx.locatorType = SL_DATALOCATOR_BUFFERQUEUE; + locator_bufferqueue_tx.numBuffers = pSles->txBufCount; + locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; + locator_outputmix.outputMix = pSles->outputmixObject; + pcm.formatType = SL_DATAFORMAT_PCM; + pcm.numChannels = pSles->channels; + pcm.samplesPerSec = pSles->sampleRate * 1000; + pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + pcm.containerSize = 16; + pcm.channelMask = pSles->channels == 1 ? SL_SPEAKER_FRONT_CENTER : + (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; + audiosrc.pLocator = &locator_bufferqueue_tx; + audiosrc.pFormat = &pcm; + audiosnk.pLocator = &locator_outputmix; + audiosnk.pFormat = NULL; + pSles->playerObject = NULL; + pSles->recorderObject = NULL; + SLInterfaceID ids_tx[1] = {SL_IID_BUFFERQUEUE}; + SLboolean flags_tx[1] = {SL_BOOLEAN_TRUE}; + result = (*engineEngine)->CreateAudioPlayer(engineEngine, &(pSles->playerObject), + &audiosrc, &audiosnk, 1, ids_tx, flags_tx); + if (SL_RESULT_CONTENT_UNSUPPORTED == result) { + fprintf(stderr, "Could not create audio player (result %x), check sample rate\n", + result); + SLES_PRINTF("ERROR: Could not create audio player (result %x), check sample rate\n", + result); + goto cleanup; + } + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->playerObject))->Realize(pSles->playerObject, SL_BOOLEAN_FALSE); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + SLPlayItf playerPlay; + result = (*(pSles->playerObject))->GetInterface(pSles->playerObject, SL_IID_PLAY, + &playerPlay); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->playerObject))->GetInterface(pSles->playerObject, SL_IID_BUFFERQUEUE, + &(pSles->playerBufferQueue)); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->playerBufferQueue))->RegisterCallback(pSles->playerBufferQueue, + playerCallback, pSles); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Enqueue some zero buffers for the player + for (j = 0; j < pSles->txBufCount; ++j) { + + // allocate a free buffer + assert(pSles->freeFront != pSles->freeRear); + char *buffer = pSles->freeBuffers[pSles->freeFront]; + if (++pSles->freeFront > pSles->freeBufCount) { + pSles->freeFront = 0; + } + + // put on play queue + SLuint32 txRearNext = pSles->txRear + 1; + if (txRearNext > pSles->txBufCount) { + txRearNext = 0; + } + assert(txRearNext != pSles->txFront); + pSles->txBuffers[pSles->txRear] = buffer; + pSles->txRear = txRearNext; + result = (*(pSles->playerBufferQueue))->Enqueue(pSles->playerBufferQueue, + buffer, pSles->bufSizeInBytes); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + } + + result = (*playerPlay)->SetPlayState(playerPlay, SL_PLAYSTATE_PLAYING); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Create an audio recorder with microphone device source and buffer queue sink. + // The buffer queue as sink is an Android-specific extension. + + SLDataLocator_IODevice locator_iodevice; + SLDataLocator_AndroidSimpleBufferQueue locator_bufferqueue_rx; + locator_iodevice.locatorType = SL_DATALOCATOR_IODEVICE; + locator_iodevice.deviceType = SL_IODEVICE_AUDIOINPUT; + locator_iodevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; + locator_iodevice.device = NULL; + audiosrc.pLocator = &locator_iodevice; + audiosrc.pFormat = NULL; + locator_bufferqueue_rx.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + locator_bufferqueue_rx.numBuffers = pSles->rxBufCount; + audiosnk.pLocator = &locator_bufferqueue_rx; + audiosnk.pFormat = &pcm; + { + SLInterfaceID ids_rx[2] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, + SL_IID_ANDROIDCONFIGURATION}; + SLboolean flags_rx[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; + result = (*engineEngine)->CreateAudioRecorder(engineEngine, &(pSles->recorderObject), + &audiosrc, &audiosnk, 2, ids_rx, flags_rx); + if (SL_RESULT_SUCCESS != result) { + fprintf(stderr, "Could not create audio recorder (result %x), " + "check sample rate and channel count\n", result); + status = SLES_FAIL; + + SLES_PRINTF("ERROR: Could not create audio recorder (result %x), " + "check sample rate and channel count\n", result); + goto cleanup; + } + } + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + { + /* Get the Android configuration interface which is explicit */ + SLAndroidConfigurationItf configItf; + result = (*(pSles->recorderObject))->GetInterface(pSles->recorderObject, + SL_IID_ANDROIDCONFIGURATION, (void*)&configItf); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + SLuint32 presetValue = micSource; + /* Use the configuration interface to configure the recorder before it's realized */ + if (presetValue != SL_ANDROID_RECORDING_PRESET_NONE) { + result = (*configItf)->SetConfiguration(configItf, SL_ANDROID_KEY_RECORDING_PRESET, + &presetValue, sizeof(SLuint32)); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + } + + } + + result = (*(pSles->recorderObject))->Realize(pSles->recorderObject, SL_BOOLEAN_FALSE); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + SLRecordItf recorderRecord; + result = (*(pSles->recorderObject))->GetInterface(pSles->recorderObject, SL_IID_RECORD, + &recorderRecord); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->recorderObject))->GetInterface(pSles->recorderObject, + SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &(pSles->recorderBufferQueue)); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + result = (*(pSles->recorderBufferQueue))->RegisterCallback(pSles->recorderBufferQueue, + recorderCallback, pSles); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Enqueue some empty buffers for the recorder + for (j = 0; j < pSles->rxBufCount; ++j) { + + // allocate a free buffer + assert(pSles->freeFront != pSles->freeRear); + char *buffer = pSles->freeBuffers[pSles->freeFront]; + if (++pSles->freeFront > pSles->freeBufCount) { + pSles->freeFront = 0; + } + + // put on record queue + SLuint32 rxRearNext = pSles->rxRear + 1; + if (rxRearNext > pSles->rxBufCount) { + rxRearNext = 0; + } + assert(rxRearNext != pSles->rxFront); + pSles->rxBuffers[pSles->rxRear] = buffer; + pSles->rxRear = rxRearNext; + result = (*(pSles->recorderBufferQueue))->Enqueue(pSles->recorderBufferQueue, + buffer, pSles->bufSizeInBytes); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + } + + // Kick off the recorder + result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_RECORDING); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + // Tear down the objects and exit + status = SLES_SUCCESS; + cleanup: + SLES_PRINTF("Finished initialization with status: %d", status); + + return status; +} + +int slesProcessNext(sles_data *pSles, double *pSamples, long maxSamples) { + //int status = SLES_FAIL; + + SLES_PRINTF("slesProcessNext: pSles = %p, currentSample: %p, maxSamples = %ld", pSles, + pSamples, maxSamples); + + int samplesRead = 0; + + int currentSample = 0; + double *pCurrentSample = pSamples; + int maxValue = 32768; + + if (pSles == NULL) { + return samplesRead; + } + + SLresult result; + for (int i = 0; i < 10; i++) { + usleep(100000); + if (pSles->fifo2Buffer != NULL) { + for (;;) { + short buffer[pSles->bufSizeInFrames * pSles->channels]; + ssize_t actual = audio_utils_fifo_read(&(pSles->fifo2), buffer, + pSles->bufSizeInFrames); + if (actual <= 0) + break; + { + for (int jj =0; jj<actual && currentSample < maxSamples; jj++) { + *(pCurrentSample++) = ((double)buffer[jj])/maxValue; + currentSample++; + } + } + samplesRead +=actual; + } + } + if (pSles->injectImpulse > 0) { + if (pSles->injectImpulse <= 100) { + pSles->injectImpulse = -1; + write(1, "I", 1); + } else { + if ((pSles->injectImpulse % 1000) < 100) { + write(1, "i", 1); + } + pSles->injectImpulse -= 100; + } + } else if (i == 9) { + write(1, ".", 1); + } + } + SLBufferQueueState playerBQState; + result = (*(pSles->playerBufferQueue))->GetState(pSles->playerBufferQueue, + &playerBQState); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + SLAndroidSimpleBufferQueueState recorderBQState; + result = (*(pSles->recorderBufferQueue))->GetState(pSles->recorderBufferQueue, + &recorderBQState); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + SLES_PRINTF("End of slesProcessNext: pSles = %p, samplesRead = %d, maxSamples= %ld", pSles, + samplesRead, maxSamples); + + return samplesRead; +} + +int slesDestroyServer(sles_data *pSles) { + int status = SLES_FAIL; + + SLES_PRINTF("Start slesDestroyServer: pSles = %p", pSles); + if (pSles == NULL) { + return status; + } + + if (NULL != pSles->playerObject) { + + SLES_PRINTF("stopping player..."); + SLPlayItf playerPlay; + SLresult result = (*(pSles->playerObject))->GetInterface(pSles->playerObject, + SL_IID_PLAY, &playerPlay); + + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + //stop player and recorder if they exist + result = (*playerPlay)->SetPlayState(playerPlay, SL_PLAYSTATE_STOPPED); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + } + + if (NULL != pSles->recorderObject) { + SLES_PRINTF("stopping recorder..."); + SLRecordItf recorderRecord; + SLresult result = (*(pSles->recorderObject))->GetInterface(pSles->recorderObject, + SL_IID_RECORD, &recorderRecord); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + + result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED); + ASSERT_EQ(SL_RESULT_SUCCESS, result); + } + + usleep(1000); + + audio_utils_fifo_deinit(&(pSles->fifo)); + delete[] pSles->fifoBuffer; + + SLES_PRINTF("slesDestroyServer 2"); + + // if (sndfile != NULL) { + audio_utils_fifo_deinit(&(pSles->fifo2)); + delete[] pSles->fifo2Buffer; + + SLES_PRINTF("slesDestroyServer 3"); + + // sf_close(sndfile); + // } + if (NULL != pSles->playerObject) { + (*(pSles->playerObject))->Destroy(pSles->playerObject); + } + + SLES_PRINTF("slesDestroyServer 4"); + + if (NULL != pSles->recorderObject) { + (*(pSles->recorderObject))->Destroy(pSles->recorderObject); + } + + SLES_PRINTF("slesDestroyServer 5"); + + (*(pSles->outputmixObject))->Destroy(pSles->outputmixObject); + SLES_PRINTF("slesDestroyServer 6"); + (*(pSles->engineObject))->Destroy(pSles->engineObject); + SLES_PRINTF("slesDestroyServer 7"); + + // free(pSles); + // pSles=NULL; + + status = SLES_SUCCESS; + + SLES_PRINTF("End slesDestroyServer: status = %d", status); + return status; +} +
diff --git a/apps/CtsVerifier/jni/audio_loopback/sles.h b/apps/CtsVerifier/jni/audio_loopback/sles.h new file mode 100644 index 0000000..2550b81 --- /dev/null +++ b/apps/CtsVerifier/jni/audio_loopback/sles.h
@@ -0,0 +1,94 @@ +/* + * Copyright (C) 2015 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. + */ + +#include <SLES/OpenSLES.h> +#include <SLES/OpenSLES_Android.h> +#include <pthread.h> +#include <android/log.h> + +#ifndef _Included_org_drrickorang_loopback_sles +#define _Included_org_drrickorang_loopback_sles + +//struct audio_utils_fifo; +#define SLES_PRINTF(...) __android_log_print(ANDROID_LOG_INFO, "sles_jni", __VA_ARGS__); + + +#ifdef __cplusplus +extern "C" { +#endif +#include <audio_utils/fifo.h> + +typedef struct { + SLuint32 rxBufCount; // -r# + SLuint32 txBufCount; // -t# + SLuint32 bufSizeInFrames; // -f# + SLuint32 channels; // -c# + SLuint32 sampleRate; // -s# + SLuint32 exitAfterSeconds; // -e# + SLuint32 freeBufCount; // calculated + SLuint32 bufSizeInBytes; // calculated + int injectImpulse; // -i#i + + // Storage area for the buffer queues + char **rxBuffers; + char **txBuffers; + char **freeBuffers; + + // Buffer indices + SLuint32 rxFront; // oldest recording + SLuint32 rxRear; // next to be recorded + SLuint32 txFront; // oldest playing + SLuint32 txRear; // next to be played + SLuint32 freeFront; // oldest free + SLuint32 freeRear; // next to be freed + + struct audio_utils_fifo fifo; //(*) + struct audio_utils_fifo fifo2; + short *fifo2Buffer; + short *fifoBuffer; + SLAndroidSimpleBufferQueueItf recorderBufferQueue; + SLBufferQueueItf playerBufferQueue; + + pthread_mutex_t mutex;// = PTHREAD_MUTEX_INITIALIZER; + + //other things that belong here + SLObjectItf playerObject; + SLObjectItf recorderObject; + SLObjectItf outputmixObject; + SLObjectItf engineObject; +} sles_data; + +enum { + SLES_SUCCESS = 0, + SLES_FAIL = 1, +} SLES_STATUS_ENUM; + +int slesInit(sles_data ** ppSles, int samplingRate, int frameCount, int micSource); + +//note the double pointer to properly free the memory of the structure +int slesDestroy(sles_data ** ppSles); + +///full +int slesFull(sles_data *pSles); + +int slesCreateServer(sles_data *pSles, int samplingRate, int frameCount, int micSource); +int slesProcessNext(sles_data *pSles, double *pSamples, long maxSamples); +int slesDestroyServer(sles_data *pSles); + +#ifdef __cplusplus +} +#endif +#endif //_Included_org_drrickorang_loopback_sles
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/Android.mk b/apps/CtsVerifier/jni/cameraanalyzer/Android.mk deleted file mode 100644 index d595a20..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/Android.mk +++ /dev/null
@@ -1,42 +0,0 @@ -# Copyright (C) 2011 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. -# - -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) -LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk - -LOCAL_MODULE := libcameraanalyzer - -LOCAL_MODULE_TAGS := optional - -LOCAL_SRC_FILES := com_android_cts_verifier_camera_analyzer_CameraTests.cpp \ - com_android_cts_verifier_camera_analyzer_ColorCheckerTest.cpp \ - com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.cpp \ - com_android_cts_verifier_camera_analyzer_AutoLockTest.cpp \ - com_android_cts_verifier_camera_analyzer_MeteringTest.cpp \ - com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.cpp - -LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../include/colorchecker $(JNI_H_INCLUDE) - -LOCAL_CXX_STL := libc++ -LOCAL_STATIC_LIBRARIES := libcolorchecker -LOCAL_SHARED_LIBRARIES := \ - libjnigraphics \ - libcutils \ - libutils \ - liblog \ - -include $(BUILD_SHARED_LIBRARY)
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.cpp deleted file mode 100644 index fac39e1..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.cpp +++ /dev/null
@@ -1,95 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "AutoLockJNI" -#include <utils/Log.h> -#include "com_android_cts_verifier_camera_analyzer_AutoLockTest.h" - -#include <vector> -#include <string> -#include <string.h> - -#include "testingimage.h" -#include "autolocktest.h" -#include "vec2.h" -#include "android/bitmap.h" - -jlong Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_createAutoLockTest( - JNIEnv* env, - jobject thiz) { - - AutoLockTest* testHandler = new AutoLockTest(); - long handlerAddress = (long)testHandler; - return handlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_createAutoLockClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress) { - - ALOGV("JNI createAutoLockClass starts!"); - long imageAddress = (long)inputImageAddress; - long handlerAddress = (long)inputHandlerAddress; - - TestingImage *image = (TestingImage*) imageAddress; - AutoLockTest *testHandler = (AutoLockTest*) handlerAddress; - - std::vector<std::vector< Vec2f > >* checkerCenter = - (std::vector<std::vector< Vec2f > >*) (long) checkercenterAddress; - std::vector<std::vector< float > >* checkerRadius = - (std::vector<std::vector< float > >*) (long) checkerradiusAddress; - ALOGV("Classes recovered"); - - // Uses only the gray patches on the color checker for comparison. - testHandler->addDataToList(image->getColorChecker(3, 4, 0, 6, - checkerCenter, - checkerRadius)); - - delete image; -} - -void Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_processAutoLockTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress, - jbooleanArray tempArray) { - - ALOGV("Processing Auto Lock data!"); - - long handlerAddress = (long) inputHandlerAddress; - AutoLockTest *testHandler = (AutoLockTest*) handlerAddress; - - testHandler->processData(); - - // Converts the native boolean array into a java boolean array. - const std::vector<bool>* nativeComparisonResults = - testHandler->getComparisonResults(); - jboolean comparisonResults[nativeComparisonResults->size()]; - - for (int i = 0; i < nativeComparisonResults->size(); ++i) { - comparisonResults[i] = (jboolean) (*nativeComparisonResults)[i]; - } - - env->SetBooleanArrayRegion(tempArray, - 0, nativeComparisonResults->size(), - comparisonResults); - testHandler->clearData(); -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.h deleted file mode 100644 index dc40bc2..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_AutoLockTest.h +++ /dev/null
@@ -1,52 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_AUTOLOCKTEST_H -#define JNI_CAMERAANALYZER_AUTOLOCKTEST_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_createAutoLockTest( - JNIEnv* env, - jobject thiz); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_createAutoLockClass( - JNIEnv *env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_AutoLockTest_processAutoLockTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress, - jbooleanArray tempArray); - -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.cpp deleted file mode 100644 index ed91233..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.cpp +++ /dev/null
@@ -1,223 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "CameraTestsJNI" -#include <utils/Log.h> -#include "com_android_cts_verifier_camera_analyzer_CameraTests.h" -#include "android/bitmap.h" -#include "testingimage.h" -#include "imagetesthandler.h" - -#include <string.h> - -jlong Java_com_android_cts_verifier_camera_analyzer_CameraTests_findNative( - JNIEnv* env, - jobject thiz, - jobject inputBitmap) { - - ALOGV("JNI findNative starts!"); - - // Verify that we can handle the input bitmap - AndroidBitmapInfo inputInfo; - AndroidBitmap_getInfo(env, inputBitmap, &inputInfo); - if (inputInfo.format != ANDROID_BITMAP_FORMAT_RGBA_8888 && - inputInfo.format != ANDROID_BITMAP_FORMAT_RGB_565) { - ALOGE("Only RGBA_8888 and RGB_565 bitmaps are supported, type was %d.", - inputInfo.format); - } - - // Get some references to the fields and class type of ColorChecker - jclass thizCls = env->GetObjectClass(thiz); - ALOGV("ColorChecker field and classes reference finished!"); - - // Get raw inputs and outputs ready - uint8_t *inputBuffer = NULL; - int result = AndroidBitmap_lockPixels( - env, - inputBitmap, - reinterpret_cast<void**>(&inputBuffer)); - - if (result != ANDROID_BITMAP_RESULT_SUCCESS) { - ALOGE("Unable to lock input bitmap"); - } - - uint8_t *outputImage = NULL; - int outputWidth, outputHeight; - - ALOGV("Input and output images created!"); - - // Find the color checker - bool success; - uint8_t *inputBufferRGBA = NULL; - int inputStride; - bool freeInputRGBA = false; - switch (inputInfo.format) { - case ANDROID_BITMAP_FORMAT_RGB_565: { - // First convert to RGBA_8888 - inputBufferRGBA = new uint8_t[inputInfo.width * - inputInfo.height * - 4]; - inputStride = inputInfo.width * 4; - uint8_t *outP = inputBufferRGBA; - for (int y = 0; y < inputInfo.height; y++ ) { - uint16_t *inP = (uint16_t*)(&inputBuffer[y * inputInfo.stride]); - for (int x = 0; x < inputInfo.width; x++) { - *(outP++) = ( ((*inP) >> 0) & 0x001F) << 3; - *(outP++) = ( ((*inP) >> 5) & 0x003F) << 2; - *(outP++) = ( ((*inP) >> 11) & 0x001F) << 3; - outP++; - inP++; - } - } - freeInputRGBA = true; - - ALOGV("RGB_565 Format with width, height and stride as %d, %d, %d", - inputInfo.width, inputInfo.height, inputStride); - break; - } - case ANDROID_BITMAP_FORMAT_RGBA_8888: { - // Already in RGBA - inputBufferRGBA = inputBuffer; - inputStride = inputInfo.stride; - ALOGV("RGB_8888 Format with width, height and stride as %d, %d, %d", - inputInfo.width, inputInfo.height, inputStride); - break; - } - } - - TestingImage *input_testing_image = - new TestingImage(inputBufferRGBA, inputInfo.height, inputInfo.width, - 4, inputStride, 120, 160); - - long lp = (long)input_testing_image; - - result = AndroidBitmap_unlockPixels(env, inputBitmap); - if (result != ANDROID_BITMAP_RESULT_SUCCESS) { - ALOGE("Unable to unlock input bitmap"); - } - - if (freeInputRGBA) { - ALOGV("Deleteing inputbufferRGBA"); - delete[] inputBufferRGBA; - } - - return lp; - ALOGV("Input format switched!"); -} - -jlong Java_com_android_cts_verifier_camera_analyzer_CameraTests_createImageTestHandler( - JNIEnv* env, - jobject thiz, - jint debugHeight, - jint debugWidth) { - - ImageTestHandler* testHandler = - new ImageTestHandler(debugHeight, debugWidth); - long handlerAddress = (long)testHandler; - return handlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_CameraTests_cleanUpHandler( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - ImageTestHandler* testHandler = (ImageTestHandler*) (long) inputHandlerAddress; - delete testHandler; -} - -void Java_com_android_cts_verifier_camera_analyzer_CameraTests_displayHandlerDebugOutput( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - jclass thizCls = env->GetObjectClass(thiz); - jfieldID outputId = env->GetFieldID(thizCls, "mDebugOutput", - "Landroid/graphics/Bitmap;"); - - ImageTestHandler* testHandler = (ImageTestHandler*) (long) inputHandlerAddress; - uint8_t *outputImage = new uint8_t[testHandler->getDebugHeight() * - testHandler->getDebugWidth() * 4]; - - const unsigned char *debugoutput = testHandler->debug_output(); - memcpy(outputImage, debugoutput, testHandler->getDebugHeight() * - testHandler->getDebugWidth() * 4); - - int outputWidth = testHandler->getDebugWidth(); - int outputHeight = testHandler->getDebugHeight(); - bool success = false; - - if (outputImage == NULL) { - ALOGV("output Image is null!"); - } else { - ALOGV("output Image is ready!"); - } - - // Create debug bitmap from output image data - if (outputImage != NULL) { - // Get method handles, create inputs to createBitmap - jclass bitmapClass = - env->FindClass("android/graphics/Bitmap"); - jclass bitmapConfigClass = - env->FindClass("android/graphics/Bitmap$Config"); - - jmethodID createBitmap = env->GetStaticMethodID( - bitmapClass, "createBitmap", - "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;"); - - jmethodID getConfig = env->GetStaticMethodID( - bitmapConfigClass, "valueOf", - "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;"); - - // Create bitmap config and bitmap - jstring bitmapConfigValue = env->NewStringUTF("ARGB_8888"); - jobject rgbaConfig = env->CallStaticObjectMethod(bitmapConfigClass, - getConfig, - bitmapConfigValue); - jobject outputBitmap = env->CallStaticObjectMethod(bitmapClass, - createBitmap, - outputWidth, - outputHeight, - rgbaConfig); - // Copy output image into it - uint8_t *outputBuffer; - int result = AndroidBitmap_lockPixels( - env, - outputBitmap, - reinterpret_cast<void**>(&outputBuffer) ); - - if (result != ANDROID_BITMAP_RESULT_SUCCESS) { - ALOGE("Unable to lock output bitmap"); - } - - memcpy(outputBuffer, outputImage, outputWidth * outputHeight * 4); - - result = AndroidBitmap_unlockPixels(env, outputBitmap); - if (result != ANDROID_BITMAP_RESULT_SUCCESS) { - ALOGE("Unable to unlock output bitmap"); - } - - // Write new Bitmap reference into mDebugOutput class member - env->SetObjectField(thiz, outputId, outputBitmap); - ALOGV("Copied to outputBitmap"); - delete [] outputImage; - env->DeleteLocalRef(outputBitmap); - env->DeleteLocalRef(rgbaConfig); - env->DeleteLocalRef(bitmapClass); - env->DeleteLocalRef(bitmapConfigClass); - } -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.h deleted file mode 100644 index e071dc1..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_CameraTests.h +++ /dev/null
@@ -1,57 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_CAMERATESTS_H -#define JNI_CAMERAANALYZER_CAMERATESTS_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_CameraTests_findNative( - JNIEnv *env, - jobject thiz, - jobject inputBitmap); - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_CameraTests_createImageTestHandler( - JNIEnv* env, - jobject thiz, - jint debugHeight, - jint debugWidth); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_CameraTests_cleanUpHandler( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_CameraTests_displayHandlerDebugOutput( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress); - - -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.cpp deleted file mode 100644 index 94e3ac2..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.cpp +++ /dev/null
@@ -1,84 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "FindColorCheckerJNI" -#include <utils/Log.h> -#include "com_android_cts_verifier_camera_analyzer_ColorCheckerTest.h" - -#include <string.h> -#include "android/bitmap.h" -#include "colorcheckertest.h" -#include "testingimage.h" - -jlong Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerTest( - JNIEnv* env, - jobject thiz, - jint debugHeight, - jint debugWidth) { - ColorCheckerTest* testHandler = new ColorCheckerTest(debugHeight, - debugWidth); - long testHandlerAddress = (long)testHandler; - return testHandlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress) { - ALOGV("JNI createColorCheckerClass starts!"); - - TestingImage *testImage = (TestingImage*) (long) inputImageAddress; - ColorCheckerTest *testHandler = (ColorCheckerTest*) - (long) inputHandlerAddress; - - testHandler->addTestingImage(testImage); -} - -jboolean Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_processColorCheckerTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - ColorCheckerTest *testHandler = (ColorCheckerTest*) - (long) inputHandlerAddress; - testHandler->processData(); - return testHandler->getSuccess(); -} - -jlong Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerRadiusAdd( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - ColorCheckerTest *testHandler = (ColorCheckerTest*) - (long) inputHandlerAddress; - long rtn = (long) testHandler->getCheckerRadiusAdd(); - return rtn; -} - -jlong Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerCenterAdd( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - ColorCheckerTest *testHandler = (ColorCheckerTest*) - (long) inputHandlerAddress; - - long rtn = (long) testHandler->getCheckerCenterAdd(); - return rtn; -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.h deleted file mode 100644 index fb87735..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ColorCheckerTest.h +++ /dev/null
@@ -1,63 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_COLORCHECKERTEST_H -#define JNI_CAMERAANALYZER_COLORCHECKERTEST_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerTest( - JNIEnv* env, - jobject thiz, - jint output_height, - jint output_width); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerClass( - JNIEnv *env, - jobject thiz, - jlong buffer_address, - jlong handler_address); - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerRadiusAdd( - JNIEnv *env, - jobject thiz, - jlong handler_address); - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerCenterAdd( - JNIEnv *env, - jobject thiz, - jlong handler_address); - -JNIEXPORT jboolean JNICALL -Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_processColorCheckerTest( - JNIEnv* env, - jobject thiz, - jlong handler_address); - -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.cpp deleted file mode 100644 index 0224639..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.cpp +++ /dev/null
@@ -1,88 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "ExposureCompensationJNI" -#include <utils/Log.h> -#include <vector> -#include <string.h> - -#include "android/bitmap.h" -#include "testingimage.h" -#include "exposurecompensationtest.h" -#include "vec2.h" - -#include "com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.h" - -jlong Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_createExposureCompensationTest( - JNIEnv* env, - jobject thiz, - jint debugHeight, - jint debugWidth) { - - ExposureCompensationTest* testHandler = - new ExposureCompensationTest(debugHeight, debugWidth); - long handlerAddress = (long)testHandler; - - return handlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_createExposureCompensationClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkerCenterAddress, - jlong checkerRadiusAddress, - jfloat exposureValue) { - - ALOGV("JNI createExposureCompensationClass starts!"); - - long imageAddress = (long)inputImageAddress; - long handlerAddress = (long)inputHandlerAddress; - - TestingImage *inputImage = (TestingImage*) imageAddress; - ExposureCompensationTest *testHandler = - (ExposureCompensationTest*) handlerAddress; - - std::vector<std::vector< Vec2f > >* checkerCenter = - (std::vector<std::vector< Vec2f > >*) (long) checkerCenterAddress; - std::vector<std::vector< float > >* checkerRadius = - (std::vector<std::vector< float > >*) (long) checkerRadiusAddress; - - const std::vector<Vec3f>* checkerValue = - inputImage->getColorChecker(3, 4, 0, 6, - checkerCenter, checkerRadius); - testHandler->addDataToList((float) exposureValue, checkerValue); - delete inputImage; - delete checkerValue; -} - -jstring Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_processExposureCompensationTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - - long handlerAddress = (long) inputHandlerAddress; - ExposureCompensationTest *testHandler = - (ExposureCompensationTest*) handlerAddress; - - testHandler->processData(); - - const char* nativeDebugText = testHandler->getDebugText(); - ALOGV("%s", nativeDebugText); - return env->NewStringUTF(nativeDebugText); -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.h deleted file mode 100644 index 8e8761d..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_ExposureCompensationTest.h +++ /dev/null
@@ -1,54 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_EXPOSURECOMPENSATIONTEST_H -#define JNI_CAMERAANALYZER_EXPOSURECOMPENSATIONTEST_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_createExposureCompensationTest( - JNIEnv* env, - jobject thiz, - jint debugHeight, - jint debugWidth); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_createExposureCompensationClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkerCenterAddress, - jlong checkerRadiusAddress, - jfloat exposureValue); - - -JNIEXPORT jstring JNICALL -Java_com_android_cts_verifier_camera_analyzer_ExposureCompensationTest_processExposureCompensationTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress); -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.cpp deleted file mode 100644 index faebe21..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.cpp +++ /dev/null
@@ -1,142 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "MeteringJNI" -#include <utils/Log.h> -#include "com_android_cts_verifier_camera_analyzer_MeteringTest.h" - -#include <vector> -#include <string> -#include <string.h> -#include <math.h> - -#include "testingimage.h" -#include "meteringtest.h" -#include "vec2.h" -#include "android/bitmap.h" - -jlong Java_com_android_cts_verifier_camera_analyzer_MeteringTest_createMeteringTest( - JNIEnv* env, - jobject thiz) { - - MeteringTest* testHandler = new MeteringTest(); - long handlerAddress = (long)testHandler; - return handlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_MeteringTest_createMeteringClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress){ - - ALOGV("JNI createMeteringClass starts!"); - long imageAddress = (long)inputImageAddress; - long handlerAddress = (long)inputHandlerAddress; - - TestingImage *image = (TestingImage*) imageAddress; - MeteringTest *testHandler = (MeteringTest*) handlerAddress; - - std::vector<std::vector< Vec2f > >* checkerCenter = - (std::vector<std::vector< Vec2f > >*) (long) checkercenterAddress; - std::vector<std::vector< float > >* checkerRadius = - (std::vector<std::vector< float > >*) (long) checkerradiusAddress; - ALOGV("Classes recovered"); - - testHandler->addDataToList(image->getColorChecker(3, 4, 0, 6, - checkerCenter, - checkerRadius)); - - delete image; -} - -void Java_com_android_cts_verifier_camera_analyzer_MeteringTest_processMeteringTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress, - jbooleanArray tempArray) { - - ALOGV("Processing Auto Lock data!"); - - long handlerAddress = (long) inputHandlerAddress; - MeteringTest *testHandler = (MeteringTest*) handlerAddress; - - testHandler->processData(); - - const std::vector<bool>* nativeComparisonResults = - testHandler->getComparisonResults(); - jboolean jComparisonResults[nativeComparisonResults->size()]; - - for (int i = 0; i < nativeComparisonResults->size(); ++i) { - jComparisonResults[i] = (jboolean) (*nativeComparisonResults)[i]; - } - - env->SetBooleanArrayRegion(tempArray, - 0, nativeComparisonResults->size(), - jComparisonResults); - testHandler->clearData(); -} - -// Find the gray checker borders from the native array of checker center and -// radius. Convert the coordinate to the coordinates accepted by Android -// Camera.Area type, which defines the top left corner to (-1000, -1000) and -// bottom right corner to (1000, 1000). -void Java_com_android_cts_verifier_camera_analyzer_MeteringTest_findGreyCoordinates( - JNIEnv* env, - jobject thiz, - jintArray greyCoordinates, - jlong checkercenterAddress, - jlong checkerradiusAddress){ - - ALOGV("Start finding grey coordinates"); - - std::vector<std::vector< Vec2f > >* checkerCenter = - (std::vector<std::vector< Vec2f > >*) (long) checkercenterAddress; - std::vector<std::vector< float > >* checkerRadius = - (std::vector<std::vector< float > >*) (long) checkerradiusAddress; - - ALOGV("Checker recovered!"); - int nativeGreyCoordinates[24]; - - for (int i = 0; i < 6; ++i) { - float radius = sqrt((*checkerRadius)[3][i]); - nativeGreyCoordinates[i * 4] = static_cast<int>( - ((*checkerCenter)[3][i].y() - radius) - / 160.0 * 2000.0 - 1000.0); - nativeGreyCoordinates[i * 4 + 1] = static_cast<int>( - ((*checkerCenter)[3][i].x() - radius) - / 120.0 * 2000.0 - 1000.0); - nativeGreyCoordinates[i * 4 + 2] = static_cast<int>( - ((*checkerCenter)[3][i].y() + radius) - / 160.0 * 2000.0 - 1000.0); - nativeGreyCoordinates[i * 4 + 3] = static_cast<int>( - ((*checkerCenter)[3][i].x() + radius) - / 120.0 * 2000.0 - 1000.0); - - ALOGV("checker is bounded by %f, %f, %f", - (*checkerCenter)[3][i].x(), (*checkerCenter)[3][i].y(), radius); - - ALOGV("Square is bounded by %d, %d, %d, %d", - nativeGreyCoordinates[i * 4], nativeGreyCoordinates[i * 4 + 1], - nativeGreyCoordinates[i * 4 + 2], - nativeGreyCoordinates[i * 4 + 3]); - } - - env->SetIntArrayRegion(greyCoordinates, 0, 24, nativeGreyCoordinates); -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.h deleted file mode 100644 index ecc1b96..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_MeteringTest.h +++ /dev/null
@@ -1,60 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_METERINGTEST_H -#define JNI_CAMERAANALYZER_METERINGTEST_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_MeteringTest_createMeteringTest( - JNIEnv* env, - jobject thiz); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_MeteringTest_createMeteringClass( - JNIEnv *env, - jobject thiz, - jlong inputAddress, - jlong handlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_MeteringTest_processMeteringTest( - JNIEnv* env, - jobject thiz, - jlong handlerAddress, - jbooleanArray tempArray); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_MeteringTest_findGreyCoordinates( - JNIEnv* env, - jobject thiz, - jintArray greyCoordinates, - jlong checkercenterAddress, - jlong checkerradiusAddress); - -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.cpp b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.cpp deleted file mode 100644 index bce0fca..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.cpp +++ /dev/null
@@ -1,90 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "WhiteBalanceJNI" -#include <utils/Log.h> -#include "com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.h" - -#include <vector> -#include <string> -#include <string.h> - -#include "testingimage.h" -#include "whitebalancetest.h" -#include "vec2.h" -#include "android/bitmap.h" - -jlong Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_createWhiteBalanceTest( - JNIEnv* env, - jobject thiz) { - - WhiteBalanceTest* testHandler = new WhiteBalanceTest(); - long handlerAddress = (long)testHandler; - return handlerAddress; -} - -void Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_createWhiteBalanceClass( - JNIEnv* env, - jobject thiz, - jlong inputImageAddress, - jlong inputHandlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress, - jstring whiteBalance){ - - ALOGV("JNI createWhiteBalanceClass starts!"); - long imageAddress = (long)inputImageAddress; - long handlerAddress = (long)inputHandlerAddress; - - TestingImage *image = (TestingImage*) imageAddress; - WhiteBalanceTest *testHandler = (WhiteBalanceTest*) handlerAddress; - - std::vector<std::vector< Vec2f > >* checkerCenter = - (std::vector<std::vector< Vec2f > >*) (long) checkercenterAddress; - std::vector<std::vector< float > >* checkerRadius = - (std::vector<std::vector< float > >*) (long) checkerradiusAddress; - ALOGV("Classes recovered"); - - jboolean isCopy; - const char* stringWhiteBalance = - env->GetStringUTFChars(whiteBalance, &isCopy); - ALOGV("White Balance is %s", stringWhiteBalance); - - // Adds the gray checker's RGB values to the test handler. - testHandler->addDataToList(stringWhiteBalance, - image->getColorChecker(3, 4, 0, 6, - checkerCenter, - checkerRadius)); - - env->ReleaseStringUTFChars(whiteBalance, stringWhiteBalance); - delete image; -} - -jint Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_processWhiteBalanceTest( - JNIEnv* env, - jobject thiz, - jlong inputHandlerAddress) { - ALOGV("Processing white balance test"); - - long handlerAddress = (long) inputHandlerAddress; - WhiteBalanceTest *testHandler = (WhiteBalanceTest*) handlerAddress; - - testHandler->processData(); - - ALOGV("CCT is %d", testHandler->getCorrelatedColorTemp()); - return testHandler->getCorrelatedColorTemp(); -}
diff --git a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.h b/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.h deleted file mode 100644 index 88cf52e..0000000 --- a/apps/CtsVerifier/jni/cameraanalyzer/com_android_cts_verifier_camera_analyzer_WhiteBalanceTest.h +++ /dev/null
@@ -1,53 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef JNI_CAMERAANALYZER_WHITEBALANCETEST_H -#define JNI_CAMERAANALYZER_WHITEBALANCETEST_H - -#include <jni.h> -#include <stdio.h> - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jlong JNICALL -Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_createWhiteBalanceTest( - JNIEnv* env, - jobject thiz); - -JNIEXPORT void JNICALL -Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_createWhiteBalanceClass( - JNIEnv *env, - jobject thiz, - jlong inputAddress, - jlong handlerAddress, - jlong checkercenterAddress, - jlong checkerradiusAddress, - jstring whiteBalance); - -JNIEXPORT jint JNICALL -Java_com_android_cts_verifier_camera_analyzer_WhiteBalanceTest_processWhiteBalanceTest( - JNIEnv* env, - jobject thiz, - jlong handlerAddress); - - -#ifdef __cplusplus -} -#endif - -#endif
diff --git a/apps/CtsVerifier/jni/verifier/Android.mk b/apps/CtsVerifier/jni/verifier/Android.mk index da4687d..4840e62 100644 --- a/apps/CtsVerifier/jni/verifier/Android.mk +++ b/apps/CtsVerifier/jni/verifier/Android.mk
@@ -25,8 +25,11 @@ LOCAL_SRC_FILES := \ CtsVerifierJniOnLoad.cpp \ - com_android_cts_verifier_os_FileUtils.cpp + com_android_cts_verifier_camera_StatsImage.cpp \ + com_android_cts_verifier_os_FileUtils.cpp LOCAL_C_INCLUDES := $(JNI_H_INCLUDE) +LOCAL_SHARED_LIBRARIES := liblog + include $(BUILD_SHARED_LIBRARY)
diff --git a/apps/CtsVerifier/jni/verifier/CtsVerifierJniOnLoad.cpp b/apps/CtsVerifier/jni/verifier/CtsVerifierJniOnLoad.cpp index 81e5690..399275b 100644 --- a/apps/CtsVerifier/jni/verifier/CtsVerifierJniOnLoad.cpp +++ b/apps/CtsVerifier/jni/verifier/CtsVerifierJniOnLoad.cpp
@@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,6 +18,7 @@ #include <stdio.h> extern int register_com_android_cts_verifier_os_FileUtils(JNIEnv*); +extern int register_com_android_cts_verifier_camera_its_StatsImage(JNIEnv*); jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; @@ -30,5 +31,9 @@ return JNI_ERR; } + if (register_com_android_cts_verifier_camera_its_StatsImage(env)) { + return JNI_ERR; + } + return JNI_VERSION_1_4; }
diff --git a/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_camera_StatsImage.cpp b/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_camera_StatsImage.cpp new file mode 100644 index 0000000..16dff85 --- /dev/null +++ b/apps/CtsVerifier/jni/verifier/com_android_cts_verifier_camera_StatsImage.cpp
@@ -0,0 +1,94 @@ +/* + * Copyright (C) 2015 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. + */ + +#define LOG_TAG "ITS-StatsImage-JNI" +// #define LOG_NDEBUG 0 +#include <android/log.h> +#include <utils/Log.h> + +#include <jni.h> +#include <stdio.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <inttypes.h> +#include <string.h> + +jfloatArray com_android_cts_verifier_camera_its_computeStatsImage(JNIEnv* env, jobject thiz, + jbyteArray img, jint width, jint height, jint gridWidth, jint gridHeight) +{ + int bufSize = (int)(env->GetArrayLength(img)); + unsigned char *buf = (unsigned char*)env->GetByteArrayElements(img, /*is_copy*/NULL); + + // Size of the raw image. + const int w = width; + const int h = height; + // Size of each grid cell. + const int gw = gridWidth; + const int gh = gridHeight; + // Number of grid cells (rounding down to full cells only at right+bottom edges). + const int ngx = w / gw; + const int ngy = h / gh; + + float *mean = new float[ngy*ngx*4]; + float *var = new float[ngy*ngx*4]; + for (int gy = 0; gy < ngy; gy++) { + for (int gx = 0; gx < ngx; gx++) { + float sum[4] = {0}; + float sumSq[4] = {0}; + int count[4] = {0}; + for (int y = gy*gh; y < (gy+1)*gh; y++) { + int chnOffset = (y & 0x1) * 2; + unsigned char *pbuf = buf + 2*y*w + 2*gx*gw; + for (int x = gx*gw; x < (gx+1)*gw; x++) { + // input is RAW16 + int byte0 = *pbuf++; + int byte1 = *pbuf++; + int pixelValue = (byte1 << 8) | byte0; + int ch = chnOffset + (x & 1); + sum[ch] += pixelValue; + sumSq[ch] += pixelValue * pixelValue; + count[ch] += 1; + } + } + for (int ch = 0; ch < 4; ch++) { + float m = (float)sum[ch] / count[ch]; + float mSq = (float)sumSq[ch] / count[ch]; + mean[gy*ngx*4 + gx*4 + ch] = m; + var[gy*ngx*4 + gx*4 + ch] = mSq - m*m; + } + } + } + + jfloatArray ret = env->NewFloatArray(ngx*ngy*4*2); + env->SetFloatArrayRegion(ret, 0, ngx*ngy*4, (float*)mean); + env->SetFloatArrayRegion(ret, ngx*ngy*4, ngx*ngy*4, (float*)var); + delete [] mean; + delete [] var; + return ret; +} + +static JNINativeMethod gMethods[] = { + { "computeStatsImage", "([BIIII)[F", + (void *) com_android_cts_verifier_camera_its_computeStatsImage }, +}; + +int register_com_android_cts_verifier_camera_its_StatsImage(JNIEnv* env) +{ + jclass clazz = env->FindClass("com/android/cts/verifier/camera/its/StatsImage"); + + return env->RegisterNatives(clazz, gMethods, + sizeof(gMethods) / sizeof(JNINativeMethod)); +}
diff --git a/apps/CtsVerifier/lib/Android.mk b/apps/CtsVerifier/lib/Android.mk deleted file mode 100644 index 56a3fa8..0000000 --- a/apps/CtsVerifier/lib/Android.mk +++ /dev/null
@@ -1,17 +0,0 @@ -# -# Copyright (C) 2011 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. -# - -include $(call all-subdir-makefiles)
diff --git a/apps/CtsVerifier/lib/colorchecker/Android.mk b/apps/CtsVerifier/lib/colorchecker/Android.mk deleted file mode 100644 index 48f1356..0000000 --- a/apps/CtsVerifier/lib/colorchecker/Android.mk +++ /dev/null
@@ -1,43 +0,0 @@ -# Copyright (C) 2011 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. -# - -LOCAL_PATH := $(call my-dir) - -##################### -# Build image analysis library - -include $(CLEAR_VARS) -LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk - -LOCAL_MODULE_TAGS := optional -LOCAL_MODULE := libcolorchecker - -LOCAL_SRC_FILES += testingimage.cpp \ - vec3.cpp \ - vec2.cpp \ - imagetesthandler.cpp \ - colorcheckertest.cpp \ - exposurecompensationtest.cpp \ - autolocktest.cpp \ - meteringtest.cpp \ - whitebalancetest.cpp - -LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../include/colorchecker -LOCAL_CXX_STL := libc++ -LOCAL_SHARED_LIBRARIES := \ - libcutils \ - libutils \ - -include $(BUILD_STATIC_LIBRARY)
diff --git a/apps/CtsVerifier/lib/colorchecker/autolocktest.cpp b/apps/CtsVerifier/lib/colorchecker/autolocktest.cpp deleted file mode 100644 index 6bfa922..0000000 --- a/apps/CtsVerifier/lib/colorchecker/autolocktest.cpp +++ /dev/null
@@ -1,101 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "AutoLockTest" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <string> - -#include "vec2.h" -#include "vec3.h" -#include "autolocktest.h" - -const float kOverExposure = 230.f; -const float kEqThreshold = 0.05f; -// Processes the color checker values and compare the two values from -// the same individual test. -void AutoLockTest::processData() { - ALOGV("Start Processing Auto Lock Test Data!"); - - int numTests = mCheckerColors.size() / 2; - mNumPatches = 0; - - if (numTests > 0) { - mNumPatches = mCheckerColors[0].size(); - } - - for (int i = 0; i < numTests; ++i) { - mComparisonResults.push_back( - IsBrighterThan((&mCheckerColors[i * 2]), - (&mCheckerColors[i * 2 + 1]))); - mComparisonResults.push_back( - IsEquivalentTo((&mCheckerColors[i * 2]), - (&mCheckerColors[i * 2 + 1]))); - } -} - -// Compares whether one array of gray color patches is brighter than -// another one. -bool AutoLockTest::IsBrighterThan( - const std::vector<Vec3f>* colorCheckers1, - const std::vector<Vec3f>* colorCheckers2) const { - float meanRatio = 0.f; - int meanNumCount = 0; - - for (int i = 0; i < mNumPatches; ++i) { - float luminance1 = (*colorCheckers1)[i].convertToLuminance(); - float luminance2 = (*colorCheckers2)[i].convertToLuminance(); - - // Consider a 5% raise as a considerably large increase. - if ((luminance1 < kOverExposure) && (luminance2 != 0.f)) { - meanRatio += luminance1 / luminance2; - ++meanNumCount; - } - } - meanRatio = meanRatio / meanNumCount; - - return (meanRatio > 1 + kEqThreshold); -} - -// Compares whether one array of gray color patches is within a small range -// of the other one to be considered equivalent. -bool AutoLockTest::IsEquivalentTo( - const std::vector<Vec3f>* colorCheckers1, - const std::vector<Vec3f>* colorCheckers2) const { - float meanRatio = 0.f; - int meanNumCount = 0; - - for (int i = 0; i < mNumPatches; ++i) { - float luminance1 = (*colorCheckers1)[i].convertToLuminance(); - float luminance2 = (*colorCheckers2)[i].convertToLuminance(); - ALOGV("Luma_1 and Luma_2 is %f, %f", luminance1, luminance2); - - if ((luminance1 < kOverExposure) && (luminance2 < kOverExposure)) { - meanRatio += luminance2 / luminance1; - ++meanNumCount; - } - } - meanRatio = meanRatio / meanNumCount; - - return ((meanRatio >= 1 - kEqThreshold) && (meanRatio <= 1 + kEqThreshold)); -} - -void AutoLockTest::clearData() { - mCheckerColors.clear(); - mComparisonResults.clear(); -}
diff --git a/apps/CtsVerifier/lib/colorchecker/colorcheckertest.cpp b/apps/CtsVerifier/lib/colorchecker/colorcheckertest.cpp deleted file mode 100644 index ef7d2c6..0000000 --- a/apps/CtsVerifier/lib/colorchecker/colorcheckertest.cpp +++ /dev/null
@@ -1,979 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "ColorCheckerTest" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <string> - -#include "vec2.h" -#include "vec3.h" -#include "colorcheckertest.h" - -const float GAMMA_CORRECTION = 2.2f; -const float COLOR_ERROR_THRESHOLD = 200.f; -ColorCheckerTest::~ColorCheckerTest() { - ALOGV("Deleting color checker test handler"); - - if (mImage != NULL) { - delete mImage; - } - ALOGV("Image deleted"); - - int numHorizontalLines = mCandidateColors.size(); - int numVerticalLines = mCandidateColors[0].size(); - - for (int i = 0; i < numHorizontalLines; ++i) { - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - delete mCandidateColors[i][j]; - } - if (mCandidatePositions[i][j] != NULL) { - delete mCandidatePositions[i][j]; - } - } - } - ALOGV("Candidates deleted!"); - - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 6; ++j) { - if (mMatchPositions[i][j] != NULL) { - delete mMatchPositions[i][j]; - } - if (mReferenceColors[i][j] != NULL) { - delete mReferenceColors[i][j]; - } - if (mMatchColors[i][j] != NULL) { - delete mMatchColors[i][j]; - } - } - } -} - -// Adds a new image to the test handler. -void ColorCheckerTest::addTestingImage(TestingImage* inputImage) { - if (mImage != NULL) { - delete mImage; - } - mImage = NULL; - ALOGV("Original image deleted"); - mImage = inputImage; - - if ((mImage->getHeight() == getDebugHeight()) && - (mImage->getWidth() == getDebugWidth())) { - copyDebugImage(getDebugHeight(), getDebugWidth(), mImage->getImage()); - } -} - -void ColorCheckerTest::processData() { - mSuccess = false; - initializeRefColor(); - edgeDetection(); -} - -void ColorCheckerTest::initializeRefColor() { - mReferenceColors.resize(4, std::vector<Vec3i*>(6, NULL)); - mMatchPositions.resize(4, std::vector<Vec2f*>(6, NULL)); - mMatchColors.resize(4, std::vector<Vec3f*>(6, NULL)); - mMatchRadius.resize(4, std::vector<float>(6, 0.f)); - - mReferenceColors[0][0]= new Vec3i(115, 82, 68); - mReferenceColors[0][1]= new Vec3i(194, 150, 130); - mReferenceColors[0][2]= new Vec3i(98, 122, 157); - mReferenceColors[0][3]= new Vec3i(87, 108, 67); - mReferenceColors[0][4]= new Vec3i(133, 128, 177); - mReferenceColors[0][5]= new Vec3i(103, 189, 170); - mReferenceColors[1][0]= new Vec3i(214, 126, 44); - mReferenceColors[1][1]= new Vec3i(80, 91, 166); - mReferenceColors[1][2]= new Vec3i(193, 90, 99); - mReferenceColors[1][3]= new Vec3i(94, 60, 108); - mReferenceColors[1][4]= new Vec3i(157, 188, 64); - mReferenceColors[1][5]= new Vec3i(224, 163, 46); - mReferenceColors[2][0]= new Vec3i(56, 61, 150); - mReferenceColors[2][1]= new Vec3i(70, 148, 73); - mReferenceColors[2][2]= new Vec3i(175, 54, 60); - mReferenceColors[2][3]= new Vec3i(231, 199, 31); - mReferenceColors[2][4]= new Vec3i(187, 86, 149); - mReferenceColors[2][5]= new Vec3i(8, 133, 161); - mReferenceColors[3][0]= new Vec3i(243, 243, 242); - mReferenceColors[3][1]= new Vec3i(200, 200, 200); - mReferenceColors[3][2]= new Vec3i(160, 160, 160); - mReferenceColors[3][3]= new Vec3i(122, 122, 121); - mReferenceColors[3][4]= new Vec3i(85, 85, 85); - mReferenceColors[3][5]= new Vec3i(52, 52, 52); -} - -void ColorCheckerTest::edgeDetection() { - int width = mImage->getWidth(); - int height = mImage->getHeight(); - - bool* edgeMap = new bool[height * width]; - unsigned char* grayImage = new unsigned char[height * width]; - - // If the image is a color image and can be converted to a luminance layer - if (mImage->rgbToGrayScale(grayImage)) { - float* gradientMap = new float[height * width * 2]; - - // Computes the gradient image on the luminance layer. - computeGradient(grayImage, gradientMap); - - float* gradientMagnitude = new float[height * width]; - int* gradientDirectionInt = new int[height * width]; - float* gradientDirection = new float[height * width]; - - // Computes the absolute gradient of the image without padding. - for (int i = 1; i < height - 1; ++i) { - for (int j = 1; j < width - 1; ++j) { - gradientMagnitude[i * width + j] = - sqrt(gradientMap[(i * width + j) * 2] * - gradientMap[(i * width + j) * 2] + - gradientMap[(i * width + j ) * 2 + 1] * - gradientMap[(i * width + j ) * 2 + 1]); - - // Computes the gradient direction of the image. - if (gradientMap[(i * width + j) * 2] == 0 ) { - // If the vertical gradient is 0, the edge is horizontal - // Mark the gradient direction as 90 degrees. - gradientDirectionInt[i * width + j] = 2; - gradientDirection[i * width + j] = 90.0f; - } else { - // Otherwise the atan operation is valid and can decide - // the gradient direction of the edge. - float gradient = atan(gradientMap[(i * width + j) * 2 + 1] - / gradientMap[(i * width + j) * 2]) - / (M_PI / 4); - - gradientDirection[i * width + j] = gradient * 45.0f; - - // Maps the gradient direction to 4 major directions with - // 0 mapped to up and 2 mapped to right. - if (gradient - floor(gradient) > 0.5) { - gradientDirectionInt[i * width + j] = - (static_cast<int>(ceil(gradient)) + 4) % 4; - } else { - gradientDirectionInt[i * width + j] = - (static_cast<int>(floor(gradient)) + 4) % 4; - } - } - } - } - - // Compute a boolean map to show whether a pixel is on the edge. - for (int i = 1; i < height - 1; ++i) { - for (int j = 1; j < width - 1; ++j) { - edgeMap[i * width + j] = false; - - switch (gradientDirectionInt[i * width + j]) { - case 0: - // If the gradient points rightwards, the pixel is - // on an edge if it has a larger absolute gradient than - // pixels on its left and right sides. - if ((gradientMagnitude[i * width + j] >= - gradientMagnitude[i * width + j + 1]) && - (gradientMagnitude[i * width + j] >= - gradientMagnitude[i * width + j - 1])) { - edgeMap[i * width + j] = true; - } - break; - case 1: - // If the gradient points right-downwards, the pixel is - // on an edge if it has a larger absolute gradient than - // pixels on its upper left and bottom right sides. - if ((gradientMagnitude[i * width + j] >= - gradientMagnitude[(i + 1) * width + j + 1]) && - (gradientMagnitude[i * width + j] >= - gradientMagnitude[(i - 1) * width + j - 1])) { - edgeMap[i * width + j] = true; - } - break; - case 2: - // If the gradient points upwards, the pixel is - // on an edge if it has a larger absolute gradient than - // pixels on its up and down sides. - if ((gradientMagnitude[i * width + j] >= - gradientMagnitude[(i + 1) * width + j]) && - (gradientMagnitude[i * width + j] >= - gradientMagnitude[(i - 1) * width + j])) { - edgeMap[i * width + j] = true; - } - break; - case 3: - // If the gradient points right-upwards, the pixel is - // on an edge if it has a larger absolute gradient than - // pixels on its bottom left and upper right sides. - if ((gradientMagnitude[i * width + j] >= - gradientMagnitude[(i - 1) * width + j + 1]) && - (gradientMagnitude[i * width + j] >= - gradientMagnitude[(i + 1) * width + j - 1])) { - edgeMap[i * width + j] = true; - } - } - - } - } - - houghLineDetection(edgeMap, gradientMagnitude, gradientDirection); - - // Cleans up - delete[] gradientMap; - delete[] gradientDirectionInt; - delete[] gradientMagnitude; - delete[] gradientDirection; - - } else { - ALOGE("Not a color image!"); - } - - delete[] edgeMap; - delete[] grayImage; -} - -// Runs the hough voting algorithm to find the grid of the color checker -// with the edge map, gradient direction and gradient magnitude as inputs. -void ColorCheckerTest::houghLineDetection(bool* edgeMap, - float* gradientMagnitude, - float* gradientDirection) { - // Constructs a graph for Hough voting. The vertical axis counts the vote - // for a certain angle. The horizontal axis counts the vote for the distance - // of a line from the origin of the image. - int houghHeight = 180; - int houghWidth = 200; - int houghCounts[houghHeight][houghWidth]; - int houghSum[houghHeight][houghWidth]; - - int** houghVote; - houghVote = new int*[180]; - for (int i = 0; i < 180; ++i) { - houghVote[i] = new int[200]; - } - - for (int i = 0; i < houghHeight; ++i) { - for (int j = 0; j < houghWidth; ++j) { - houghCounts[i][j] = 0; - houghVote[i][j] = 0; - houghSum[i][j] = 0; - } - } - - // Vectors to record lines in two orthogonal directions. - // Each line is represented by its direction and its distance to the origin. - std::vector<std::vector<int> > verticalLines; - std::vector<std::vector<int> > horizontalLines; - float radius; - int height = mImage->getHeight(); - int width = mImage->getWidth(); - - // Processes the signicant edge pixels and cast vote for the corresponding - // edge passing this pixel. - for (int i = 1; i < height - 1; ++i) { - for (int j = 1; j < width - 1; ++j) { - // Sets threashold for the gradient magnitude to discount noises - if (edgeMap[i * width + j] && - (gradientMagnitude[i * width + j] > 15)) { - int shiftedAngle; - - // Shifts angles for 45 degrees so the vertical and horizontal - // direction is mapped to 45 and 135 degrees to avoid padding. - // This uses the assumption that the color checker is placed - // roughly parallel to the image boarders. So that the edges - // at the angle of 45 will be rare. - shiftedAngle = (static_cast<int>( - -gradientDirection[i * width + j]) + 225 % 180); - float shiftedAngleRad = static_cast<float>(shiftedAngle) - * M_PI / 180.0f; - - // Computes the distance of the line from the origin. - float a, b; - a = static_cast<float>(i - j) / sqrt(2.0f); - b = static_cast<float>(i + j) / sqrt(2.0f); - radius = a * sin(shiftedAngleRad) - b * cos(shiftedAngleRad); - - // Adds one vote for the line. The line's angle is shifted by - // 45 degrees to avoid avoid padding for the vertical lines, - // which is more common than diagonal lines. The line's - // distance is mapped to [0, 200] from [-200, 200]. - ++houghCounts[shiftedAngle][static_cast<int>((radius / 2.0f) + - 100.0f)]; - - drawPoint(i, j, Vec3i(255, 255, 255)); - } - } - } - - int houghAngleSum[houghHeight]; - int primaryVerticalAngle, primaryHorizontalAngle; - int max1 = 0; - int max2 = 0; - - // Looking for the two primary angles of the lines. - for (int i = 5; i < houghHeight - 5; ++i) { - houghAngleSum[i] = 0; - for (int j = 0; j < houghWidth; ++j) { - for (int l = -5; l <= 5; ++l) { - houghSum[i][j] += houghCounts[i + l][j]; - } - houghAngleSum[i] += houghSum[i][j]; - } - - if ((i < houghHeight / 2) && (houghAngleSum[i] > max1)) { - max1 = houghAngleSum[i]; - primaryVerticalAngle = i; - } else if ((i > houghHeight / 2) && (houghAngleSum[i] > max2)) { - max2 = houghAngleSum[i]; - primaryHorizontalAngle = i; - } - } - - ALOGV("Primary angles are %d, %d", - primaryVerticalAngle, primaryHorizontalAngle); - - int angle; - - // For each primary angle, look for the highest voted lines. - for (int k = 0; k < 2; ++k) { - if (k == 0) { - angle = primaryVerticalAngle; - } else { - angle = primaryHorizontalAngle; - } - - std::vector<int> line(2); - for (int j = 2; j < houghWidth - 2; ++j) { - houghVote[angle][j] = houghSum[angle][j]; - houghSum[angle][j] = 0; - } - - // For each radius, average the vote with nearby ones. - for (int j = 2; j < houghWidth - 2; ++j) { - for (int m = -2; m <= 2; ++m) { - houghSum[angle][j] += houghVote[angle][j + m]; - } - } - - bool isCandidate[houghWidth]; - - // Find whether a lines is a candidate by rejecting the ones that have - // lower vote than others in the neighborhood. - for (int j = 2; j < houghWidth - 2; ++j) { - isCandidate[j] = true; - for (int m = -2; ((isCandidate[j]) && (m <= 2)); ++m) { - if ((houghSum[angle][j] < 20) || - (houghSum[angle][j] < houghSum[angle][j + m])) { - isCandidate[j] = false; - } - } - } - - int iter1 = 0; - int iter2 = 0; - int count = 0; - - // Finds the lines that are not too close to each other and add to the - // detected lines. - while (iter2 < houghWidth) { - while ((!isCandidate[iter2]) && (iter2 < houghWidth)) { - ++iter2; - } - if ((isCandidate[iter2]) && (iter2 - iter1 < 5)) { - iter1 = (iter2 + iter1) / 2; - ++iter2; - } else { - line[0] = angle; - line[1] = (iter1 - 100) * 2; - if (iter1 != 0) { - if (k == 0) { - verticalLines.push_back(line); - Vec3i color(verticalLines.size() * 20, 0, 0); - drawLine(line[0], line[1], color); - } else { - horizontalLines.push_back(line); - Vec3i color(0, horizontalLines.size() * 20, 0); - drawLine(line[0], line[1], color); - } - } - iter1 = iter2; - ++iter2; - ALOGV("pushing back line %d %d", line[0], line[1]); - } - } - } - - ALOGV("Numbers of lines in each direction is %d, %d", - verticalLines.size(), horizontalLines.size()); - - for (int i = 0; i < 180; ++i) { - delete[] houghVote[i]; - } - delete[] houghVote; - - findCheckerBoards(verticalLines, horizontalLines); -} - -// Computes the gradient in both x and y direction of a layer -void ColorCheckerTest::computeGradient(unsigned char* layer, - float* gradientMap) { - int width = mImage->getWidth(); - int height = mImage->getHeight(); - - // Computes the gradient in the whole image except the image boarders. - for (int i = 1; i < height - 1; ++i) { - for (int j = 1; j < width - 1; ++j) { - gradientMap[(i * width + j) * 2] = - 0.5f * (layer[i * width + j + 1] - - layer[i * width + j - 1]); - gradientMap[(i * width + j) * 2 + 1] = - 0.5f * (layer[(i + 1) * width + j] - - layer[(i - 1) * width + j]); - } - } -} - -// Tries to find the checker boards with the highest voted lines -void ColorCheckerTest::findCheckerBoards( - std::vector<std::vector<int> > verticalLines, - std::vector<std::vector<int> > horizontalLines) { - ALOGV("Start looking for Color checker"); - - int numHorizontalLines = mCandidateColors.size(); - int numVerticalLines; - if (numHorizontalLines > 0) { - numVerticalLines = mCandidateColors[0].size(); - for (int i = 0; i < numHorizontalLines; ++i) { - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - delete mCandidateColors[i][j]; - } - if (mCandidatePositions[i][j] != NULL) { - delete mCandidatePositions[i][j]; - } - } - mCandidateColors[i].clear(); - mCandidatePositions[i].clear(); - } - } - mCandidateColors.clear(); - mCandidatePositions.clear(); - - ALOGV("Candidates deleted!"); - - numVerticalLines = verticalLines.size(); - numHorizontalLines = horizontalLines.size(); - Vec2f pointUpperLeft; - Vec2f pointBottomRight; - - mCandidateColors.resize(numHorizontalLines - 1); - mCandidatePositions.resize(numHorizontalLines - 1); - - for (int i = numVerticalLines - 1; i >= 1; --i) { - for (int j = 0; j < numHorizontalLines - 1; ++j) { - // Finds the upper left and bottom right corner of each rectangle - // formed by two neighboring highest voted lines. - pointUpperLeft = findCrossing(verticalLines[i], horizontalLines[j]); - pointBottomRight = findCrossing(verticalLines[i - 1], - horizontalLines[j + 1]); - - Vec3i* color = new Vec3i(); - Vec2f* pointCenter = new Vec2f(); - // Verifies if they are separated by a reasonable distance. - if (verifyPointPair(pointUpperLeft, pointBottomRight, - pointCenter, color)) { - mCandidatePositions[j].push_back(pointCenter); - mCandidateColors[j].push_back(color); - ALOGV("Color at (%d, %d) is (%d, %d, %d)", j, i,color->r(), color->g(), color->b()); - - } else { - mCandidatePositions[j].push_back(NULL); - mCandidateColors[j].push_back(NULL); - delete color; - delete pointCenter; - } - } - } - - ALOGV("Candidates Number (%d, %d)", mCandidateColors.size(), mCandidateColors[0].size()); - // Verifies whether the current line candidates form a valid color checker. - verifyColorGrid(); -} - -// Returns the corssing point of two lines given the lines. -Vec2f ColorCheckerTest::findCrossing(std::vector<int> line1, - std::vector<int> line2) { - Vec2f crossingPoint; - float r1 = static_cast<float>(line1[1]); - float r2 = static_cast<float>(line2[1]); - float ang1, ang2; - float y1, y2; - - ang1 = static_cast<float>(line1[0]) / 180.0f * M_PI; - ang2 = static_cast<float>(line2[0]) / 180.0f * M_PI; - - float x, y; - x = (r1 * cos(ang2) - r2 * cos(ang1)) / sin(ang1 - ang2); - y = (r1 * sin(ang2) - r2 * sin(ang1)) / sin(ang1 - ang2); - - crossingPoint.set((x + y) / sqrt(2.0), (y - x) / sqrt(2.0)); - - //ALOGV("Crosspoint at (%f, %f)", crossingPoint.x(), crossingPoint.y()); - return crossingPoint; -} - -// Verifies whether two opposite corners on a quadrilateral actually can be -// the two corners of a color checker. -bool ColorCheckerTest::verifyPointPair(Vec2f pointUpperLeft, - Vec2f pointBottomRight, - Vec2f* pointCenter, - Vec3i* color) { - bool success = true; - - /** 5 and 30 are the threshold tuned for resolution 640*480*/ - if ((pointUpperLeft.x() < 0) || - (pointUpperLeft.x() >= mImage->getHeight()) || - (pointUpperLeft.y() < 0) || - (pointUpperLeft.y() >= mImage->getWidth()) || - (pointBottomRight.x() < 0) || - (pointBottomRight.x() >= mImage->getHeight()) || - (pointBottomRight.y() < 0) || - (pointBottomRight.y() >= mImage->getWidth()) || - (std::abs(pointUpperLeft.x() - pointBottomRight.x()) <= 5) || - (std::abs(pointUpperLeft.y() - pointBottomRight.y()) <= 5) || - (std::abs(pointUpperLeft.x() - pointBottomRight.x()) >= 30) || - (std::abs(pointUpperLeft.y() - pointBottomRight.y()) >= 30)) { - - // If any of the quadrilateral corners are out of the image or if - // the distance between them are too large or too big, the quadrilateral - // could not be one of the checkers - success = false; - } else { - // Find the checker center if the corners of the rectangle meet criteria - pointCenter->set((pointUpperLeft.x() + pointBottomRight.x()) / 2.0f, - (pointUpperLeft.y() + pointBottomRight.y()) / 2.0f); - color->set(mImage->getPixelValue(*pointCenter).r(), - mImage->getPixelValue(*pointCenter).g(), - mImage->getPixelValue(*pointCenter).b()); - ALOGV("Color at (%f, %f) is (%d, %d, %d)", pointCenter->x(), pointCenter->y(),color->r(), color->g(), color->b()); - } - return success; -} - -// Verifies the color checker centers and finds the match between the detected -// color checker and the reference MacBeth color checker -void ColorCheckerTest::verifyColorGrid() { - ALOGV("Start looking for Color Grid"); - int numHorizontalLines = mCandidateColors.size(); - int numVerticalLines = mCandidateColors[0].size(); - bool success = false; - - // Computes the standard deviation of one row/column of the proposed color - // checker. Discards the row/column if the std is below a threshold. - for (int i = 0; i < numHorizontalLines; ++i) { - Vec3f meanColor(0.f, 0.f, 0.f); - int numNonZero = 0; - - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - ALOGV("candidate color (%d, %d) is (%d, %d, %d)", i, j, mCandidateColors[i][j]->r(), mCandidateColors[i][j]->g(), mCandidateColors[i][j]->b()); - - meanColor = meanColor + (*mCandidateColors[i][j]); - ++numNonZero; - } - } - if (numNonZero > 0) { - meanColor = meanColor / numNonZero; - } - ALOGV("Mean color for vertical direction computed!"); - - float std = 0; - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - std += mCandidateColors[i][j]->squareDistance<float>(meanColor); - } - } - if (numNonZero > 0) { - std = sqrt(std / (3 * numNonZero)); - } - ALOGV("st. deviation for the %d dir1 is %d", i, static_cast<int>(std)); - - if ((std <= 30) && (numNonZero > 1)) { - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - delete mCandidateColors[i][j]; - mCandidateColors[i][j] = NULL; - } - } - } - } - - // Discards the column/row of the color checker if the std is below a - // threshold. - for (int j = 0; j < numVerticalLines; ++j) { - Vec3f meanColor(0.f, 0.f, 0.f); - int numNonZero = 0; - - for (int i = 0; i < numHorizontalLines; ++i) { - if (mCandidateColors[i][j] != NULL) { - meanColor = meanColor + (*mCandidateColors[i][j]); - ++numNonZero; - } - } - if (numNonZero > 0) { - meanColor = meanColor / numNonZero; - } - - float std = 0; - for (int i = 0; i < numHorizontalLines; ++i) { - if (mCandidateColors[i][j] != NULL) { - std += mCandidateColors[i][j]->squareDistance<float>(meanColor); - } - } - if (numNonZero > 0) { - std = sqrt(std / (3 * numNonZero)); - } - - ALOGV("st. deviation for the %d dir2 is %d", j, static_cast<int>(std)); - - if ((std <= 30) && (numNonZero > 1)) { - for (int i = 0; i < numHorizontalLines; ++i) { - if (mCandidateColors[i][j] != NULL) { - delete mCandidateColors[i][j]; - mCandidateColors[i][j] = NULL; - } - } - } - } - - for (int i = 0; i < numHorizontalLines; ++i) { - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[i][j] != NULL) { - ALOGV("position (%d, %d) is at (%f, %f) with color (%d, %d, %d)", - i, j, - mCandidatePositions[i][j]->x(), - mCandidatePositions[i][j]->y(), - mCandidateColors[i][j]->r(), - mCandidateColors[i][j]->g(), - mCandidateColors[i][j]->b()); - } else { - ALOGV("position (%d, %d) is 0", i, j); - } - } - } - - // Finds the match between the detected color checker and the reference - // MacBeth color checker. - int rowStart = 0; - int rowEnd = 0; - - // Loops until all dectected color checker has been processed. - while (!success) { - int columnStart = 0; - int columnEnd = 0; - bool isRowStart = false; - bool isRowEnd = true; - - // Finds the row start of the next block of detected color checkers. - while ((!isRowStart) && (rowStart < numHorizontalLines)) { - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[rowStart][j] != NULL) { - isRowStart = true; - } - } - ++rowStart; - } - rowStart--; - rowEnd = rowStart; - ALOGV("rowStart is %d", rowStart); - - // Finds the row end of the next block of detected color checkers. - while ((isRowEnd) && (rowEnd < numHorizontalLines)) { - isRowEnd = false; - for (int j = 0; j < numVerticalLines; ++j) { - if (mCandidateColors[rowEnd][j] != NULL) { - isRowEnd= true; - } - } - if (isRowEnd) { - ++rowEnd; - } - } - if ((!isRowEnd) && isRowStart) { - rowEnd--; - } - if ((isRowEnd) && (rowEnd == numHorizontalLines)) { - rowEnd--; - isRowEnd = false; - } - ALOGV("rowEnd is %d", rowEnd); - - // Matches color checkers between the start row and the end row. - bool successVertical = false; - - while (!successVertical) { - bool isColumnEnd = true; - bool isColumnStart = false; - - // Finds the start column of the next block of color checker - while ((!isColumnStart) && (columnStart < numVerticalLines)) { - if (mCandidateColors[rowStart][columnStart] != NULL) { - isColumnStart = true; - } - ++columnStart; - } - columnStart--; - columnEnd = columnStart; - - // Finds the end column of the next block of color checker - while ((isColumnEnd) && (columnEnd < numVerticalLines)) { - isColumnEnd = false; - if (mCandidateColors[rowStart][columnEnd] != NULL) - isColumnEnd = true; - if (isColumnEnd) { - ++columnEnd; - } - } - - if ((!isColumnEnd) && isColumnStart) { - columnEnd--; - } - if ((isColumnEnd) && (columnEnd == numVerticalLines)) { - columnEnd--; - isColumnEnd = false; - } - - // Finds the best match on the MacBeth reference color checker for - // the continuous block of detected color checker - if (isRowStart && (!isRowEnd) && - isColumnStart && (!isColumnEnd)) { - findBestMatch(rowStart, rowEnd, columnStart, columnEnd); - } - ALOGV("FindBestMatch for %d, %d, %d, %d", rowStart, - rowEnd, columnStart, columnEnd); - - // If the column search finishes, go out of the loop - if (columnEnd >= numVerticalLines - 1) { - successVertical = true; - } else { - columnStart = columnEnd + 1; - } - } - ALOGV("Continuing to search for direction 1"); - - // If the row search finishes, go out of the loop - if (rowEnd >= numHorizontalLines - 1) { - success = true; - } else { - rowStart = rowEnd + 1; - } - } - - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 6; ++j) { - if (mMatchPositions[i][j] != NULL) { - ALOGV("Reference Match position for (%d, %d) is (%f, %f)", i, j, - mMatchPositions[i][j]->x(), mMatchPositions[i][j]->y()); - } - } - } - - fillRefColorGrid(); -} - -// Finds the best match on the MacBeth color checker for the continuous block of -// detected color checkers bounded by row i1, row i2 and column j1 and column j2 -// Assumes that the subsample is less than 4*6. -void ColorCheckerTest::findBestMatch(int i1, int i2, int j1, int j2) { - int numHorizontalGrid = i2 - i1 + 1; - int numVerticalGrid = j2 - j1 + 1; - - if (((numHorizontalGrid > 1) || (numVerticalGrid > 1)) && - (numHorizontalGrid <= 4) && (numVerticalGrid <= 6)) { - ALOGV("i1, j2, j1, j2 is %d, %d, %d, %d", i1, i2, j1, j2); - float minError; - float error = 0.f; - int horizontalMatch, verticalMatch; - - // Finds the match start point where the error is minimized. - for (int i = 0; i < numHorizontalGrid; ++i) { - for (int j = 0; j < numVerticalGrid; ++j) { - if (mCandidateColors[i1 + i][j1 + j] != NULL) { - error += mCandidateColors[i1 + i][j1 + j]->squareDistance<int>( - *mReferenceColors[i][j]); - } - } - } - ALOGV("Error is %f", error); - minError = error; - horizontalMatch = 0; - verticalMatch = 0; - - for (int i = 0; i <= 4 - numHorizontalGrid; ++i) { - for (int j = 0; j <= 6 - numVerticalGrid; ++j) { - error = 0.f; - - for (int id = 0; id < numHorizontalGrid; ++id) { - for (int jd = 0; jd < numVerticalGrid; ++jd) { - if (mCandidateColors[i1 + id][j1 + jd] != NULL) { - error += mCandidateColors[i1 + id][j1 + jd]-> - squareDistance<int>( - *mReferenceColors[i + id][j + jd]); - } - } - } - - if (error < minError) { - minError = error; - horizontalMatch = i; - verticalMatch = j; - } - ALOGV("Processed %d, %d and error is %f", i, j, error ); - } - } - - for (int id = 0; id < numHorizontalGrid; ++id) { - for (int jd = 0; jd < numVerticalGrid; ++jd) { - if (mCandidatePositions[i1 + id][j1 + jd] != NULL) { - mMatchPositions[horizontalMatch + id][verticalMatch + jd] = - new Vec2f(mCandidatePositions[i1 + id][j1 + jd]->x(), - mCandidatePositions[i1 + id][j1 + jd]->y()); - } - } - } - ALOGV("Grid match starts at %d, %d", horizontalMatch, verticalMatch); - } -} - -// Finds the boundary of a color checker by its color similarity to the center. -// Also predicts the location of unmatched checkers. -void ColorCheckerTest::fillRefColorGrid() { - int rowStart = 0; - int columnStart = 0; - bool foundStart = true; - - for (int i = 0; (i < 4) && foundStart; ++i) { - for (int j = 0; (j < 6) && foundStart; ++j) { - if (mMatchPositions[i][j] != NULL) { - rowStart = i; - columnStart = j; - foundStart = false; - } - } - } - ALOGV("First match found at (%d, %d)", rowStart, columnStart); - - float rowDistance, columnDistance; - rowDistance = 0; - columnDistance = 0; - int numRowGrids = 0; - int numColumnGrids = 0; - - for (int i = rowStart; i < 4; ++i) { - for (int j = columnStart; j < 6; ++j) { - if (mMatchPositions[i][j] != NULL) { - if (i > rowStart) { - ++numRowGrids; - rowDistance += (mMatchPositions[i][j]->x() - - mMatchPositions[rowStart][columnStart]->x()) / - static_cast<float>(i - rowStart); - } - if (j > columnStart) { - ++numColumnGrids; - columnDistance += (mMatchPositions[i][j]->y() - - mMatchPositions[rowStart][columnStart]->y()) / - static_cast<float>(j - columnStart); - } - } - } - } - - if ((numRowGrids > 0) && (numColumnGrids > 0)) { - rowDistance = rowDistance / numRowGrids; - columnDistance = columnDistance / numColumnGrids; - ALOGV("delta is %f, %f", rowDistance, columnDistance); - - for (int i = 0; i < 4; ++i) { - for (int j = 0 ; j < 6; ++j) { - if (mMatchPositions[i][j] == NULL) { - mMatchPositions[i][j] = new Vec2f( - mMatchPositions[rowStart][columnStart]->x() + - (i - rowStart) * rowDistance, - mMatchPositions[rowStart][columnStart]->y() + - (j - columnStart) * columnDistance); - } - } - } - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 6; ++j) { - float radius = 0; - Vec3i color = mImage->getPixelValue(*mMatchPositions[i][j]); - Vec3f meanColor(0.f , 0.f, 0.f); - - int numPixels = 0; - for (int ii = static_cast<int>(mMatchPositions[i][j]->x() - - rowDistance/2); - ii <= static_cast<int>(mMatchPositions[i][j]->x() + - rowDistance/2); - ++ii) { - for (int jj = static_cast<int>(mMatchPositions[i][j]->y() - - columnDistance/2); - jj <= static_cast<int>(mMatchPositions[i][j]->y() + - columnDistance/2); - ++jj) { - if ((ii >= 0) && (ii < mImage->getHeight()) && - (jj >= 0) && (jj < mImage->getWidth())) { - Vec3i pixelColor = mImage->getPixelValue(ii,jj); - float error = color.squareDistance<int>(pixelColor); - - if (error < COLOR_ERROR_THRESHOLD) { - drawPoint(ii, jj, *mReferenceColors[i][j]); - meanColor = meanColor + pixelColor; - numPixels++; - Vec2i pixelPosition(ii, jj); - - if (pixelPosition.squareDistance<float>( - *mMatchPositions[i][j]) > radius) { - radius = pixelPosition.squareDistance<float>( - *mMatchPositions[i][j]); - } - } - } - } - } - - /** Computes the radius of the checker. - * The above computed radius is the squared distance to the - * furthest point with a matching color. To be conservative, we - * only consider an area with radius half of the above computed - * value. Since radius is computed as a squared root, the one - * that will be recorded is 1/4 of the above computed value. - */ - mMatchRadius[i][j] = radius / 4.f; - mMatchColors[i][j] = new Vec3f(meanColor / numPixels); - - ALOGV("Reference color at (%d, %d) is (%d, %d, %d)", i, j, - mReferenceColors[i][j]->r(), - mReferenceColors[i][j]->g(), - mReferenceColors[i][j]->b()); - ALOGV("Average color at (%d, %d) is (%f, %f, %f)", i, j, - mMatchColors[i][j]->r(), - mMatchColors[i][j]->g(), - mMatchColors[i][j]->b()); - ALOGV("Radius is %f", mMatchRadius[i][j]); - } - } - - mSuccess = true; - } -}
diff --git a/apps/CtsVerifier/lib/colorchecker/exposurecompensationtest.cpp b/apps/CtsVerifier/lib/colorchecker/exposurecompensationtest.cpp deleted file mode 100644 index da9fc40..0000000 --- a/apps/CtsVerifier/lib/colorchecker/exposurecompensationtest.cpp +++ /dev/null
@@ -1,96 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "ExposureCompensationTest" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <string> -#include <stdio.h> - -#include "vec2.h" -#include "vec3.h" -#include "exposurecompensationtest.h" - -const float GAMMA_CORRECTION = 2.2f; -void ExposureCompensationTest::processData() { - ALOGV("Start Processing Exposure Compensation Test Data!"); - clearDebugImage(); - - if (mDebugText != NULL) { - delete mDebugText; - mDebugText = NULL; - } - - int numTests = mExposureValues.size(); - int numPatches = mCheckerColors[0].size(); - ALOGV("Processing %d tests with %d patches", numTests, numPatches); - - mDebugText = new char[320 * numTests]; - mDebugText[0] = 0; - char* debugText = new char[50]; - - Vec3i red(255, 0, 0); - Vec3i green(0, 255, 0); - Vec3i blue(0, 0, 255); - - float minExposure = -3.0f; - float scale = 9.0f; - for (int i = 0; i < numTests; ++i) { - snprintf(debugText, 50, "Exposure is %f \n", mExposureValues[i]); - strcat(mDebugText, debugText); - for (int j = 0; j < numPatches; ++j) { - int exposureRed = static_cast<int>(( - log(static_cast<float>(mReferenceColors[j].r())) - / log(2.0f) * GAMMA_CORRECTION + - mExposureValues[i] - minExposure) * scale); - int exposureGreen = static_cast<int>(( - log(static_cast<float>(mReferenceColors[j].g())) - / log(2.0f) * GAMMA_CORRECTION + - mExposureValues[i] - minExposure) * scale); - int exposureBlue = static_cast<int>(( - log(static_cast<float>(mReferenceColors[j].b())) - / log(2.0f) * GAMMA_CORRECTION + - mExposureValues[i] - minExposure) * scale); - - snprintf(debugText, 50, "%d %f %d %f %d %f \n", - exposureRed, mCheckerColors[i][j].r(), - exposureGreen, mCheckerColors[i][j].g(), - exposureBlue, mCheckerColors[i][j].b()); - - ALOGV("%s", debugText); - strcat(mDebugText, debugText); - - drawPoint(200 - exposureRed, mCheckerColors[i][j].r(), red); - drawPoint(200 - exposureGreen, mCheckerColors[i][j].g(), green); - drawPoint(200 - exposureBlue, mCheckerColors[i][j].b(), blue); - } - } - mExposureValues.clear(); - mCheckerColors.clear(); -} - -void ExposureCompensationTest::initializeReferenceColors() { - mReferenceColors.resize(6); - - mReferenceColors[0].set(243, 243, 242); - mReferenceColors[1].set(200, 200, 200); - mReferenceColors[2].set(160, 160, 160); - mReferenceColors[3].set(122, 122, 121); - mReferenceColors[4].set(85, 85, 85); - mReferenceColors[5].set(52, 52, 52); -}
diff --git a/apps/CtsVerifier/lib/colorchecker/imagetesthandler.cpp b/apps/CtsVerifier/lib/colorchecker/imagetesthandler.cpp deleted file mode 100644 index cc3bca9..0000000 --- a/apps/CtsVerifier/lib/colorchecker/imagetesthandler.cpp +++ /dev/null
@@ -1,102 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "ImageTestHandler" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <cstring> - -#include "vec2.h" -#include "vec3.h" -#include "imagetesthandler.h" - -void ImageTestHandler::initDebugImage() { - mDebugOutput = NULL; -} - -// Initializes the debug image with a given height and width. -void ImageTestHandler::initDebugImage(int debugHeight, - int debugWidth) { - mDebugOutput = NULL; - mDebugOutput = new unsigned char[debugHeight * debugWidth * 4]; - memset(mDebugOutput, 0, debugHeight * debugWidth * 4); - - mDebugHeight = debugHeight; - mDebugWidth = debugWidth; -} - -// Copies an existing image to the debug image. -void ImageTestHandler::copyDebugImage(int inputHeight, int inputWidth, - const unsigned char* inputImage) { - if ((inputHeight == mDebugHeight) && (inputWidth == mDebugWidth)) { - ALOGV("Copying debug images"); - memcpy(mDebugOutput, inputImage, mDebugHeight * mDebugWidth * 4); - } -} - -void ImageTestHandler::clearDebugImage() { - if (mDebugOutput != NULL) { - delete[] mDebugOutput; - mDebugOutput = new unsigned char[mDebugHeight * mDebugWidth * 4]; - memset(mDebugOutput, 0, mDebugHeight * mDebugWidth * 4); - } -} - - -// Draws a point of a given color. -void ImageTestHandler::drawPoint(int row, int column, const Vec3i &color) { - if ((row >= 0) && (column >= 0) && - (column < mDebugWidth) && (row < mDebugHeight)) { - mDebugOutput[(row*mDebugWidth + column) * 4] = color.r(); - mDebugOutput[(row*mDebugWidth + column) * 4+1] = color.g(); - mDebugOutput[(row*mDebugWidth + column) * 4+2] = color.b(); - mDebugOutput[(row*mDebugWidth + column) * 4+3] = 255; - } -} - -// Draws a point in Vec2 format of a given color. -void ImageTestHandler::drawPoint(const Vec2i &point, const Vec3i &color) { - drawPoint((int) point.y(), (int) point.x(), color); -} - -// Draws a line of a given color. -void ImageTestHandler::drawLine(int angle, int radius, const Vec3i &color) { - const int r = color.r(); - const int g = color.g(); - const int b = color.b(); - const int a = 255; - - int shiftedMin = -113; - int shiftedMax = 83; - - float radiusDouble = static_cast<float>(radius); - - float angleRad = static_cast<float>(angle) * M_PI / 180.0; - - //ALOGV("draw line for (%d, %d)", angle, radius); - for (int i = shiftedMin; i <= shiftedMax; ++i) { - float j; - - assert(angle != 0); - j = (i - radiusDouble / sin(angleRad)) * tan(angleRad); - float x = (static_cast<float>(i) + j) / sqrt(2.0); - float y = (j - static_cast<float>(i)) / sqrt(2.0); - - drawPoint(x, y, color); - } -}
diff --git a/apps/CtsVerifier/lib/colorchecker/meteringtest.cpp b/apps/CtsVerifier/lib/colorchecker/meteringtest.cpp deleted file mode 100644 index 47de5d8..0000000 --- a/apps/CtsVerifier/lib/colorchecker/meteringtest.cpp +++ /dev/null
@@ -1,102 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "MeteringTest" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <string> - -#include "vec2.h" -#include "vec3.h" -#include "meteringtest.h" - -const float kOverExposure = 230.f; -const float kEqThreshold = 0.05f; -// Processes the checker colors stored by comparing the pixel values from the -// two scenarios in a test. -void MeteringTest::processData() { - ALOGV("Start Processing Metering Test Data!"); - - int numTests = mCheckerColors.size() / 2; - mNumPatches = 0; - - if (numTests > 0) { - mNumPatches = mCheckerColors[0].size(); - } - - for (int i = 0; i < numTests; ++i) { - mComparisonResults.push_back( - isEquivalentTo((&mCheckerColors[i * 2]), - (&mCheckerColors[i * 2 + 1]))); - mComparisonResults.push_back( - isDarkerThan((&mCheckerColors[i * 2]), - (&mCheckerColors[i * 2 + 1]))); - } -} - -void MeteringTest::clearData() { - mComparisonResults.clear(); - mCheckerColors.clear(); -} - -// Compares two given arrays of pixel values and decide whether the first one is -// significantly darker than the second one. -bool MeteringTest::isDarkerThan( - const std::vector<Vec3f>* checkerColors1, - const std::vector<Vec3f>* checkerColors2) const { - float meanRatio = 0.f; - int meanNumCount = 0; - - for (int i = 0; i < mNumPatches; ++i) { - float luminance1 = (*checkerColors1)[i].convertToLuminance(); - float luminance2 = (*checkerColors2)[i].convertToLuminance(); - - // Out of the saturation rage, define 5% as a margin for being - // significantly brighter. - if ((luminance2 < kOverExposure) && (luminance1 != 0.f)) { - meanRatio += luminance2 / luminance1; - ++meanNumCount; - } - } - meanRatio = meanRatio / meanNumCount; - - return (meanRatio > 1 + kEqThreshold); -} - -// Compares the two givn arrays of pixel values and decide whether they are -// equivalent within an acceptable range. -bool MeteringTest::isEquivalentTo( - const std::vector<Vec3f>* checkerColors1, - const std::vector<Vec3f>* checkerColors2) const { - float meanRatio = 0.f; - int meanNumCount = 0; - - for (int i = 0; i < mNumPatches; ++i) { - float luminance1 = (*checkerColors1)[i].convertToLuminance(); - float luminance2 = (*checkerColors2)[i].convertToLuminance(); - ALOGV("Luma_1 and Luma_2 is %f, %f", luminance1, luminance2); - - if ((luminance1 < kOverExposure) && (luminance2 < kOverExposure)) { - meanRatio += luminance2 / luminance1; - ++meanNumCount; - } - } - meanRatio = meanRatio / meanNumCount; - - return ((meanRatio >= 1 - kEqThreshold) && (meanRatio <= 1 + kEqThreshold)); -}
diff --git a/apps/CtsVerifier/lib/colorchecker/testingimage.cpp b/apps/CtsVerifier/lib/colorchecker/testingimage.cpp deleted file mode 100644 index 28f025f..0000000 --- a/apps/CtsVerifier/lib/colorchecker/testingimage.cpp +++ /dev/null
@@ -1,190 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "TestingImage" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <string.h> -#include <cmath> -#include <vector> -#include <assert.h> -#include "vec3.h" - -#include "testingimage.h" - -const float GAMMA_CORRECTION = 2.2f; - -// Constructs an instance with the given image byte array. -TestingImage::TestingImage(const unsigned char* inputImage, - int inputHeight, int inputWidth, - int inputChannel, int inputRowSpan) { - mImage = new unsigned char[inputRowSpan * inputHeight]; - - ALOGV("mImage format created! with size as %d, %d, %d", - inputRowSpan, inputHeight, inputChannel); - mWidth = inputWidth; - mHeight = inputHeight; - mChannels = inputChannel; - mRowSpan = mWidth * mChannels; - - for (int i = 0; i < mHeight; ++i) { - for (int j = 0; j < mWidth; ++j) { - for (int k = 0; k < mChannels; ++k) { - mImage[i * mRowSpan + j* mChannels + k] = - inputImage[i * inputRowSpan + j * inputChannel + k]; - } - } - } - ALOGV("mImage converted!"); -} - -// Constructs an instance with the given image and resize it to a new size. -TestingImage::TestingImage(const unsigned char* inputImage, - int inputHeight, int inputWidth, - int inputChannel, int inputRowSpan, - int newHeight, int newWidth) { - mImage = new unsigned char[newHeight * newWidth * inputChannel]; - - ALOGV("mImage format created! with size as %d, %d, %d", - newHeight, newWidth, inputChannel); - mHeight = newHeight; - mWidth = newWidth; - mChannels = inputChannel; - mRowSpan = mWidth * mChannels; - - // Computes how many pixels in the original image corresponds to one pixel - // in the new image. - int heightScale = inputHeight / newHeight; - int widthScale = inputWidth / newWidth; - - // Average the corresponding pixels in the original image to compute the - // pixel value of the new image. - for (int i = 0; i < mHeight; ++i) { - for (int j = 0; j < mWidth; ++j) { - for (int k = 0; k < mChannels; ++k) { - int pixelValue = 0; - - for (int l = 0; l < heightScale; ++l) { - for (int m = 0; m < widthScale; ++m) { - pixelValue += inputImage[ - (i * heightScale + l) * inputRowSpan - + (j * widthScale + m) * inputChannel + k]; - } - } - pixelValue = pixelValue / (heightScale * widthScale); - mImage[i * mRowSpan + j * mChannels + k] = - (unsigned char) pixelValue; - } - } - } -} - -TestingImage::~TestingImage() { - if (mImage!=NULL) { - delete[] mImage; - } -} - -int TestingImage::getPixelValue(int row, int column, int channel) const { - assert ((row >= 0) && (row < mHeight)); - assert ((column >= 0) && (column < mWidth)); - assert ((channel >= 0) && (channel < mChannels)); - return (int)mImage[row * mRowSpan + column * mChannels + channel]; -} - -Vec3i TestingImage::getPixelValue(int row, int column) const { - Vec3i current_color(getPixelValue(row, column, 0), - getPixelValue(row, column, 1), - getPixelValue(row, column, 2)); - return current_color; -} - -Vec3i TestingImage::getPixelValue(const Vec2i &pixelPosition) const { - return getPixelValue(pixelPosition.x(), pixelPosition.y()); -} - -Vec3i TestingImage::getPixelValue(const Vec2f &pixelPosition) const { - return getPixelValue(static_cast<int>(pixelPosition.x()), - static_cast<int>(pixelPosition.y())); -} - -// Returns a vector of the colors in the requested block of color checkers. -// The vector is formatted by going through the block from left to right and -// from top to bottom. -const std::vector<Vec3f>* TestingImage::getColorChecker( - int rowStart, int rowEnd, int columnStart, int columnEnd, - const std::vector<std::vector< Vec2f > >* centerAddress, - const std::vector<std::vector< float > >* radiusAddress) const { - std::vector<Vec3f>* checkerColors = new std::vector<Vec3f>; - - // Average the pixel values of the pixels within the given radius to the - // given center position. - for (int i = rowStart; i < rowEnd; ++i) { - for (int j = columnStart; j < columnEnd; ++j) { - float radius = sqrt((*radiusAddress)[i][j]); - Vec2f center((*centerAddress)[i][j].x(), - (*centerAddress)[i][j].y()); - Vec3f meanColor(0.f, 0.f, 0.f); - int numPixels = 0; - - for (int ii = static_cast<int>(center.x() - radius); - ii < static_cast<int>(center.x() + radius); ++ii) { - for (int jj = static_cast<int>(center.y() - radius); - jj < static_cast<int>(center.y() + radius); ++jj) { - - Vec2i pixelPosition(ii,jj); - if (pixelPosition.squareDistance<float>(center) < - (*radiusAddress)[i][j]) { - meanColor = meanColor + getPixelValue(pixelPosition); - ++numPixels; - } - } - } - meanColor = meanColor / numPixels; - checkerColors->push_back(meanColor); - } - } - - return checkerColors; -} - -bool TestingImage::rgbToGrayScale(unsigned char* grayLayer) const { - if (mChannels == 4) { - for (int i = 0; i < mWidth; i++) { - for (int j = 0; j < mHeight; j++) { - float redLinear = pow(getPixelValue(j, i, 0), - GAMMA_CORRECTION); - float greenLinear = pow(getPixelValue(j,i,1), - GAMMA_CORRECTION); - float blueLinear = pow(getPixelValue(j,i,2), - GAMMA_CORRECTION); - - // Computes the luminance value - grayLayer[j * mWidth + i] = - (unsigned char)((int)pow((0.299f * redLinear - + 0.587f * greenLinear - + 0.114f * blueLinear), - 1/GAMMA_CORRECTION)); - } - } - - return true; - } else { - - return false; - } -}
diff --git a/apps/CtsVerifier/lib/colorchecker/vec2.cpp b/apps/CtsVerifier/lib/colorchecker/vec2.cpp deleted file mode 100644 index 29736bb..0000000 --- a/apps/CtsVerifier/lib/colorchecker/vec2.cpp +++ /dev/null
@@ -1,22 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "Vec2" -#include <utils/Log.h> -#include <utils/Timers.h> - -#include "vec2.h"
diff --git a/apps/CtsVerifier/lib/colorchecker/vec3.cpp b/apps/CtsVerifier/lib/colorchecker/vec3.cpp deleted file mode 100644 index ac16620..0000000 --- a/apps/CtsVerifier/lib/colorchecker/vec3.cpp +++ /dev/null
@@ -1,22 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "Vec3" -#include <utils/Log.h> -#include <utils/Timers.h> - -#include "vec3.h"
diff --git a/apps/CtsVerifier/lib/colorchecker/whitebalancetest.cpp b/apps/CtsVerifier/lib/colorchecker/whitebalancetest.cpp deleted file mode 100644 index 6413a2b..0000000 --- a/apps/CtsVerifier/lib/colorchecker/whitebalancetest.cpp +++ /dev/null
@@ -1,122 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ -#define LOG_NDEBUG 0 - -#define LOG_TAG "WhiteBalanceTest" -#include <utils/Log.h> -#include <utils/Timers.h> -#include <cmath> -#include <string> - -#include "vec2.h" -#include "vec3.h" -#include "whitebalancetest.h" - -// White point in XYZ color space under 5200k illumination. -const Vec3f kDaylightWhitePoint(0.9781f, 1.f, 0.9021f); - -// Process the data of checker colors collected under different white balance. -// Assuming the Daylight CCT is set to 5200k, compute the CCT of other white -// balance modes. -void WhiteBalanceTest::processData() { - ALOGV("Start Processing White Balance Test Data!"); - - int numPatches = mCheckerColors.size(); - ALOGV("Processing %d tests with %d patches", 2, numPatches); - - std::vector<Vec3f> xyzColors(numPatches); - for (int j = 0; j < numPatches; ++j) { - Vec3f xyzCheckerColor = initializeFromRGB(mCheckerColors[j]); - xyzColors[j] = xyzCheckerColor; - ALOGV("XYZ coordinate is %f, %f, %f", xyzCheckerColor.r(), - xyzCheckerColor.g(), xyzCheckerColor.b()); - } - - Vec3f meanScale(0.f, 0.f, 0.f); - - if (mMode == "daylight") { - mXyzColorsDaylight = xyzColors; - // For testing the auto white balance mode. Compute a CCT that would - // map the gray checkers to a white point. - for (int j = 1; j < numPatches; ++j) { - meanScale = meanScale + - (mXyzColorsDaylight[j] / kDaylightWhitePoint); - } - } else { - for (int j = 1; j < numPatches; ++j) { - meanScale = meanScale + (mXyzColorsDaylight[j] / xyzColors[j]); - } - } - - meanScale = meanScale / (numPatches - 1); - ALOGV("Scale: %f, %f, %f", meanScale.r(), meanScale.g(), meanScale.b()); - - Vec3f whitePoint; - whitePoint = meanScale * kDaylightWhitePoint; - - ALOGV("White point is %f, %f, %f", whitePoint.r(), - whitePoint.g(), whitePoint.b()); - - mCorrelatedColorTemp = findCorrelatedColorTemp(whitePoint); - ALOGV("CCT is %d", mCorrelatedColorTemp); -} - -// Given a white point, find the correlated color temperature. -// Formula taken from the paper "Calculating Correlated Color Temperatures -// Across the Entire Gamut of Daylight and Skylight Chromaticities" by Hernandez -// Andres et al. in 1999. The numbers are fitting parameters. -int WhiteBalanceTest::findCorrelatedColorTemp(const Vec3f &whitePoint) { - Vec2f chromaOfWhitePoint( - whitePoint.r() / (whitePoint.r() + whitePoint.g() + whitePoint.b()), - whitePoint.g() / (whitePoint.r() + whitePoint.g() + whitePoint.b())); - - float n = (chromaOfWhitePoint.x() - 0.3366f) - / (chromaOfWhitePoint.y() - 0.1735f); - float y = -949.86315f + 6253.80338f * exp(-n / 0.92159f) - + 28.70599f * exp(-n / 0.20039f) + 0.00004f * exp(-n / 0.07125f); - - return static_cast<int>(y); -} - -// Converts a RGB pixel value to XYZ color space. -Vec3f WhiteBalanceTest::initializeFromRGB(const Vec3f &rgb) { - float linearRed = convertToLinear(rgb.r()); - float linearGreen = convertToLinear(rgb.g()); - float linearBlue = convertToLinear(rgb.b()); - - float x = 0.4124f * linearRed + 0.3576f * linearGreen + - 0.1805f * linearBlue; - float y = 0.2126f * linearRed + 0.7152f * linearGreen + - 0.0722f * linearBlue; - float z = 0.0193f * linearRed + 0.1192f * linearGreen + - 0.9505f * linearBlue; - - return Vec3f(x, y, z); -} - -float WhiteBalanceTest::convertToLinear(float color) { - float norm = color/ 255.0f; - float linearColor; - - // Convert from sRGB space to linear RGB value - if (norm > 0.04045f) { - linearColor = pow(((norm + 0.055f) / 1.055f), 2.4f); - } else { - linearColor = norm / 12.92f; - } - - return linearColor; -}
diff --git a/apps/CtsVerifier/libs/opencv-android.jar b/apps/CtsVerifier/libs/opencv-android.jar new file mode 100644 index 0000000..1c13eee --- /dev/null +++ b/apps/CtsVerifier/libs/opencv-android.jar Binary files differ
diff --git a/apps/CtsVerifier/libs/opencv-android_LICENSE b/apps/CtsVerifier/libs/opencv-android_LICENSE new file mode 100644 index 0000000..5e32d88 --- /dev/null +++ b/apps/CtsVerifier/libs/opencv-android_LICENSE
@@ -0,0 +1,33 @@ +By downloading, copying, installing or using the software you agree to this license. +If you do not agree to this license, do not download, install, +copy or use the software. + + + License Agreement + For Open Source Computer Vision Library + (3-clause BSD License) + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the names of the copyright holders nor the names of the contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are disclaimed. +In no event shall copyright holders or contributors be liable for any direct, +indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused +and on any theory of liability, whether in contract, strict liability, +or tort (including negligence or otherwise) arising in any way out of +the use of this software, even if advised of the possibility of such damage.
diff --git a/apps/CtsVerifier/proguard.flags b/apps/CtsVerifier/proguard.flags index ca4680f..5a2beb5 100644 --- a/apps/CtsVerifier/proguard.flags +++ b/apps/CtsVerifier/proguard.flags
@@ -16,6 +16,14 @@ -keepclasseswithmembers class * extends com.android.cts.verifier.location.LocationModeTestActivity +# keep mockito methods +-keep class org.mockito.** { *; } +-keep interface org.mockito.** { *; } +-keep class com.google.dexmaker.** { *; } +-keep interface com.google.dexmaker.** { *; } + -dontwarn android.hardware.Sensor -dontwarn android.test.AndroidTestRunner -dontwarn java.util.concurrent.ConcurrentLinkedDeque +-dontwarn android.cts.util.** +-dontwarn junit.**
diff --git a/apps/CtsVerifier/res/drawable/app_link_img.png b/apps/CtsVerifier/res/drawable/app_link_img.png new file mode 100644 index 0000000..851fc6f --- /dev/null +++ b/apps/CtsVerifier/res/drawable/app_link_img.png Binary files differ
diff --git a/apps/CtsVerifier/res/drawable/prompt_x.png b/apps/CtsVerifier/res/drawable/prompt_x.png new file mode 100644 index 0000000..64302dc --- /dev/null +++ b/apps/CtsVerifier/res/drawable/prompt_x.png Binary files differ
diff --git a/apps/CtsVerifier/res/drawable/prompt_y.png b/apps/CtsVerifier/res/drawable/prompt_y.png new file mode 100644 index 0000000..01926b5 --- /dev/null +++ b/apps/CtsVerifier/res/drawable/prompt_y.png Binary files differ
diff --git a/apps/CtsVerifier/res/drawable/prompt_z.png b/apps/CtsVerifier/res/drawable/prompt_z.png new file mode 100644 index 0000000..f4d86d6 --- /dev/null +++ b/apps/CtsVerifier/res/drawable/prompt_z.png Binary files differ
diff --git a/apps/CtsVerifier/res/drawable/stat_sys_managed_profile_status.xml b/apps/CtsVerifier/res/drawable/stat_sys_managed_profile_status.xml new file mode 100644 index 0000000..b04059e --- /dev/null +++ b/apps/CtsVerifier/res/drawable/stat_sys_managed_profile_status.xml
@@ -0,0 +1,29 @@ +<!-- +Copyright (C) 2015 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. +--> +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="23.0dp" + android:height="18.0dp" + android:viewportWidth="21.0" + android:viewportHeight="17.0"> + <group android:translateX="2.0"> + <path + android:fillColor="#FFFFFFFF" + android:pathData="M9.9,11.6H7v-1.1H2.1v2.8c0,0.8,0.6,1.4,1.4,1.4h9.9c0.8,0,1.4,-0.6,1.4,-1.4v-2.8H9.9V11.6z"/> + <path + android:fillColor="#FFFFFFFF" + android:pathData="M14.1,4.2h-2.5V3.2l-1.1,-1.1H6.3L5.3,3.2v1H2.8C2,4.2,1.4,4.9,1.4,5.6v2.8c0,0.8,0.6,1.4,1.4,1.4H7V8.8h2.8v1.1h4.2 c0.8,0,1.4,-0.6,1.4,-1.4V5.6C15.5,4.9,14.8,4.2,14.1,4.2z M10.6,4.2H6.3V3.2h4.2V4.2z"/> + </group> +</vector>
diff --git a/apps/CtsVerifier/res/layout/audio_dev_notify.xml b/apps/CtsVerifier/res/layout/audio_dev_notify.xml new file mode 100644 index 0000000..98dbd8b --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_dev_notify.xml
@@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text" + android:text="@string/audio_devices_notification_instructions" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_dev_notification_connect_clearmsgs_btn" + android:text="@string/audio_dev_notification_clearmsgs"/> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_dev_notification_connect_msg"/> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_dev_notification_disconnect_msg"/> + + </LinearLayout> + + <include layout="@layout/pass_fail_buttons" /> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/audio_frequency_line_activity.xml b/apps/CtsVerifier/res/layout/audio_frequency_line_activity.xml new file mode 100644 index 0000000..96c83b2 --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_frequency_line_activity.xml
@@ -0,0 +1,83 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> +<ScrollView + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/scrollView"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text" + android:text="@string/audio_frequency_line_instructions" /> + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_line_plug_ready_btn" + android:text="@string/audio_frequency_line_plug_ready_btn"/> + + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal" + android:id="@+id/audio_frequency_line_layout"> + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_line_test_btn" + android:id="@+id/audio_frequency_line_test_btn"/> + + <ProgressBar + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_line_progress_bar"/> + </LinearLayout> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_line_results_text" + android:id="@+id/audio_frequency_line_results_text"/> + + </LinearLayout> + </LinearLayout> + + <include layout="@layout/pass_fail_buttons" /> + </LinearLayout> + </ScrollView> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml b/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml new file mode 100644 index 0000000..10b0003 --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml
@@ -0,0 +1,133 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/scrollView"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal"> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:id="@+id/info_text" + android:text="@string/audio_frequency_mic_instructions"/> + + <ProgressBar + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:id="@+id/audio_frequency_mic_progress_bar"/> + </LinearLayout> + + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_mic_speakers_ready_btn" + android:text="@string/audio_frequency_mic_speakers_ready_btn"/> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/audio_frequency_mic_speakers_ready_status" + android:text="@string/audio_frequency_mic_speakers_ready_status"/> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:id="@+id/audio_frequency_mic_layout_test1"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_instructions2" + android:id="@+id/audio_frequency_mic_instructions2"/> + + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_test1_btn" + android:id="@+id/audio_frequency_mic_test1_btn"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_results_text" + android:id="@+id/audio_frequency_mic_results1_text"/> + </LinearLayout> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:id="@+id/audio_frequency_mic_layout_test2a"> + + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_mic_mic_ready_btn" + android:text="@string/audio_frequency_mic_mic_ready_btn"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_usb_status" + android:id="@+id/audio_frequency_mic_usb_status"/> + </LinearLayout> + + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/audio_frequency_mic_layout_test2b"> + + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_test2_btn" + android:id="@+id/audio_frequency_mic_test2_btn"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_mic_results_text" + android:id="@+id/audio_frequency_mic_results_text"/> + + </LinearLayout> + + <include layout="@layout/pass_fail_buttons"/> + </LinearLayout> + </ScrollView> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/audio_frequency_speaker_activity.xml b/apps/CtsVerifier/res/layout/audio_frequency_speaker_activity.xml new file mode 100644 index 0000000..5dd55b1 --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_frequency_speaker_activity.xml
@@ -0,0 +1,92 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/scrollView"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text" + android:text="@string/audio_frequency_speaker_instructions"/> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_speaker_mic_ready_btn" + android:text="@string/audio_frequency_speaker_mic_ready_btn"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_speaker_usb_status" + android:id="@+id/audio_frequency_speaker_usb_status"/> + + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal" + android:id="@+id/audio_frequency_speaker_layout"> + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_speaker_test_btn" + android:id="@+id/audio_frequency_speaker_test_btn"/> + + <ProgressBar + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:id="@+id/audio_frequency_speaker_progress_bar"/> + </LinearLayout> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_frequency_speaker_results_text" + android:id="@+id/audio_frequency_speaker_results_text"/> + + </LinearLayout> + </LinearLayout> + + <include layout="@layout/pass_fail_buttons"/> + </LinearLayout> + </ScrollView> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/audio_loopback_activity.xml b/apps/CtsVerifier/res/layout/audio_loopback_activity.xml new file mode 100644 index 0000000..773ee9d --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_loopback_activity.xml
@@ -0,0 +1,90 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/scrollView"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text" + android:text="@string/audio_loopback_instructions" /> + + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_loopback_plug_ready_btn" + android:text="@string/audio_loopback_plug_ready_btn"/> + + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/audio_loopback_layout"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_loopback_instructions2" + android:id="@+id/audio_loopback_instructions2"/> + + <SeekBar + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_loopback_level_seekbar"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_loopback_level_text" + android:id="@+id/audio_loopback_level_text"/> + + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_loopback_test_btn" + android:id="@+id/audio_loopback_test_btn"/> + + <ProgressBar + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:id="@+id/audio_loopback_progress_bar"/> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/audio_loopback_results_text" + android:id="@+id/audio_loopback_results_text"/> + </LinearLayout> + <include layout="@layout/pass_fail_buttons" /> + </LinearLayout> + </ScrollView> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/audio_routingnotifications_test.xml b/apps/CtsVerifier/res/layout/audio_routingnotifications_test.xml new file mode 100644 index 0000000..cef30d6 --- /dev/null +++ b/apps/CtsVerifier/res/layout/audio_routingnotifications_test.xml
@@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text" + android:text="@string/audio_dev_routingnotification_instructions" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:id="@+id/audioTrackRoutingLayout"> + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="@string/audio_routingnotification_playHeader"/> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_audioTrack_change"/> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal"> + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_playBtn" + android:text="@string/audio_routingnotification_playBtn"/> + + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_playStopBtn" + android:text="@string/audio_routingnotification_playStopBtn"/> + </LinearLayout> + </LinearLayout> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:id="@+id/audioRecordRoutingLayout"> + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="@string/audio_routingnotification_recHeader"/> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_audioRecord_change"/> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="horizontal"> + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_recordBtn" + android:text="@string/audio_routingnotification_recBtn"/> + + <Button + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:id="@+id/audio_routingnotification_recordStopBtn" + android:text="@string/audio_routingnotification_recStopBtn"/> + </LinearLayout> + </LinearLayout> + + <include layout="@layout/pass_fail_buttons" /> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/ca_main.xml b/apps/CtsVerifier/res/layout/ca_main.xml deleted file mode 100644 index 274430d..0000000 --- a/apps/CtsVerifier/res/layout/ca_main.xml +++ /dev/null
@@ -1,81 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> - -<!-- Copyright (C) 2011 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. ---> -<android.support.wearable.view.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - android:layout_width="match_parent" - android:layout_height="match_parent"> - <LinearLayout app:layout_box="all" - android:orientation="vertical" android:layout_width="fill_parent" - android:layout_height="fill_parent"> - - - <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:orientation="horizontal" android:layout_width="fill_parent" - android:layout_height="wrap_content"> - <!--Button android:id="@+id/focusmodesbutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_focus_modes_label" - android:layout_weight="1" /--> - <Button android:id="@+id/findcheckerboardbutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_find_checkerboard_label" - android:layout_weight="1" /> - - <Button android:id="@+id/meteringbutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_metering_label" - android:layout_weight="1" /> - - <Button android:id="@+id/exposurecompensationbutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_exposure_test_label" - android:layout_weight="1"/> - - <Button android:id="@+id/whitebalancebutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_wb_test_label" - android:layout_weight="1" /> - - <Button android:id="@+id/lockbutton" android:layout_width="0px" - android:layout_height="wrap_content" android:text="@string/ca_lock_test_label" - android:layout_weight="1" /> - </LinearLayout> - - <LinearLayout android:orientation="horizontal" - android:layout_width="fill_parent" android:layout_height="0px" - android:layout_weight="1"> - - <SurfaceView android:id="@+id/cameraview" android:layout_height="fill_parent" - android:layout_width="wrap_content" - android:layout_weight="0" /> - - <LinearLayout android:orientation="vertical" - android:layout_width="fill_parent" android:layout_height="match_parent" - android:layout_weight="1"> - - <ListView android:id="@+id/ca_tests" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:layout_weight="1" - android:layout_marginLeft="10px"/> - - <ImageView android:id="@+id/resultview" android:layout_height="wrap_content" - android:layout_width="fill_parent" - android:layout_weight="1" /> - </LinearLayout> - - </LinearLayout> - - <include layout="@layout/pass_fail_buttons" /> - - </LinearLayout> -</android.support.wearable.view.BoxInsetLayout>
diff --git a/apps/CtsVerifier/res/layout/cam_preview_overlay.xml b/apps/CtsVerifier/res/layout/cam_preview_overlay.xml new file mode 100644 index 0000000..41bbeb1 --- /dev/null +++ b/apps/CtsVerifier/res/layout/cam_preview_overlay.xml
@@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="utf-8"?> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" android:layout_width="match_parent" + android:layout_height="match_parent" + android:keepScreenOn="true"> + <view + android:layout_width="match_parent" + android:layout_height="match_parent" + class="com.android.cts.verifier.sensors.RVCVCameraPreview" + android:id="@+id/cam_preview" + android:layout_centerVertical="true" + android:layout_centerHorizontal="true" /> + + <!-- + <ImageView + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_centerVertical="true" + android:id="@+id/cam_overlay" + android:src="@drawable/icon" + android:scaleType="fitStart" + /> + --> + <view + android:layout_width="match_parent" + android:layout_height="match_parent" + class="com.android.cts.verifier.sensors.MotionIndicatorView" + android:id="@+id/cam_indicator" + android:layout_centerVertical="true" + android:layout_centerHorizontal="true" /> + + <ImageView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_centerInParent="true" + android:id="@+id/cam_overlay" + android:scaleType="fitStart" + /> +</RelativeLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/camera_flashlight.xml b/apps/CtsVerifier/res/layout/camera_flashlight.xml new file mode 100644 index 0000000..2d4378c --- /dev/null +++ b/apps/CtsVerifier/res/layout/camera_flashlight.xml
@@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_gravity="bottom" + android:orientation="vertical"> + + <TextView + android:id="@+id/flash_instruction_text" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="2" + android:gravity="center" + android:text="@string/camera_flashlight_start_text" /> + + <Button + android:id="@+id/flash_instruction_button" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginLeft="100dp" + android:layout_marginRight="100dp" + android:text="@string/camera_flashlight_start_button" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="10dp" + android:layout_marginLeft="50dp" + android:layout_marginRight="50dp" + android:layout_marginBottom="50dp" + android:orientation="horizontal"> + + <Button + android:id="@+id/flash_on_button" + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="1" + android:text="@string/camera_flashlight_on_button" /> + + <Button + android:id="@+id/flash_off_button" + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="1" + android:text="@string/camera_flashlight_off_button" /> + + </LinearLayout> + + <include layout="@layout/pass_fail_buttons"/> + +</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/byod_custom_view.xml b/apps/CtsVerifier/res/layout/dialog_custom_view.xml similarity index 100% rename from apps/CtsVerifier/res/layout/byod_custom_view.xml rename to apps/CtsVerifier/res/layout/dialog_custom_view.xml
diff --git a/apps/CtsVerifier/res/layout/hifi_ultrasound.xml b/apps/CtsVerifier/res/layout/hifi_ultrasound.xml new file mode 100644 index 0000000..7d2de5a --- /dev/null +++ b/apps/CtsVerifier/res/layout/hifi_ultrasound.xml
@@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2011 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. +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="7" + android:scrollbars="vertical" + android:gravity="bottom" + android:id="@+id/info_text"/> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="3" + android:orientation="horizontal"> + <Button + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="5" + android:text="@string/hifi_ultrasound_test_record" + android:id="@+id/recorder_button"/> + <Button + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="5" + android:text="@string/hifi_ultrasound_test_play" + android:id="@+id/player_button"/> + </LinearLayout> + + <include layout="@layout/pass_fail_buttons" /> + +</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/hifi_ultrasound_popup.xml b/apps/CtsVerifier/res/layout/hifi_ultrasound_popup.xml new file mode 100644 index 0000000..afff2c9 --- /dev/null +++ b/apps/CtsVerifier/res/layout/hifi_ultrasound_popup.xml
@@ -0,0 +1,33 @@ +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:background="@android:color/white" + android:gravity="center" + android:orientation="vertical" > + + <com.androidplot.xy.XYPlot + android:id="@+id/responseChart" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="9" + androidPlot.domainLabel="kHz" + androidPlot.rangeLabel="dB" + androidPlot.domainLabelWidget.labelPaint.textSize="16dp" + androidPlot.rangeLabelWidget.labelPaint.textSize="16dp" + androidPlot.graphWidget.rangeLabelPaint.textSize="16dp" + androidPlot.graphWidget.rangeOriginLabelPaint.textSize="16dp" + androidPlot.graphWidget.domainLabelPaint.textSize="16dp" + androidPlot.graphWidget.domainOriginLabelPaint.textSize="16dp" + androidPlot.legendWidget.textPaint.textSize="16dp" + androidPlot.legendWidget.iconSizeMetrics.heightMetric.value="16dp" + androidPlot.legendWidget.iconSizeMetrics.widthMetric.value="16dp" + androidPlot.legendWidget.heightMetric.value="16dp" + androidPlot.graphWidget.gridLinePaint.color="#000000" /> + + <Button + android:id="@+id/dismiss" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:text="@string/hifi_ultrasound_test_dismiss" /> +</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/hifi_ultrasound_popup_instru.xml b/apps/CtsVerifier/res/layout/hifi_ultrasound_popup_instru.xml new file mode 100644 index 0000000..42af6e9 --- /dev/null +++ b/apps/CtsVerifier/res/layout/hifi_ultrasound_popup_instru.xml
@@ -0,0 +1,21 @@ +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:gravity="center" + android:background="@android:color/black" + android:padding="5dp" + android:orientation="vertical" > + + <TextView + android:id="@+id/instru" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_weight="5" /> + + <Button + android:id="@+id/ok" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:text="@string/hifi_ultrasound_test_ok" + android:layout_weight="1" /> +</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/keychain_main.xml b/apps/CtsVerifier/res/layout/keychain_main.xml new file mode 100644 index 0000000..3f695cd --- /dev/null +++ b/apps/CtsVerifier/res/layout/keychain_main.xml
@@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> +<android.support.wearable.view.BoxInsetLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical" + android:padding="10dip"> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:fillViewport="true"> + + <LinearLayout + android:id="@+id/test_messages" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:id="@+id/test_instruction" + style="@style/InstructionsFont" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_weight="0" /> + + <TextView + android:id="@+id/test_log" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:orientation="vertical" /> + + </LinearLayout> + </ScrollView> + + <LinearLayout + android:id="@+id/action_buttons" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_weight="0" + android:orientation="horizontal"> + + <Button + android:id="@+id/action_reset" + android:text="@string/keychain_reset" + android:layout_weight="1" + android:layout_width="0dp" + android:layout_height="wrap_content" /> + + <Button + android:id="@+id/action_skip" + android:text="@string/keychain_skip" + android:layout_weight="1" + android:layout_width="0dp" + android:layout_height="wrap_content" /> + + <Button + android:id="@+id/action_next" + android:text="@string/next_button_text" + android:layout_weight="1" + android:layout_width="0dp" + android:layout_height="wrap_content" /> + + </LinearLayout> + + <include + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_weight="0" + layout="@layout/pass_fail_buttons" /> + + </LinearLayout> +</android.support.wearable.view.BoxInsetLayout>
diff --git a/apps/CtsVerifier/res/layout/permission_lockdown.xml b/apps/CtsVerifier/res/layout/permission_lockdown.xml new file mode 100644 index 0000000..ea295dd --- /dev/null +++ b/apps/CtsVerifier/res/layout/permission_lockdown.xml
@@ -0,0 +1,110 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/permission_lockdown_activity" + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:paddingTop="4dp"> + <TextView + android:id="@+id/test_instructions" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="@string/device_profile_owner_permission_lockdown_test_instructions" + android:textSize="18sp" + android:padding="10dp" /> + </ScrollView> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_gravity="center_vertical" + android:paddingStart="10dp" + android:paddingEnd="10dp"> + + <LinearLayout + android:orientation="horizontal" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingTop="4dp"> + <ImageView + android:id="@+id/package_icon" + android:layout_width="48dp" + android:layout_height="48dp" + android:scaleType="centerInside" + android:gravity="center" /> + <TextView + android:id="@+id/package_name" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:gravity="center_vertical" + android:paddingLeft="10dp" + android:textSize="16sp" + android:singleLine="true" + android:ellipsize="end" /> + </LinearLayout> + + <TextView + android:id="@+id/permission_name" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textSize="16sp" + android:paddingTop="4dp" /> + + <RadioGroup + android:id="@+id/permission_group" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:paddingTop="4dp"> + <RadioButton + android:id="@+id/permission_allow" + android:text="@string/permission_allow" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + <RadioButton + android:id="@+id/permission_default" + android:text="@string/permission_default" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + <RadioButton + android:id="@+id/permission_deny" + android:text="@string/permission_deny" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + </RadioGroup> + + <Button + android:id="@+id/open_settings" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_horizontal" + android:text="@string/open_settings_button_label" + android:onClick="openSettings" /> + </LinearLayout> + </ScrollView> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/positive_device_owner.xml b/apps/CtsVerifier/res/layout/positive_device_owner.xml new file mode 100644 index 0000000..f5d10e0 --- /dev/null +++ b/apps/CtsVerifier/res/layout/positive_device_owner.xml
@@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + > + + <ScrollView + android:layout_width="match_parent" + android:layout_height="320dp" + android:layout_weight="2"> + <TextView + android:id="@+id/positive_device_owner_instructions" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:text="@string/device_owner_positive_tests_instructions" + android:textSize="18dip" /> + </ScrollView> + + <Button + android:id="@+id/set_device_owner_button" + android:layout_width="204dp" + android:layout_height="wrap_content" + android:text="@string/set_device_owner_button_label" /> + + <ListView + android:id="@+id/android:list" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_weight="3" /> + + <include layout="@layout/pass_fail_buttons" /> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/layout/provisioning_byod.xml b/apps/CtsVerifier/res/layout/provisioning_byod.xml index b1b75ba..375c3ab 100644 --- a/apps/CtsVerifier/res/layout/provisioning_byod.xml +++ b/apps/CtsVerifier/res/layout/provisioning_byod.xml
@@ -24,19 +24,17 @@ android:layout_height="320dp" android:layout_weight="2"> <TextView - android:id="@+id/byod_instructions" + android:id="@+id/test_instructions" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dip" - android:text="@string/provisioning_byod_instructions" android:textSize="18dip" /> </ScrollView> <Button - android:id="@+id/byod_start" + android:id="@+id/prepare_test_button" android:layout_width="204dp" - android:layout_height="wrap_content" - android:text="@string/provisioning_byod_start" /> + android:layout_height="wrap_content" /> <ListView android:id="@+id/android:list"
diff --git a/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml b/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml new file mode 100644 index 0000000..af53335 --- /dev/null +++ b/apps/CtsVerifier/res/layout/sec_screen_lock_keys_main.xml
@@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2011 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. +--> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:padding="10dip" + > + + <Button android:id="@+id/sec_start_test_button" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_centerInParent="true" + android:text="@string/sec_start_test" + /> + + <include android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_alignParentBottom="true" + layout="@layout/pass_fail_buttons" + /> + +</RelativeLayout> +
diff --git a/apps/CtsVerifier/res/layout/wifi_lockdown.xml b/apps/CtsVerifier/res/layout/wifi_lockdown.xml new file mode 100644 index 0000000..ae6ea0c --- /dev/null +++ b/apps/CtsVerifier/res/layout/wifi_lockdown.xml
@@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + > + + <ScrollView + android:layout_width="match_parent" + android:layout_height="320dp" + android:layout_weight="2"> + <TextView + android:id="@+id/device_owner_wifi_lockdown_info" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:padding="10dip" + android:text="@string/device_owner_wifi_lockdown_info" + android:textSize="18dip" /> + </ScrollView> + + <EditText + android:id="@+id/device_owner_wifi_ssid" + android:hint="(SSID)" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + + <RadioGroup + android:id="@+id/device_owner_keyManagementMethods" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal"> + <RadioButton + android:id="@+id/device_owner_keymgmnt_none" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/device_owner_wifi_key_management_none_button" /> + <RadioButton + android:id="@+id/device_owner_keymgmnt_wpa" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/device_owner_wifi_key_management_wpa_button" /> + <RadioButton + android:id="@+id/device_owner_keymgmnt_wep" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/device_owner_wifi_key_management_wep_button" /> + </RadioGroup> + + <Button + android:id="@+id/create_wifi_config_button" + android:layout_width="204dp" + android:layout_height="wrap_content" + android:text="@string/create_wifi_config_button_label" /> + + <ListView + android:id="@+id/android:list" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_weight="3" /> + + <include layout="@layout/pass_fail_buttons" /> + +</LinearLayout> \ No newline at end of file
diff --git a/apps/CtsVerifier/res/raw/cacert.der b/apps/CtsVerifier/res/raw/cacert.der new file mode 100644 index 0000000..3934e1b --- /dev/null +++ b/apps/CtsVerifier/res/raw/cacert.der Binary files differ
diff --git a/apps/CtsVerifier/res/raw/next_axis.mp3 b/apps/CtsVerifier/res/raw/next_axis.mp3 new file mode 100644 index 0000000..0a3174d --- /dev/null +++ b/apps/CtsVerifier/res/raw/next_axis.mp3 Binary files differ
diff --git a/apps/CtsVerifier/res/raw/stereo_mono_white_noise_48.mp3 b/apps/CtsVerifier/res/raw/stereo_mono_white_noise_48.mp3 new file mode 100644 index 0000000..e877fc1 --- /dev/null +++ b/apps/CtsVerifier/res/raw/stereo_mono_white_noise_48.mp3 Binary files differ
diff --git a/apps/CtsVerifier/res/raw/usercert.der b/apps/CtsVerifier/res/raw/usercert.der new file mode 100644 index 0000000..cdfb8f7 --- /dev/null +++ b/apps/CtsVerifier/res/raw/usercert.der Binary files differ
diff --git a/apps/CtsVerifier/res/raw/userkey.der b/apps/CtsVerifier/res/raw/userkey.der new file mode 100644 index 0000000..31f1f8c --- /dev/null +++ b/apps/CtsVerifier/res/raw/userkey.der Binary files differ
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml index 1444723..9277782 100644 --- a/apps/CtsVerifier/res/values/strings.xml +++ b/apps/CtsVerifier/res/values/strings.xml
@@ -22,6 +22,7 @@ <string name="info_button_text">Info</string> <string name="fail_button_text">Fail</string> <string name="next_button_text">Next</string> + <string name="go_button_text">Go</string> <!-- Strings for TestListActivity --> <string name="test_category_audio">Audio</string> @@ -43,6 +44,7 @@ <string name="test_results_cleared">Test results cleared.</string> <string name="view">View</string> <string name="test_results_error">Couldn\'t create test results report.</string> + <string name="runtime_permissions_error">Cannot continue. Please grant runtime permissions</string> <string name="export">Export</string> <string name="no_storage">Cannot save report to external storage, see log for details.</string> <string name="report_saved">Report saved to: %s</string> @@ -126,6 +128,24 @@ <string name="da_lock_success">It appears the screen was locked successfully!</string> <string name="da_lock_error">It does not look like the screen was locked...</string> + <!-- Strings for lock bound keys test --> + <string name="sec_lock_bound_key_test">Lock Bound Keys Test</string> + <string name="sec_lock_bound_key_test_info"> + This test ensures that Keystore cryptographic keys that are bound to lock screen authentication + are unusable without a recent enough authentication. You need to set up a screen lock in order to + complete this test. If available, this test should be run by using fingerprint authentication + as well as PIN/pattern/password authentication. + </string> + <string name="sec_fingerprint_bound_key_test">Fingerprint Bound Keys Test</string> + <string name="sec_fingerprint_bound_key_test_info"> + This test ensures that Keystore cryptographic keys that are bound to fingerprint authentication + are unusable without an authentication. You need to set up a fingerprint order to + complete this test. + </string> + <string name="sec_fp_dialog_message">Authenticate now with fingerprint</string> + <string name="sec_fp_auth_failed">Authentication failed</string> + <string name="sec_start_test">Start Test</string> + <!-- Strings for BluetoothActivity --> <string name="bluetooth_test">Bluetooth Test</string> <string name="bluetooth_test_info">The Bluetooth Control tests check whether or not the device @@ -298,6 +318,55 @@ <string name="empty"></string> + <!-- Strings for HifiUltrasoundTestActivity --> + <string name="hifi_ultrasound_test">Hifi Ultrasound Microphone Test</string> + <string name="hifi_ultrasound_test_info"> + This is a test for near-ultrasound (18500Hz - 20000Hz) microphone response.\n + This test requires two devices.\n</string> + <string name="hifi_ultrasound_test_play">PLAY</string> + <string name="hifi_ultrasound_test_record">RECORD</string> + <string name="hifi_ultrasound_test_plot">PLOT</string> + <string name="hifi_ultrasound_test_dismiss">DISMISS</string> + <string name="hifi_ultrasound_test_ok">OK</string> + <string name="hifi_ultrasound_test_instruction1"> + Open Hifi Ultrasound Microphone Test on the test device and the reference device.\n + Set the media volume of the reference device at 70% and hold it with one hand.\n + Hold the testing device with the other hand\n + Press the RECORD button on the testing device, then the PLAY button on the reference device within one second.\n + After the test, report result on the testing (recording) device.\n</string> + <string name="hifi_ultrasound_test_pass">PASS</string> + <string name="hifi_ultrasound_test_fail">FAIL</string> + <string name="hifi_ultrasound_test_default_false_string">false</string> + <string name="hifi_ultrasound_test_mic_no_support"> + Device does not support near-ultrasound recording.\n + All new phones and tablets MUST support near-ultrasound recording.\n + Report FAIL if this is a new device, report PASS if this is an updating device.\n</string> + <string name="hifi_ultrasound_test_spkr_no_support"> + Device does not support near-ultrasound playback.\n + If this is your reference device, please use a different reference device.\n</string> + + <string name="hifi_ultrasound_speaker_test">Hifi Ultrasound Speaker Test</string> + <string name="hifi_ultrasound_speaker_test_info"> + This is a test for near-ultrasound (18500Hz - 20000Hz) speaker response.\n + This test requires two devices.\n</string> + <string name="hifi_ultrasound_speaker_test_instruction1"> + Open Hifi Ultrasound Speaker Test on the test device and the reference device.\n + Set the media volume of the testing device at 70% and hold it with one hand.\n + Hold the reference device with the other hand\n + Press the RECORD button on the reference device, then the PLAY button on the testing device within one second.\n + After the test, report result on the testing (playback) device.\n</string> + <string name="hifi_ultrasound_speaker_test_mic_no_support"> + Device does not support near-ultrasound recording.\n + If this is your reference device, please use a different reference device.\n</string> + <string name="hifi_ultrasound_speaker_test_spkr_no_support"> + Device does not support near-ultrasound playback.\n + All new phones and tablets MUST support near-ultrasound playback.\n + Report FAIL if this is a new device, report PASS if this is an updating device.\n</string> + <string name="hifi_ultrasound_speaker_test_test_side"> + Please wait for the result on the reference device then report here.</string> + <string name="hifi_ultrasound_speaker_test_reference_side"> + Please report on the testing device.\n</string> + <!-- Strings for Location tests --> <string name="location_gps_test">GPS Test</string> <string name="location_gps_test_info">This test verifies basic GPS behavior @@ -331,6 +400,7 @@ <string name="nfc_pee_2_pee">Peer-to-Peer Data Exchange</string> <string name="nfc_ndef_push_sender">NDEF Push Sender</string> <string name="nfc_ndef_push_receiver">NDEF Push Receiver</string> + <string name="nfc_llcp_version_check">LLCP version check</string> <string name="nfc_tag_verification">Tag Verification</string> <string name="nfc_ndef">NDEF</string> @@ -352,6 +422,13 @@ <string name="nfc_ndef_push_receive_failure">Failed to receive the correct NDEF push message.</string> + <string name="nfc_llcp_version_check_info">This test requires two candidate devices + with NFC enabled to exchange P2P messages. Start the \"LLCP version check\" test on + the other candidate device also, and touch the devices back to back. This test + then verifies that the candidate device correctly advises the LLCP version as 1.2</string> + <string name="nfc_llcp_version_check_failure">The candidate devices does not report LLCP + version 1.2 or higher.</string> + <string name="nfc_llcp_version_check_success">The candidate device has a valid LLCP version.</string> <string name="nfc_tag_verifier">NFC Tag Verifier</string> <string name="nfc_tag_verifier_info">Follow the on-screen instructions to write and read a tag of the chosen technology.</string> @@ -496,6 +573,8 @@ <string name="snsr_test_skipped">SKIPPED</string> <string name="snsr_test_fail">FAIL</string> <string name="snsr_execution_time">Test execution time %1$s sec</string> + <string name="snsr_rvcvxchk_test">Rotation Vector CV XCheck</string> + <string name="snsr_rvcvxchk_test_rec">Rotation Vector CV XCheck Recording</string> <!-- Strings to interact with users in Sensor Tests --> <string name="snsr_test_play_sound">A sound will be played once the verification is complete...</string> @@ -600,6 +679,14 @@ <string name="snsr_step_counter_event">%1$d | Step Counter event. count=%2$d.</string> <string name="snsr_step_detector_event">%1$d | Step Detector event.</string> + <!-- Device suspend tests --> + <string name="snsr_device_suspend_test">Device Suspend Tests</string> + <string name="snsr_device_did_not_go_into_suspend">Device did not go into suspend mode during test execution </string> + <string name="snsr_batch_did_not_arrive_at_expected_time">Batch did not arrive at the expected time estimatedBatchArrivalMs=%1$d + firstEventReceivedMs=%2$d diffMs=%3$d toleranceMs=%4$d </string> + <string name="snsr_device_suspend_test_instr">One you begin the test, disconnect USB, turn off the display and allow + the device to go into suspend mode. The screen will turn on and a sound will be played once all the tests are completed.</string> + <!-- Significant Motion --> <string name="snsr_significant_motion_test">Significant Motion Tests</string> <string name="snsr_significant_motion_event_arrival">Event expected to trigger. Triggered=%1$s.</string> @@ -614,6 +701,9 @@ <string name="snsr_significant_motion_test_deactivation">Once you begin the test, you will need to walk to ensure Significant Motion triggers only once.</string> <string name="snsr_significant_motion_registration">Expected to be able to register for TriggerSensor. Found=%1$b.</string> <string name="snsr_significant_motion_cancelation">Expected to be able to cancel TriggerSensor. Found=%b.</string> + <string name="snsr_significant_motion_ap_suspend">One you begin the test, disconnect USB, turn off the display and allow the device to go into suspend. + You will need to walk to ensure that Significant Motion triggers. The screen will turn on and a sound will be played once the test completes.</string> + <string name="snsr_device_did_not_wake_up_at_trigger">Device did not wakeup at tigger time. wakeTime=%1$d ms triggerTime=%2$d ms</string> <!-- Strings for Sensor CTS tests inside CtsVerifier --> <string name="snsr_single_sensor_tests">CTS Single Sensor Tests</string> @@ -636,18 +726,6 @@ <string name="congratulations">Congratulations!</string> <string name="no_suid_files">No unauthorized suid files detected!</string> - <!-- Strings for Camera Analyzer --> - <string name="camera_analyzer">Camera Analyzer</string> - <string name="ca_find_checkerboard_label">Find target</string> - <string name="ca_check_formats_label">Output formats</string> - <string name="ca_exposure_test_label">Exposure Comp.</string> - <string name="ca_result_label">Results will be here</string> - <string name="ca_wb_test_label">White Balance</string> - <string name="ca_lock_test_label">AE Lock</string> - <string name="ca_metering_label">Metering Area</string> - <string name="ca_focus_modes_label">Focus Modes</string> - <string name="ca_info">This test checks the image quality of the camera of this device. It requires a MacBeth 4x6 color checker. With an ADK board and a lamp connected to it on the Relay 1 port, all tests can be run automatically. Without the ADK board, all the tests except the Auto Exposure Lock Test can be run automatically and the Auto Exposure Lock Test will require users to turn on/off a lamp according to the instruction given. </string> - <!-- Strings for Camera Orientation --> <string name="camera_orientation">Camera Orientation</string> <string name="co_info">This test verifies the orientation capabilities of @@ -815,6 +893,25 @@ <string name="its_test_passed">All Camera ITS tests passed. Pass button enabled!</string> <string name="its_test_failed">Some Camera ITS tests failed.</string> + <!-- Strings for the Camera Flashlight test activity --> + <string name="camera_flashlight_test">Camera Flashlight</string> + <string name="camera_flashlight_info"> + This test checks the flashlight functionality. It will turn on and off the flashlight of + each camera device that has a flash unit. Follow the instructions on screen and observe the + flashlight status changing. + </string> + <string name="camera_flashlight_start_button">Start</string> + <string name="camera_flashlight_next_button">Next</string> + <string name="camera_flashlight_done_button">Done</string> + <string name="camera_flashlight_on_button">On</string> + <string name="camera_flashlight_off_button">Off</string> + <string name="camera_flashlight_start_text">Press Start to start flashlight test.</string> + <string name="camera_flashlight_question_text">Is Camera %1$s flashlight on or off?</string> + <string name="camera_flashlight_next_text">Ok. Press next.</string> + <string name="camera_flashlight_failed_text">Test failed. Press Done or Fail button.</string> + <string name="camera_flashlight_passed_text">All tests passed. Press Done or Pass button. + </string> + <!-- Strings for StreamingVideoActivity --> <string name="streaming_video">Streaming Video Quality Verifier</string> <string name="streaming_video_info">This is a test for assessing the quality of streaming videos. Play each stream and verify that the video is smooth and in sync with the audio, and that there are no quality problems.</string> @@ -1001,13 +1098,12 @@ respecting user preferences about notification ranking and filtering. </string> <string name="attention_ready">I\'m done</string> - <string name="attention_filter_all">Please set the notification filter to \"All\" in the dialog - that appears when you change the device\'s volume.</string> - <string name="attention_filter_priority">Please set the notification filter to \"Priority\" in - the dialog that appears when you change the device\'s volume, and allow messages from - starred contacts.</string> - <string name="attention_filter_none">Please set the notification filter to \"None\" in the dialog - that appears when you change the device\'s volume.</string> + <string name="attention_filter_all">Please disable \"Do not disturb\" by tapping the Quick Settings tile.</string> + <string name="attention_filter_priority">Please select \"Priority only\" in the dialog that appears + when you tap the \"Do not disturb\" tile in Quick Settings, and customize the setting to allow messages from + starred contacts only by tapping "More settings".</string> + <string name="attention_filter_none">Please select \"Total silence\" in the dialog that appears + when you tap the \"Do not disturb\" tile in Quick Settings.</string> <string name="attention_create_contacts">Create contacts for notification annotations.</string> <string name="attention_delete_contacts">Delete test contacts.</string> <string name="attention_default_order">Check that ranker defaults to time order.</string> @@ -1109,6 +1205,23 @@ <string name="caboot_reboot_desc">Please reboot the device and return to this test.</string> <string name="caboot_after_boot">AFTER REBOOTING: Check that there is a notification that the network may be monitored. Opening that notification should show a dialog box giving more information, with a button to check trusted credentials. This should open up the same view of trusted credentials that you get via the "Check credentials" button.</string> + <!-- Strings for KeyChain --> + <string name="keychain_test">KeyChain Storage Test</string> + <string name="keychain_info">This test checks that credentials installed to the system can be granted, retrieved, and used to create valid HTTPS connections.</string> + <string name="keychain_reset">Reset</string> + <string name="keychain_skip">Skip</string> + <string name="keychain_setup_desc">The first step sets up an internal KeyStore and generates credentials to use for the remainder of the test.\n\n + Touch \'Next\' to begin.</string> + <string name="keychain_install_desc">Credentials generated. Touch \'Next\' to install them to the system keychain.\n\n +The container for the credentials will not be protected with a password; if prompted for one, leave that field blank.\n\n +During installation you may be prompted for a name - accept the default suggestion.\n\n +In the case that these credentials were already installed, you may skip this step.</string> + <string name="keychain_https_desc">The last test involves setting up an HTTPS connection using credentials from the KeyChain.\n\n +You should be prompted to select credentials; choose the ones you just installed in the previous step.</string> + <string name="keychain_reset_desc">Before marking this test as passed, touch \'Next\' to open security settings and reset the following items:\n + 1. Clear device credentials.\n + 2. Change the lock screen type to \'None\'.</string> + <!-- Strings for Widget --> <string name="widget_framework_test">Widget Framework Test</string> <string name="widget_framework_test_info">This test checks some basic features of the widget @@ -1166,6 +1279,23 @@ <string name="provisioning_byod_capture_media_error">Error while capturing media from managed profile.</string> <string name="provisioning_byod_capture_image_error">Error while capturing image from managed profile.</string> + <string name="provisioning_byod_auth_bound_key">Autentication-boud keys</string> + <string name="provisioning_byod_auth_bound_key_info"> + This test verifies keystore cryptographic keys can be bound to device credentials. + These keys should only be available if there was a recent enough authentication. + </string> + <string name="provisioning_byod_auth_bound_key_instruction"> + This test verifies keystore cryptographic keys can be bound to device lockscreen challenge or fingerprints (if available). + These keys should only be available if there was a recent enough authentication. \n + + 1. Press "Set up" to open Security settings. Create a lockscreen password and if available, enroll a fingerprint.\n + 2. Go through the list of tests.\n + 3. Mark the overall test pass or fail.\n + 4. Once the set of tests are completed, remove the lockscreen challenge. + </string> + <string name="provisioning_byod_auth_bound_key_set_up">Set up</string> + <string name="provisioning_byod_lockscreen_bound_key">Lockscreen-bound key test</string> + <string name="provisioning_byod_fingerprint_bound_key">Fingerprint-bound key test</string> <!-- Strings for DeskClock --> <string name="deskclock_tests">Alarms and Timers Tests</string> <string name="deskclock_tests_info"> @@ -1294,9 +1424,11 @@ <string name="snsr_rotation_vector_set_final">Place the device back to the reference position.</string> <string name="snsr_rotation_vector_verification">Angular deviation [%1$4.1f %2$4.1f %3$4.1f]. Current: %4$f deg. Max tolerated: %5$f.</string> + <!-- Strings common for BYOD and DO managed provisioning tests. --> + <string name="afw_device_admin">CTS Verifier - AfW Admin</string> + <!-- Strings for BYOD managed provisioning tests (ByodFlowTestActivity) --> <string name="test_category_managed_provisioning">Managed Provisioning</string> - <string name="provisioning_byod_device_admin">CTS Verifier - BYOD Admin</string> <string name="provisioning_byod">BYOD Managed Provisioning</string> <string name="provisioning_byod_info"> This test exercises the BYOD managed provisioning flow. @@ -1322,12 +1454,13 @@ <string name="provisioning_byod_profile_visible">Profile-aware accounts settings</string> <string name="provisioning_byod_admin_visible">Profile-aware device administrator settings</string> <string name="provisioning_byod_workapps_visible">Badged work apps visible in Launcher</string> - <string name="provisioning_byod_cross_profile">Open app cross profiles</string> - <string name="provisioning_byod_cross_profile_app_personal"> - You selected the CTS Verifier option. - </string> + <string name="provisioning_byod_cross_profile_from_personal">Open app cross profiles from the personal side</string> + <string name="provisioning_byod_cross_profile_from_work">Open app cross profiles from the work side</string> + <string name="provisioning_app_linking">App links from the work side</string> + <string name="provisioning_byod_cross_profile_app_personal">You selected the personal option.</string> <string name="provisioning_byod_cross_profile_app_work">You selected the Work option.</string> - <string name="provisioning_byod_cross_profile_instruction"> + <string name="provisioning_byod_cross_profile_app_ctsverifier"> You selected the ctsverifier option </string> + <string name="provisioning_byod_cross_profile_from_personal_instruction"> Please press the Go button to start an action.\n \n You should be asked to choose either \"CTS Verifier\" or \"Work\" to complete the action. @@ -1335,6 +1468,65 @@ \n Verify that you are prompted with the above choices and both options work as intended. Then mark this test accordingly. </string> + <string name="provisioning_byod_cross_profile_from_work_instruction"> + Please press the Go button to start an action.\n + \n + You should be asked to choose either \"CTS Verifier\" or \"Personal\" to complete the action. + Pressing either should bring up a page stating your choice.\n + \n + Verify that you are prompted with the above choices and both options work as intended. Then mark this test accordingly. + </string> + <string name="provisioning_byod_app_linking_instruction"> + Please press the Go button to start an action.\n + \n + You should be asked to choose either \"CTS Verifier\" or \"Personal\" to complete the action.\n + - If you choose \"CTS Verifier\", you should see a page stating your chose \"CTS Verifier\".\n + - If you choose \"Personal\", you should be presented with another dialog between \"CTS Verifier\" + and some other apps. In this case, you should choose \"CTS verifier\".\n + You should then see a page stating you chose \"Personal\".\n + \n + Verify that you are prompted with the above choices and both options work as intended. Then mark this test accordingly. + </string> + <string name="provisioning_byod_keyguard_disabled_features">Keyguard disabled features</string> + <string name="provisioning_byod_keyguard_disabled_features_info"> + This test exercises Keyguard Disabled Features. Follow instructions above. + </string> + <string name="provisioning_byod_keyguard_disabled_features_instruction"> + Please go to Settings > Security > Device administrators and set + \"CTS Verifier - AfW Admin\" as active admin.\n + After that please press the \"Prepare test\" button to disable trust agents.\n + Then please press through the following verification steps.\n + Note: Device password will be set to \"testpassword\". After leaving the screen device + password and active admin status will be cleared. + </string> + <string name="provisioning_byod_keyguard_disabled_features_prepare_button">Prepare test</string> + <string name="provisioning_byod_keyguard_disabled_features_not_admin">CtsVerifier is not active admin. Please follow instructions.</string> + <string name="provisioning_byod_disable_trust_agents">Disable trust agents</string> + <string name="provisioning_byod_disable_trust_agents_instruction"> + Please press the Go button to go to Settings > Security. Then go to Trusted agents and\n + check if the agents are shown as disabled by the administrator. + Then please press Back and mark the test as \"Pass\" or \"Fail\". + </string> + <string name="provisioning_byod_fingerprint_disabled_in_settings">Fingerprint is disabled in Settings</string> + <string name="provisioning_byod_fingerprint_disabled_in_settings_instruction"> + Please press the Go button to go to Settings > Security. Then go to Fingerprint and\n + check if the screen is shown as disabled by the administrator. + Then please press Back and mark the test as \"Pass\" or \"Fail\". + </string> + <string name="provisioning_byod_disable_fingerprint">Fingerprint disabled on keyguard</string> + <string name="provisioning_byod_disable_fingerprint_instruction"> + Please press the Go button to lock the screen. Then try to log in using the fingerprint reader.\n + Expected result is you cannot log in using your fingerprint.\n + After you log back in, please navigate back to CtsVerifier and mark the test as \"Pass\" or \"Fail\". + </string> + <string name="provisioning_byod_disable_notifications">Notifications disabled on keyguard</string> + <string name="provisioning_byod_disable_notifications_instruction"> + Please press the Go button to lock the screen. Wait a couple of seconds and look out for a + notification from CtsVerifier.\n + Expected result is the notification is shown as \"Contents hidden\", you can not see the contents + (Which would read \"This is a work notification\").\n + After you log back in, please navigate back to CtsVerifier and mark the test as \"Pass\" or \"Fail\". + </string> <string name="provisioning_byod_work_notification">Work notification is badged</string> <string name="provisioning_byod_work_notification_instruction"> Please press the Go button to trigger a notification.\n @@ -1342,6 +1534,32 @@ Verify that the notification is badged (see sample badge below). Then mark this test accordingly. </string> <string name="provisioning_byod_work_notification_title">This is a work notification</string> + <string name="provisioning_byod_work_status_icon">Work status icon is displayed</string> + <string name="provisioning_byod_work_status_icon_instruction"> + Verify that the current status bar does not have a work status icon (see sample icon below). + \n\n + Please press the Go button to launch a work activity. + \n\n + Verify that the status bar now has a work status icon. Then mark this test accordingly. + </string> + <string name="provisioning_byod_work_status_icon_activity"> + Verify that the current status bar has a work status notification. + \n\n + Please press finish to return to the tests and then mark this test accordingly. + </string> + <string name="provisioning_byod_work_status_toast">Work status toast is displayed</string> + <string name="provisioning_byod_work_status_toast_instruction"> + Please press the Go button to launch a work activity. + \n\n + Follow instructions and then return and mark this test accordingly. + </string> + <string name="provisioning_byod_work_status_toast_activity"> + Turn off the screen and wait a few seconds then turn on the screen again. + \n\n + Verify that a toast was displayed saying you are in the work profile. + \n\n + Please press finish to return to the tests and then mark this test accordingly. + </string> <string name="provisioning_byod_profile_visible_instruction"> Please press the Go button to open the Settings page. Navigate to Accounts and confirm that:\n @@ -1349,6 +1567,10 @@ - Both Personal and Work categories exist.\n - \"Remove work profile\" exists under the Work category.\n \n + Furthermore, hit the action overflow button (3 dots) and verify that:\n + - There are two auto-sync options present, one for personal and one for work data.\n + - De-selecting either option prompts a warning dialog.\n + \n Use the Back button to return to this page. </string> <string name="provisioning_byod_admin_visible_instruction"> @@ -1356,7 +1578,7 @@ Navigate to Device administrators and confirm that:\n \n - Both Personal and Work categories exist.\n - - \"CTS Verifier - BYOD Admin\" exists under the Work category, and is activated.\n + - \"CTS Verifier - AfW Admin\" exists under the Work category, and is activated.\n \n Use the Back button to return to this page. </string> @@ -1389,6 +1611,29 @@ Then use the Back button to return to this test and mark accordingly. </string> + <string name="provisioning_byod_battery_settings">Profile-aware battery settings</string> + <string name="provisioning_byod_battery_settings_instruction"> + Please press the Go button to open Battery page in settings.\n + \n + Verify that Battery page shows both badged and unbadged apps in the usage list.\n + \n + Note that the usage list only displays usage since last charge, + so you may need to unplug your device and use a badged and unbadged app + for a little while before they will appear in the list.\n + \n + Then use the Back button to return to this test and mark accordingly. + </string> + + <string name="provisioning_byod_data_usage_settings">Profile-aware data usage settings</string> + <string name="provisioning_byod_data_usage_settings_instruction"> + Please press the Go button to open the Settings page.\n + \n + Navigate to Data usage page and confirm that it includes a Work profile section, + and that tapping it shows just work profile data usage.\n + \n + Then use the Back button to return to this test and mark accordingly. + </string> + <string name="provisioning_byod_cred_settings">Profile-aware trusted credential settings</string> <string name="provisioning_byod_cred_settings_instruction"> Please press the Go button to open the Security settings. @@ -1410,6 +1655,8 @@ Then use the Back button to return to this test and mark accordingly. </string> + <string name="provisioning_byod_cross_profile_intent_filters">Cross profile intent filters are set</string> + <string name="provisioning_byod_nfc_beam">Disable Nfc beam</string> <string name="provisioning_byod_nfc_beam_allowed_instruction"> Please press the Go button to test if Nfc beam can be triggered in the work profile.\n @@ -1431,11 +1678,11 @@ <string name="provisioning_byod_send_share_intent">Send share intent</string> <string name="provisioning_byod_cannot_resolve_beam_activity">Cannot find beam activity</string> + <string name="test_failed_cannot_start_intent">Cannot start the given intent.</string> <string name="provisioning_byod_no_activity">Cannot communicate with activity in the work profile.</string> <string name="provisioning_byod_delete_profile">Initiate deletion of work profile.</string> <string name="provisioning_byod_profile_deleted">Work profile deleted.</string> <string name="provisioning_byod_disabled">Device provisioning is not enabled.</string> - <string name="provisioning_byod_go">Go</string> <string name="provisioning_button_finish">Finish</string> <string name="provisioning_cross_profile_chooser">Choose an app to complete action</string> @@ -1447,6 +1694,165 @@ <string name="device_owner_negative_test">Device owner negative test</string> <string name="device_owner_negative_test_info">Please click the "Start provisioning" button, and when you see a warning dialog telling the device is already set up, select "pass". Otherwise, select "fail".</string> <string name="start_device_owner_provisioning_button">Start provisioning</string> + <string name="positive_device_owner">Device Owner Tests</string> + <string name="device_owner_positive_tests">Device Owner positive tests</string> + <string name="device_owner_positive_tests_instructions"> + The positive device owner tests verify policies on a corporate owned device.\n + Press below button first, follow steps described in the dialog that pops up, + then proceed to the test cases.\n + Pressing \'back\', \'pass\' or \'fail\' on this test page will remove the device owner.\n + Alternatively, you can run the \'Remove device owner\' test. Ideally, that test should + be run last so that it does not interfere with other tests. + </string> + <string name="device_owner_positive_tests_info"> + The positive device owner tests verify policies on a corporate owned device.\n + Press below button first, follow steps described in the dialog that pops up, + then proceed to the test cases.\n + Pressing \'back\', \'pass\' or \'fail\' on this test page will remove the device owner.\n + Alternatively, you can run the \'Remove device owner\' test. Ideally, that test should + be run last so that it does not interfere with other tests. + </string> + <string name="device_owner_positive_category">Device Owner Tests</string> + <string name="set_device_owner_button_label">Set up device owner</string> + <string name="set_device_owner_dialog_title">Set up device owner</string> + <string name="set_device_owner_dialog_text"> + Please set the device owner by enabling USB debugging on the device and issuing the following command on the host:\n + adb shell dpm set-device-owner \'com.android.cts.verifier/com.android.cts.verifier.managedprovisioning.DeviceAdminTestReceiver\' + </string> + <string name="device_owner_remove_device_owner_test">Remove device owner</string> + <string name="device_owner_remove_device_owner_test_info"> + Please check in Settings > Security > Device Administrators if CTSVerifier is + Device Owner. Then press the button below, and check that CTSVerifier is NOT Device + Owner anymore. + </string> + <string name="remove_device_owner_button">Remove device owner</string> + <string name="device_owner_check_device_owner_test">Check device owner</string> + <string name="device_owner_incorrect_device_owner">Missing or incorrect device owner: CTSVerifier is not DO!</string> + <string name="device_owner_wifi_lockdown_test">WiFi configuration lockdown</string> + <string name="device_owner_wifi_lockdown_info"> + Please enter the SSID and auth method of an available WiFi Access Point and press the button to create a + WiFi configuration. This configuration can be seen on Settings > WiFi. The test cases + are going use this config. Please go through test cases in order (from top to bottom). + </string> + <string name="switch_wifi_lockdown_off_button">WiFi config lockdown off</string> + <string name="switch_wifi_lockdown_on_button">WiFi config lockdown on</string> + <string name="wifi_lockdown_go_settings_wifi_button">Go to WiFi Settings</string> + <string name="device_owner_wifi_key_management_none_button">None</string> + <string name="device_owner_wifi_key_management_wpa_button">WPA</string> + <string name="device_owner_wifi_key_management_wep_button">WEP</string> + <string name="create_wifi_config_button_label">Create WiFi configuration</string> + <string name="wifi_lockdown_add_network_failed_dialog_title">WiFi configuration could not be created</string> + <string name="wifi_lockdown_add_network_failed_dialog_text"> + There was an error during creation of WiFi configuration. Check if WiFi is switched on. + </string> + <string name="device_owner_wifi_config_unlocked_modification_test">Unlocked config is modifiable in Settings</string> + <string name="device_owner_wifi_config_unlocked_modification_test_info"> + Please press the button to ensure WiFi config lockdown is NOT in effect. Then go to + Settings > WiFi and see if the CTSVerifier created WiFi configuration can be edited. + Please make sure you can connect to it. The test is successful if the config is editable + and can be connected to. + </string> + <string name="device_owner_wifi_config_locked_modification_test">Locked config is not modifiable in Settings</string> + <string name="device_owner_wifi_config_locked_modification_test_info"> + Please press the button to ensure WiFi config lockdown is in effect. Then go to + Settings > WiFi and see if the CTSVerifier created WiFi configuration can NOT be edited + or removed. The test is successful if the config is NOT modifiable. + </string> + <string name="device_owner_wifi_config_locked_connection_test">Locked config can be connected to</string> + <string name="device_owner_wifi_config_locked_connection_test_info"> + Please press the button to ensure WiFi config lockdown is in effect. Then go to + Settings > WiFi and see if the CTSVerifier created WiFi configuration can be connected + to manually. The test is successful if the connection can be established. + </string> + <string name="device_owner_wifi_config_unlocked_removal_test">Unlocked config can be forgotten in Settings</string> + <string name="device_owner_wifi_config_unlocked_removal_test_info"> + Please press the button to ensure WiFi config lockdown is NOT in effect. Then go to + Settings > WiFi and see if the CTSVerifier created WiFi configuration can be forgotten. + The test is successful if the config could be forgotten and is removed from the list of saved configs. + </string> + <string name="device_owner_disable_statusbar_test">Disable status bar</string> + <string name="device_owner_disable_statusbar_test_info"> + Please press the below button to disable the status bar and verify that quick settings, notifications + and the assist gesture are no longer available.\n + Next, press the button to reenable the status bar and verify that quick settings, notification + and the assist gesture are available again.\n + Please mark the test accordingly. + </string> + <string name="device_owner_disable_statusbar_button">Disable status bar</string> + <string name="device_owner_reenable_statusbar_button">Reenable status bar</string> + <string name="device_owner_disable_keyguard_test">Disable keyguard</string> + <string name="device_owner_disable_keyguard_test_info"> + Note that any device passwords that you might have set will be deleted during this test.\n + Please press the below button to disable the keyguard. Press the power button on your device to + switch off the screen. Then press the power button to switch the screen back on and verify that + no keyguard was shown.\n + Next, press the button to reenable the keyguard and repeat the above steps, this time verifying that + a keyguard was shown again.\n + Please mark the test accordingly. + </string> + <string name="device_owner_disable_keyguard_button">Disable keyguard</string> + <string name="device_owner_reenable_keyguard_button">Reenable keyguard</string> + <string name="device_profile_owner_permission_lockdown_test">Permissions lockdown</string> + <string name="device_profile_owner_permission_lockdown_test_instructions"> + Select each of the three grant states for the permission shown below in turn.\n + Now open application settings, select Permissions, and verify if the following behaviour is observed.\n + <b>Allow:</b> Permission is granted to the app and cannot be changed through the settings UI.\n + <b>Let user decide:</b> Permission state can be changed through the settings UI.\n + <b>Deny:</b> Permission is denied to the app and cannot be changed through the settings UI.\n + Please mark the test accordingly. + </string> + <string name="device_owner_permission_lockdown_test_info"> + This test checks if the permissions state in settings UI is locked down according to the state set by the device owner. + </string> + <string name="profile_owner_permission_lockdown_test_info"> + <b> + Before proceeding, check if com.android.cts.permissionapp (aka CtsPermissionApp) is installed in work profile by going to Settings > Apps. If not, please install the app before proceeding.\n\n + </b> + This test checks if the permissions state in settings UI is locked down correctly depending on the state set by the profile owner. + </string> + <string name="package_not_found">You must install %s (aka CtsPermissionApp).</string> + <string name="permission_allow">Grant</string> + <string name="permission_default">Let user decide</string> + <string name="permission_deny">Deny</string> + <string name="not_profile_owner">%s is not profile owner.</string> + <string name="not_device_owner">%s is not device owner.</string> + <string name="activity_not_found">No activity found to handle intent: %s</string> + <string name="open_settings_button_label">Open Application Settings</string> + <string name="finish_button_label">Finish</string> + <string name="device_owner_device_admin_visible">Device administrator settings</string> + <string name="device_owner_device_admin_visible_info"> + Please press the Go button to open the Security page in Settings. + Navigate to Device administrators and confirm that:\n + \n + - \"CTS Verifier - AfW Admin\" exists and is activated.\n + - \"CTS Verifier - AfW Admin\" cannot be disabled.\n + \n + Use the Back button to return to this page. + </string> + <string name="device_owner_disallow_config_bt">Disallow configuring Bluetooth</string> + <string name="device_owner_disallow_config_bt_info"> + Please press the Set restriction button to set the user restriction. + Then press Go to open the Bluetooth page in Settings. + Confirm that:\n + \n + - You cannot view Bluetooth devices in range.\n + - You cannot edit, add or remove any already paired devices.\n + \n + Use the Back button to return to this page. + </string> + <string name="device_owner_disallow_config_wifi">Disallow configuring WiFi</string> + <string name="device_owner_disallow_config_wifi_info"> + Please press the Set restriction button to set the user restriction. + Then press Go to open the WiFi page in Settings. + Confirm that:\n + \n + - You cannot view WiFi networks in range.\n + - You cannot edit, add or remove any existing WiFi configs.\n + \n + Use the Back button to return to this page. + </string> + <string name="device_owner_user_restriction_set">Set restriction</string> + <string name="device_owner_settings_go">Go</string> <!-- Strings for JobScheduler Tests --> <string name="js_test_description">This test is mostly automated, but requires some user interaction. You can pass this test once the list items below are checked.</string> @@ -1508,7 +1914,6 @@ Do you see the programs named \"Dummy Program\" and their descriptions "Dummy Program Description" in the EPG? </string> - <string name="tv_input_discover_test_yes">Yes</string> <string name="tv_parental_control_test">TV app parental controls test</string> <string name="tv_parental_control_test_info"> @@ -1562,6 +1967,59 @@ The Spanish audio track should be selected. </string> + <string name="tv_time_shift_test">TV app time shift test</string> + <string name="tv_time_shift_test_info"> + This test verifies that the TV app invokes proper time shift APIs in the framwork. + </string> + <string name="tv_time_shift_test_pause_resume"> + Press the \"Launch TV app\" button. Verify that the playback control is available. + Pause the playback and then resume it. + </string> + <string name="tv_time_shift_test_verify_resume_after_pause"> + The playback should be resumed after pause. + </string> + <string name="tv_time_shift_test_verify_position_tracking"> + The playback position tracking should be activated. + </string> + <string name="tv_time_shift_test_speed_rate"> + Press the \"Launch TV app\" button. Verify that the playback control is available. + Rewind the playback and in a few seconds fast-forward it. + </string> + <string name="tv_time_shift_test_verify_rewind"> + The playback should be rewinded. + </string> + <string name="tv_time_shift_test_verify_fast_forward"> + The playback should be fast-forwarded. + </string> + <string name="tv_time_shift_test_seek"> + Press the \"Launch TV app\" button. Verify that the playback control is available. + Seek to previous and then seek to next. + </string> + <string name="tv_time_shift_test_verify_seek_to_previous"> + The playback position should be moved to the previous position. + </string> + <string name="tv_time_shift_test_verify_seek_to_next"> + The playback position should be moved to the next position. + </string> + + <string name="tv_app_link_test">TV app app-link test</string> + <string name="tv_app_link_test_info"> + Verify that the bundled TV app supports linking to channel apps. If TV input service provides + links for its specific channels, TV app should show the links in a proper format. + </string> + <string name="tv_app_link_test_select_app_link"> + Select the \"Launch TV app\" button, then check if you can see a menu with \"Cts App-Link Text\" + text in red background. If you see the link, select it to follow the link. + </string> + <string name="tv_app_link_test_verify_link_clicked"> + The app-link must have been clicked and the activity should be changed correctly. + </string> + <string name="tv_input_link_test_verify_link_interface"> + Do you see the app-link card similar to the image on the left?\n + 1) You should see the poster art image, but the color could be differ.\n + 2) You should see the text \"Cts App-Link Text\".\n + </string> + <string name="overlay_view_text">Overlay View Dummy Text</string> <string name="fake_rating">Fake</string> @@ -1581,4 +2039,116 @@ <string name="error_screen_pinning_did_not_start">Screen was not pinned.</string> <string name="error_screen_pinning_did_not_exit">Screen was not unpinned.</string> <string name="error_screen_pinning_couldnt_exit">Could not exit screen pinning through API.</string> + + <!-- Audio Devices Notifcations Test --> + <string name="audio_devices_notifications_test">Audio Devices Notifications Test</string> + <string name="audio_devices_notification_instructions"> + Click the "Clear Messages" button then connect and disconnect a wired headset. + Note if the appropriate notification messages appear below. + </string> + <string name="audio_dev_notification_clearmsgs">Clear Messages</string> + <string name="audio_dev_notification_connectMsg">CONNECT DETECTED</string> + <string name="audio_dev_notification_disconnectMsg">DISCONNECT DETECTED</string> + + <!-- Audio Routing Notifcations Test --> + <string name="audio_routingnotifications_test">Audio Routing Notifications Test</string> + <string name="audio_dev_routingnotification_instructions"> + Click on the "Play" button in the AudioTrack Routing Notifictions section below to + start (silent) playback. Insert a wired headset. Observe a message acknowledging the + rerouting event below. Remove the wired headset and observe the new routing message. + Click on the "Stop" button to stop playback.\n + Repeat the process with "Record" and "Stop" button in the AudioRecord Routing + Notifications section below. + </string> + <string name="audio_routingnotification_playBtn">Play</string> + <string name="audio_routingnotification_playStopBtn">Stop</string> + <string name="audio_routingnotification_recBtn">Record</string> + <string name="audio_routingnotification_recStopBtn">Stop</string> + <string name="audio_routingnotification_playHeader">AudioTrack Routing Notifications</string> + <string name="audio_routingnotification_recHeader">AudioRecord Routing Notifications</string> + <string name="audio_routingnotification_trackRoutingMsg">AudioTrack rerouting</string> + <string name="audio_routingnotification_recordRoutingMsg">AudioRecord rerouting</string> + + <!-- Audio Loopback Latency Test --> + <string name="audio_loopback_test">Audio Loopback Latency Test</string> + <string name="audio_loopback_info"> + This test requires the Loopback Plug. Please connect a Loopback Plug on the headset + connector, and proceed with the instructions on the screen. + The system will measure the input-output audio latency by injecting a pulse on the output, + and computing the distance between replicas of the pulse. + You can vary the Audio Level slider to ensure the pulse will feed back at adecuate levels. + Repeat until a confidence level >= 0.6 is achieved. + </string> + <string name="audio_loopback_instructions"> + Please connect a "Loopback Plug" and press "Loopback Plug Ready". + </string> + <string name="audio_loopback_plug_ready_btn">Loopback Plug Ready</string> + <string name="audio_loopback_instructions2"> + Set the audio level to a suitable value, then press Test button. + It might require multiple tries until a confidence >= 0.6 is achieved. + </string> + <string name="audio_loopback_level_text">Audio Level</string> + <string name="audio_loopback_test_btn">Test</string> + <string name="audio_loopback_results_text">Results...</string> + + <!-- Audio Frequency Line Test --> + <string name="audio_frequency_line_test">Audio Frequency Line Test</string> + <string name="audio_frequency_line_info"> + The system will measure the frequency response of the left and right line outputs, + by feeding them back thru the microphone conection with the loopback jack. + This test requires the Loopback Plug. Please connect a Loopback Plug on the headset + connector, and proceed with the instructions on the screen. + </string> + <string name="audio_frequency_line_instructions"> + Please connect a "Loopback Plug" and press "Loopback Plug Ready". + </string> + <string name="audio_frequency_line_plug_ready_btn">Loopback Plug Ready</string> + + <string name="audio_frequency_line_test_btn">Test</string> + <string name="audio_frequency_line_results_text">Results...</string> + + <!-- Audio Frequency Speaker Test --> + <string name="audio_frequency_speaker_test">Audio Frequency Speaker Test</string> + <string name="audio_frequency_speaker_info"> + This test requires an external USB reference microphone. Please connect the USB microphone and proceed with the instructions on the screen. + The system will measure frequency response of the left and right speakers (if there are two speakers), or twice the response of the mono speaker. + </string> + <string name="audio_frequency_speaker_instructions"> + Please connect an USB reference microphone and press "USB Reference microphone ready" + </string> + <string name="audio_frequency_speaker_usb_status">Waiting for USB microphone...</string> + <string name="audio_frequency_speaker_mic_ready_btn">USB Reference microphone ready</string> + <string name="audio_frequency_speaker_mic_ready_text">USB Audio device detected\n\nPlease set up Device Under test + in quiet room, and Microphone 20 cms perpendicular to center of screen, then press TEST</string> + <string name="audio_frequency_speaker_mic_not_ready_text">"No USB Audio device detected. Please reconnect."</string> + <string name="audio_frequency_speaker_test_btn">Test</string> + <string name="audio_frequency_speaker_results_text">Results...</string> + + <!-- Audio Frequency Microphone Test --> + <string name="audio_frequency_mic_test">Audio Frequency Microphone Test</string> + <string name="audio_frequency_mic_info"> + This test requires an external USB reference microphone and external speakers. + Please use the headphone connector to connect external speakers. Position the device 40 cms + from the speakers and proceed with the instructions on the screen. + The system will measure frequency response of the built in microphone. + </string> + <string name="audio_frequency_mic_instructions"> + Please connect external speakers using the headphone connector. Please unplug any USB audio device (if any) + </string> + <string name="audio_frequency_mic_speakers_ready_btn">External speakers ready</string> + <string name="audio_frequency_mic_speakers_ready_status">...</string> + <string name="audio_frequency_mic_instructions2"> + Please position the speakers 40 cms from the device under test and press TEST 1 + </string> + <string name="audio_frequency_mic_test1_btn">Test 1</string> + <string name="audio_frequency_mic_usb_status">Waiting for USB microphone...</string> + <string name="audio_frequency_mic_connect_mic">Please Connect USB microphone, position it next to + the built in microphone in the device and press USB reference microphone</string> + <string name="audio_frequency_mic_mic_ready_btn">USB Reference microphone ready</string> + <string name="audio_frequency_mic_mic_ready_text">USB Audio device detected\n\nPlease set up Device Under test + in quiet room, and Microphone 20 cms perpendicular to center of screen, then press TEST</string> + <string name="audio_frequency_mic_mic_not_ready_text">"No USB Audio device detected. Please reconnect."</string> + <string name="audio_frequency_mic_test2_btn">Test 2</string> + <string name="audio_frequency_mic_results_text">Results...</string> + </resources>
diff --git a/apps/CtsVerifier/res/xml/device_admin_byod.xml b/apps/CtsVerifier/res/xml/device_admin_byod.xml index 0408ce2..ce44794 100644 --- a/apps/CtsVerifier/res/xml/device_admin_byod.xml +++ b/apps/CtsVerifier/res/xml/device_admin_byod.xml
@@ -19,6 +19,9 @@ <uses-policies> <encrypted-storage /> <wipe-data /> + <reset-password /> + <disable-keyguard-features /> + <force-lock /> </uses-policies> </device-admin> <!-- END_INCLUDE(meta_data) -->
diff --git a/apps/CtsVerifier/res/xml/mock_tv_input_service.xml b/apps/CtsVerifier/res/xml/mock_tv_input_service.xml index 1a2cf86..d9cb867 100644 --- a/apps/CtsVerifier/res/xml/mock_tv_input_service.xml +++ b/apps/CtsVerifier/res/xml/mock_tv_input_service.xml
@@ -15,5 +15,4 @@ --> <tv-input xmlns:android="http://schemas.android.com/apk/res/android" - android:setupActivity="com.android.cts.verifier.tv.MockTvInputSetupActivity" - android:settingsActivity="com.android.cts.verifier.tv.MockTvInputSettingsActivity" /> + android:setupActivity="com.android.cts.verifier.tv.MockTvInputSetupActivity" />
diff --git a/apps/CtsVerifier/res/xml/ultrasound_line_formatter_median.xml b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_median.xml new file mode 100644 index 0000000..9c6de77 --- /dev/null +++ b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_median.xml
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<config + linePaint.strokeWidth="3dp" + linePaint.color="#AA0000" + vertexPaint.color="#770000" + fillPaint.color="#00000000" />
diff --git a/apps/CtsVerifier/res/xml/ultrasound_line_formatter_noise.xml b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_noise.xml new file mode 100644 index 0000000..8fb236e --- /dev/null +++ b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_noise.xml
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<config + linePaint.strokeWidth="2dp" + linePaint.color="#777777" + vertexPaint.color="777777" + fillPaint.color="#00000000" />
diff --git a/apps/CtsVerifier/res/xml/ultrasound_line_formatter_pass.xml b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_pass.xml new file mode 100644 index 0000000..9a6c29a --- /dev/null +++ b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_pass.xml
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<config + linePaint.strokeWidth="2dp" + linePaint.color="#007700" + vertexPaint.color="#007700" + fillPaint.color="#00000000" />
diff --git a/apps/CtsVerifier/res/xml/ultrasound_line_formatter_trials.xml b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_trials.xml new file mode 100644 index 0000000..3f9ffc2 --- /dev/null +++ b/apps/CtsVerifier/res/xml/ultrasound_line_formatter_trials.xml
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<config + linePaint.strokeWidth="1dp" + linePaint.color="#AAAAAA" + vertexPaint.color="#777777" + fillPaint.color="#00000000" />
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java index 409b0db..3132219 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/AbstractTestListActivity.java
@@ -44,8 +44,13 @@ } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { + protected final void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); + handleActivityResult(requestCode, resultCode, data); + } + + /** Override this in subclasses instead of onActivityResult */ + protected void handleActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case LAUNCH_TEST_REQUEST_CODE: handleLaunchTestResult(resultCode, data); @@ -66,7 +71,7 @@ setContentView(R.layout.list_content); } - private void handleLaunchTestResult(int resultCode, Intent data) { + protected void handleLaunchTestResult(int resultCode, Intent data) { if (resultCode == RESULT_OK) { TestResult testResult = TestResult.fromActivityResult(resultCode, data); mAdapter.setTestResult(testResult); @@ -75,8 +80,13 @@ /** Launch the activity when its {@link ListView} item is clicked. */ @Override - protected void onListItemClick(ListView listView, View view, int position, long id) { + protected final void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); + handleItemClick(listView, view, position, id); + } + + /** Override this in subclasses instead of onListItemClick */ + protected void handleItemClick(ListView listView, View view, int position, long id) { Intent intent = getIntent(position); startActivityForResult(intent, LAUNCH_TEST_REQUEST_CODE); }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/DialogTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/DialogTestListActivity.java new file mode 100644 index 0000000..91b8d93 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/DialogTestListActivity.java
@@ -0,0 +1,284 @@ +/* + * Copyright (C) 2015 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; + +import android.app.AlertDialog; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.database.DataSetObserver; +import android.os.Bundle; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.android.cts.verifier.R; + +/** + * Test list activity that supports showing dialogs with pass/fail buttons instead of + * starting new activities. + * In addition to that dialogs have a 'go' button that can be configured to launch an intent. + * Instructions are shown on top of the screen and a test preparation button is provided. + */ +public abstract class DialogTestListActivity extends PassFailButtons.TestListActivity { + private final String TAG = "DialogTestListActivity"; + private final int mLayoutId; + private final int mTitleStringId; + private final int mInfoStringId; + private final int mInstructionsStringId; + + protected Button mPrepareTestButton; + + protected int mCurrentTestPosition; + + protected DialogTestListActivity(int layoutId, int titleStringId, int infoStringId, + int instructionsStringId) { + mLayoutId = layoutId; + mTitleStringId = titleStringId; + mInfoStringId = infoStringId; + mInstructionsStringId = instructionsStringId; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(mLayoutId); + setInfoResources(mTitleStringId, mInfoStringId, -1); + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + setResult(RESULT_CANCELED); + + ArrayTestListAdapter adapter = new ArrayTestListAdapter(this); + + setupTests(adapter); + + adapter.registerDataSetObserver(new DataSetObserver() { + @Override + public void onChanged() { + updatePassButton(); + } + }); + + setTestListAdapter(adapter); + + mCurrentTestPosition = 0; + + TextView instructionTextView = (TextView)findViewById(R.id.test_instructions); + instructionTextView.setText(mInstructionsStringId); + mPrepareTestButton = (Button)findViewById(R.id.prepare_test_button); + } + + /** + * Subclasses must add their tests items to the provided adapter(usually instances of + * {@link DialogTestListItem} or {@link DialogTestListItemWithIcon} but any class deriving from + * {@link TestListAdapter.TestListItem} will do). + * @param adapter The adapter to add test items to. + */ + protected abstract void setupTests(ArrayTestListAdapter adapter); + + // Enable Pass Button when all tests passed. + private void updatePassButton() { + getPassButton().setEnabled(mAdapter.allTestsPassed()); + } + + public class DefaultTestCallback implements DialogTestListItem.TestCallback { + final private DialogTestListItem mTest; + + public DefaultTestCallback(DialogTestListItem test) { + mTest = test; + } + + @Override + public void onPass() { + clearRemainingState(mTest); + setTestResult(mTest, TestResult.TEST_RESULT_PASSED); + } + + @Override + public void onFail() { + clearRemainingState(mTest); + setTestResult(mTest, TestResult.TEST_RESULT_FAILED); + } + } + + public void showManualTestDialog(final DialogTestListItem test) { + showManualTestDialog(test, new DefaultTestCallback(test)); + } + + public void showManualTestDialog(final DialogTestListItem test, + final DialogTestListItem.TestCallback callback) { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this) + .setIcon(android.R.drawable.ic_dialog_info) + .setTitle(mTitleStringId) + .setNeutralButton(R.string.go_button_text, null) + .setPositiveButton(R.string.pass_button_text, new AlertDialog.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + callback.onPass(); + } + }) + .setNegativeButton(R.string.fail_button_text, new AlertDialog.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + callback.onFail(); + } + }); + View customView = test.getCustomView(); + if (customView != null) { + dialogBuilder.setView(customView); + } else { + dialogBuilder.setMessage(test.getManualTestInstruction()); + } + final AlertDialog dialog = dialogBuilder.show(); + // Note: Setting the OnClickListener on the Dialog rather than the Builder, prevents the + // dialog being dismissed on onClick. + dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (!startTestIntent(test)) { + dialog.dismiss(); + } + } + }); + } + + @Override + protected void handleItemClick(ListView l, View v, int position, long id) { + TestListAdapter.TestListItem test = (TestListAdapter.TestListItem) getListAdapter() + .getItem(position); + if (test instanceof DialogTestListItem) { + mCurrentTestPosition = position; + ((DialogTestListItem)test).performTest(this); + } else { + try { + super.handleItemClick(l, v, position, id); + } catch (ActivityNotFoundException e) { + Log.d(TAG, "handleItemClick() threw exception: ", e); + setTestResult(test, TestResult.TEST_RESULT_FAILED); + showToast(R.string.test_failed_cannot_start_intent); + } + } + } + + + /** + * Start a test's manual intent + * @param test The test the manual intent of which is to be started. + * @return true if activity could be started successfully, false otherwise. + */ + boolean startTestIntent(final DialogTestListItem test) { + final Intent intent = test.intent; + try { + startActivity(intent); + } catch (ActivityNotFoundException e) { + Toast.makeText(this, "Cannot start " + intent, Toast.LENGTH_LONG).show(); + setTestResult(test, TestResult.TEST_RESULT_FAILED); + return false; + } + return true; + } + + protected void clearRemainingState(final DialogTestListItem test) { + // do nothing, override in subclass if needed + } + + protected void setTestResult(TestListAdapter.TestListItem test, int result) { + // Bundle result in an intent to feed into handleLaunchTestResult + Intent resultIntent = new Intent(); + TestResult.addResultData(resultIntent, result, test.testName, /* testDetails */ null, + /* reportLog */ null); + handleLaunchTestResult(RESULT_OK, resultIntent); + getListView().smoothScrollToPosition(mCurrentTestPosition + 1); + } + + protected void showToast(int messageId) { + String message = getString(messageId); + Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); + } + + protected static class DialogTestListItem extends TestListAdapter.TestListItem { + + public interface TestCallback { + void onPass(); + void onFail(); + } + + private String mManualInstruction; + + public DialogTestListItem(Context context, int nameResId, String testId) { + super(context.getString(nameResId), testId, null, null, null, null); + } + + public DialogTestListItem(Context context, int nameResId, String testId, + int testInstructionResId, Intent testIntent) { + super(context.getString(nameResId), testId, testIntent, null, null, null); + mManualInstruction = context.getString(testInstructionResId); + } + + public void performTest(DialogTestListActivity activity) { + activity.showManualTestDialog(this); + } + + public String getManualTestInstruction() { + return mManualInstruction; + } + + public Intent getManualTestIntent() { + return intent; + } + + public View getCustomView() { + return null; + } + + @Override + boolean isTest() { + return true; + } + } + + protected static class DialogTestListItemWithIcon extends DialogTestListItem { + + private final int mImageResId; + private final Context mContext; + + public DialogTestListItemWithIcon(Context context, int nameResId, String testId, + int testInstructionResId, Intent testIntent, int imageResId) { + super(context, nameResId, testId, testInstructionResId, testIntent); + mContext = context; + mImageResId = imageResId; + } + + @Override + public View getCustomView() { + LayoutInflater layoutInflater = LayoutInflater.from(mContext); + View view = layoutInflater.inflate(R.layout.dialog_custom_view, + null /* root */); + ((ImageView) view.findViewById(R.id.sample_icon)).setImageResource(mImageResId); + ((TextView) view.findViewById(R.id.message)).setText(getManualTestInstruction()); + return view; + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java index 8cfc6df..976ff32 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListActivity.java
@@ -16,8 +16,10 @@ package com.android.cts.verifier; +import android.Manifest; import android.app.ListActivity; import android.content.Intent; +import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; @@ -32,6 +34,20 @@ /** Top-level {@link ListActivity} for launching tests and managing results. */ public class TestListActivity extends AbstractTestListActivity implements View.OnClickListener { + private static final String [] RUNTIME_PERMISSIONS = { + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.BODY_SENSORS, + Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.READ_PHONE_STATE, + Manifest.permission.CALL_PHONE, + Manifest.permission.WRITE_CONTACTS, + Manifest.permission.CAMERA, + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.RECORD_AUDIO, + Manifest.permission.READ_CONTACTS + }; + private static final int CTS_VERIFIER_PERMISSION_REQUEST = 1; + private static final String TAG = TestListActivity.class.getSimpleName(); @Override @@ -43,6 +59,18 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + for (String runtimePermission : RUNTIME_PERMISSIONS) { + Log.v(TAG, "Checking permissions for: " + runtimePermission); + if (checkSelfPermission(runtimePermission) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(RUNTIME_PERMISSIONS, CTS_VERIFIER_PERMISSION_REQUEST); + return; + } + + } + createContinue(); + } + + private void createContinue() { if (!isTaskRoot()) { finish(); } @@ -63,6 +91,19 @@ } @Override + public void onRequestPermissionsResult( + int requestCode, String permissions[], int[] grantResults) { + if (requestCode == CTS_VERIFIER_PERMISSION_REQUEST) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + createContinue(); + return; + } + Log.v(TAG, "Permission not granted."); + Toast.makeText(this, R.string.runtime_permissions_error, Toast.LENGTH_SHORT).show(); + } + } + + @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.test_list_menu, menu);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java index 2160902..ce092cc 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
@@ -141,7 +141,7 @@ return new TestListItem(title, null, null, null, null, null); } - private TestListItem(String title, String testName, Intent intent, + protected TestListItem(String title, String testName, Intent intent, String[] requiredFeatures, String[] excludedFeatures, String[] applicableFeatures) { this.title = title; this.testName = testName;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java index d8a675c..c5d2d52 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
@@ -71,13 +71,18 @@ private static Intent createResult(Activity activity, int testResult, String testName, String testDetails, ReportLog reportLog) { Intent data = new Intent(activity, activity.getClass()); - data.putExtra(TEST_NAME, testName); - data.putExtra(TEST_RESULT, testResult); - data.putExtra(TEST_DETAILS, testDetails); - data.putExtra(TEST_METRICS, reportLog); + addResultData(data, testResult, testName, testDetails, reportLog); return data; } + public static void addResultData(Intent intent, int testResult, String testName, + String testDetails, ReportLog reportLog) { + intent.putExtra(TEST_NAME, testName); + intent.putExtra(TEST_RESULT, testResult); + intent.putExtra(TEST_DETAILS, testDetails); + intent.putExtra(TEST_METRICS, reportLog); + } + /** * Convert the test activity's result into a {@link TestResult}. Only meant to be used by * {@link TestListActivity}.
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java index dc2502c..05c5e77 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResultsReport.java
@@ -96,6 +96,7 @@ xml.startTag(null, VERIFIER_INFO_TAG); xml.attribute(null, "version-name", Version.getVersionName(mContext)); xml.attribute(null, "version-code", Integer.toString(Version.getVersionCode(mContext))); + xml.attribute(null, "build", Version.getBuildNumber(mContext)); xml.endTag(null, VERIFIER_INFO_TAG); xml.startTag(null, DEVICE_INFO_TAG);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/Version.java b/apps/CtsVerifier/src/com/android/cts/verifier/Version.java index e7b6121..dfe9508 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/Version.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/Version.java
@@ -24,13 +24,21 @@ class Version { static String getVersionName(Context context) { - return getPackageInfo(context).versionName; + return getVersionNameStrings(context)[0]; } static int getVersionCode(Context context) { return getPackageInfo(context).versionCode; } + static String getBuildNumber(Context context) { + return getVersionNameStrings(context)[1]; + } + + static private String[] getVersionNameStrings(Context context) { + return getPackageInfo(context).versionName.split(" "); + } + static PackageInfo getPackageInfo(Context context) { try { PackageManager packageManager = context.getPackageManager();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioBandSpecs.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioBandSpecs.java new file mode 100644 index 0000000..9af4af1 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioBandSpecs.java
@@ -0,0 +1,90 @@ +/* + * Copyright (C) 2015 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.audio; + +public class AudioBandSpecs { + double mFreqStart; + double mFreqStop; + double mRippleStartTop; + double mRippleStartBottom; + + double mRippleStopTop; + double mRippleStopBottom; + + double mOffset; + + public AudioBandSpecs(double fStart, double fStop, double startTop, double startBottom, + double stopTop, double stopBottom) { + initFreq(fStart, fStop); + initRipple(startTop, startBottom, stopTop, stopBottom); + setOffset(0); + } + + public void initRipple(double startTop, double startBottom, double stopTop, double stopBottom) { + mRippleStartTop = startTop; + mRippleStartBottom = startBottom; + mRippleStopTop = stopTop; + mRippleStopBottom = stopBottom; + // note: top should be >= bottom, but no check is done here. + } + + public void initFreq(double fStart, double fStop) { + mFreqStart = fStart; + mFreqStop = fStop; + } + + public void setOffset(double offset) { + mOffset = offset; + } + + /** + * Check if the given point is in bounds in this band. + */ + public boolean isInBounds(double freq, double value) { + if (freq < mFreqStart || freq > mFreqStop) { + return false; + } + + double d = mFreqStop - mFreqStart; + if (d <= 0) { + return false; + } + + double e = freq - mFreqStart; + double vTop = (e / d) * (mRippleStopTop - mRippleStartTop) + mRippleStartTop + mOffset; + if (value > vTop) { + return false; + } + + double vBottom = (e / d) * (mRippleStopBottom - mRippleStartBottom) + mRippleStartBottom + + mOffset; + + if (value < vBottom) { + return false; + } + return true; + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("Freq %.1f - %.1f |", mFreqStart, mFreqStop)); + sb.append(String.format("start [%.1f : %.1f] |", mRippleStartTop, mRippleStartBottom)); + sb.append(String.format("stop [%.1f : %.1f] |", mRippleStopTop, mRippleStopBottom)); + sb.append(String.format("offset %.1f", mOffset)); + return sb.toString(); + } +} \ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDeviceNotificationsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDeviceNotificationsActivity.java new file mode 100644 index 0000000..93e0507 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioDeviceNotificationsActivity.java
@@ -0,0 +1,87 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.content.Context; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioManager; + +import android.os.Bundle; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; + +/** + * Tests Audio Device Connection events by prompting the user to insert/remove a wired headset + * and noting the presence (or absence) of notifictions. + */ +public class AudioDeviceNotificationsActivity extends PassFailButtons.Activity { + Context mContext; + + TextView mConnectView; + TextView mDisconnectView; + Button mClearMsgsBtn; + + private class TestAudioDeviceCallback extends AudioDeviceCallback { + public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) { + if (addedDevices.length != 0) { + mConnectView.setText( + mContext.getResources().getString(R.string.audio_dev_notification_connectMsg)); + } + } + + public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) { + if (removedDevices.length != 0) { + mDisconnectView.setText( + mContext.getResources().getString( + R.string.audio_dev_notification_disconnectMsg)); + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_dev_notify); + + mContext = this; + + mConnectView = (TextView)findViewById(R.id.audio_dev_notification_connect_msg); + mDisconnectView = (TextView)findViewById(R.id.audio_dev_notification_disconnect_msg); + + mClearMsgsBtn = (Button)findViewById(R.id.audio_dev_notification_connect_clearmsgs_btn); + mClearMsgsBtn.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + mConnectView.setText(""); + mDisconnectView.setText(""); + } + }); + + AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); + audioManager.registerAudioDeviceCallback(new TestAudioDeviceCallback(), null); + + setPassFailButtonClickListeners(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyLineActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyLineActivity.java new file mode 100644 index 0000000..d3e2571 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyLineActivity.java
@@ -0,0 +1,664 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.audio.wavelib.*; +import com.android.compatibility.common.util.ReportLog; +import com.android.compatibility.common.util.ResultType; +import com.android.compatibility.common.util.ResultUnit; +import android.content.Context; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.media.AudioRecord; +import android.media.MediaRecorder; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; + +import android.util.Log; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; +import android.widget.SeekBar; +import android.widget.LinearLayout; +import android.widget.ProgressBar; + +/** + * Tests Audio Device roundtrip latency by using a loopback plug. + */ +public class AudioFrequencyLineActivity extends PassFailButtons.Activity implements Runnable, + AudioRecord.OnRecordPositionUpdateListener { + private static final String TAG = "AudioFrequencyLineActivity"; + + static final int TEST_STARTED = 900; + static final int TEST_ENDED = 901; + static final int TEST_MESSAGE = 902; + static final double MIN_ENERGY_BAND_1 = -20.0; + static final double MIN_FRACTION_POINTS_IN_BAND = 0.3; + + OnBtnClickListener mBtnClickListener = new OnBtnClickListener(); + Context mContext; + + Button mLoopbackPlugReady; + LinearLayout mLinearLayout; + Button mTestButton; + TextView mResultText; + ProgressBar mProgressBar; + //recording + private boolean mIsRecording = false; + private final Object mRecordingLock = new Object(); + private AudioRecord mRecorder; + private int mMinRecordBufferSizeInSamples = 0; + private short[] mAudioShortArray; + private short[] mAudioShortArray2; + + private final int mBlockSizeSamples = 1024; + private final int mSamplingRate = 48000; + private final int mSelectedRecordSource = MediaRecorder.AudioSource.VOICE_RECOGNITION; + private final int mChannelConfig = AudioFormat.CHANNEL_IN_MONO; + private final int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + private volatile Thread mRecordThread; + private boolean mRecordThreadShutdown = false; + + PipeShort mPipe = new PipeShort(65536); + SoundPlayerObject mSPlayer; + + private DspBufferComplex mC; + private DspBufferDouble mData; + + private DspWindow mWindow; + private DspFftServer mFftServer; + private VectorAverage mFreqAverageMain = new VectorAverage(); + + private VectorAverage mFreqAverage0 = new VectorAverage(); + private VectorAverage mFreqAverage1 = new VectorAverage(); + + private int mCurrentTest = -1; + int mBands = 4; + AudioBandSpecs[] bandSpecsArray = new AudioBandSpecs[mBands]; + + int mMaxLevel; + private class OnBtnClickListener implements OnClickListener { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.audio_frequency_line_plug_ready_btn: + Log.i(TAG, "audio loopback plug ready"); + //enable all the other views. + enableLayout(true); + break; + case R.id.audio_frequency_line_test_btn: + Log.i(TAG, "audio loopback test"); + startAudioTest(); + break; + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_frequency_line_activity); + + mContext = this; + + mLoopbackPlugReady = (Button)findViewById(R.id.audio_frequency_line_plug_ready_btn); + mLoopbackPlugReady.setOnClickListener(mBtnClickListener); + mLinearLayout = (LinearLayout)findViewById(R.id.audio_frequency_line_layout); + mTestButton = (Button)findViewById(R.id.audio_frequency_line_test_btn); + mTestButton.setOnClickListener(mBtnClickListener); + mResultText = (TextView)findViewById(R.id.audio_frequency_line_results_text); + mProgressBar = (ProgressBar)findViewById(R.id.audio_frequency_line_progress_bar); + showWait(false); + enableLayout(false); //disabled all content + + mSPlayer = new SoundPlayerObject(); + mSPlayer.setSoundWithResId(getApplicationContext(), R.raw.stereo_mono_white_noise_48); + mSPlayer.setBalance(0.5f); + + //Init FFT stuff + mAudioShortArray2 = new short[mBlockSizeSamples*2]; + mData = new DspBufferDouble(mBlockSizeSamples); + mC = new DspBufferComplex(mBlockSizeSamples); + mFftServer = new DspFftServer(mBlockSizeSamples); + + int overlap = mBlockSizeSamples / 2; + + mWindow = new DspWindow(DspWindow.WINDOW_HANNING, mBlockSizeSamples, overlap); + + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + setInfoResources(R.string.audio_frequency_line_test, + R.string.audio_frequency_line_info, -1); + + //Init bands + bandSpecsArray[0] = new AudioBandSpecs( + 50, 500, /* frequency start,stop */ + -20.0, -50, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[1] = new AudioBandSpecs( + 500,4000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[2] = new AudioBandSpecs( + 4000, 12000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 5.0, -5.0 /* stop top,bottom value */); + + bandSpecsArray[3] = new AudioBandSpecs( + 12000, 20000, /* frequency start,stop */ + 5.0, -5.0, /* start top,bottom value */ + 5.0, -30.0 /* stop top,bottom value */); + } + + /** + * enable test ui elements + */ + private void enableLayout(boolean enable) { + for (int i = 0; i < mLinearLayout.getChildCount(); i++) { + View view = mLinearLayout.getChildAt(i); + view.setEnabled(enable); + } + } + + /** + * show active progress bar + */ + private void showWait(boolean show) { + if (show) { + mProgressBar.setVisibility(View.VISIBLE); + } else { + mProgressBar.setVisibility(View.INVISIBLE); + } + } + + private void setMaxLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + mMaxLevel = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + am.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(mMaxLevel), 0); + } + + /** + * Start the loopback audio test + */ + private void startAudioTest() { + if (mTestThread != null && !mTestThread.isAlive()) { + mTestThread = null; //kill it. + } + + if (mTestThread == null) { + Log.v(TAG,"Executing test Thread"); + mTestThread = new Thread(mPlayRunnable); + getPassButton().setEnabled(false); + if (!mSPlayer.isAlive()) + mSPlayer.start(); + mTestThread.start(); + } else { + Log.v(TAG,"test Thread already running."); + } + } + + Thread mTestThread; + Runnable mPlayRunnable = new Runnable() { + public void run() { + Message msg = Message.obtain(); + msg.what = TEST_STARTED; + mMessageHandler.sendMessage(msg); + setMaxLevel(); + + sendMessage("Testing Left Capture"); + mCurrentTest = 0; + mFreqAverage0.reset(); + mSPlayer.setBalance(0.0f); + play(); + + sendMessage("Testing Right Capture"); + mCurrentTest = 1; + mFreqAverage1.reset(); + mSPlayer.setBalance(1.0f); + play(); + + mCurrentTest = -1; + sendMessage("Testing Completed"); + + Message msg2 = Message.obtain(); + msg2.what = TEST_ENDED; + mMessageHandler.sendMessage(msg2); + } + + private void play() { + startRecording(); + mSPlayer.play(true); + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + mSPlayer.play(false); + stopRecording(); + } + + private void sendMessage(String str) { + Message msg = Message.obtain(); + msg.what = TEST_MESSAGE; + msg.obj = str; + mMessageHandler.sendMessage(msg); + } + }; + + private Handler mMessageHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case TEST_STARTED: + showWait(true); + getPassButton().setEnabled(false); + break; + case TEST_ENDED: + showWait(false); + computeResults(); + break; + case TEST_MESSAGE: + String str = (String)msg.obj; + if (str != null) { + mResultText.setText(str); + } + break; + default: + Log.e(TAG, String.format("Unknown message: %d", msg.what)); + } + } + }; + + private class Results { + private String mLabel; + public double[] mValuesLog; + int[] mPointsPerBand = new int[mBands]; + double[] mAverageEnergyPerBand = new double[mBands]; + int[] mInBoundPointsPerBand = new int[mBands]; + public Results(String label) { + mLabel = label; + } + + //append results + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("Channel %s\n", mLabel)); + sb.append("Level in Band 1 : " + (testLevel() ? "OK" :"FAILED") +"\n"); + for (int b = 0; b < mBands; b++) { + double percent = 0; + if (mPointsPerBand[b] > 0) { + percent = 100.0 * (double)mInBoundPointsPerBand[b] / mPointsPerBand[b]; + } + sb.append(String.format( + " Band %d: Av. Level: %.1f dB InBand: %d/%d (%.1f%%) %s\n", + b, mAverageEnergyPerBand[b], + mInBoundPointsPerBand[b], + mPointsPerBand[b], + percent, + (testInBand(b) ? "OK" : "FAILED"))); + } + return sb.toString(); + } + + public boolean testLevel() { + if (mAverageEnergyPerBand[1] >= MIN_ENERGY_BAND_1) { + return true; + } + return false; + } + + public boolean testInBand(int b) { + if (b >= 0 && b < mBands && mPointsPerBand[b] > 0) { + if ((double)mInBoundPointsPerBand[b] / mPointsPerBand[b] > + MIN_FRACTION_POINTS_IN_BAND) + return true; + } + return false; + } + + public boolean testAll() { + if (!testLevel()) { + return false; + } + for (int b = 0; b < mBands; b++) { + if (!testInBand(b)) { + return false; + } + } + return true; + } + } + + /** + * compute test results + */ + private void computeResults() { + Results resultsLeft = new Results("Left"); + computeResultsForVector(mFreqAverage0, resultsLeft); + Results resultsRight = new Results("Right"); + computeResultsForVector(mFreqAverage1, resultsRight); + if (resultsLeft.testAll() && resultsRight.testAll()) { + //enable button + getPassButton().setEnabled(true); + } + } + + private void computeResultsForVector(VectorAverage freqAverage,Results results) { + + int points = freqAverage.getSize(); + if (points > 0) { + //compute vector in db + double[] values = new double[points]; + freqAverage.getData(values, false); + results.mValuesLog = new double[points]; + for (int i = 0; i < points; i++) { + results.mValuesLog[i] = 20 * Math.log10(values[i]); + } + + int currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecsArray[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecsArray[currentBand].mFreqStart) { + results.mAverageEnergyPerBand[currentBand] += results.mValuesLog[i]; + results.mPointsPerBand[currentBand]++; + } + } + + for (int b = 0; b < mBands; b++) { + if (results.mPointsPerBand[b] > 0) { + results.mAverageEnergyPerBand[b] = + results.mAverageEnergyPerBand[b] / results.mPointsPerBand[b]; + } + } + + //set offset relative to band 1 level + for (int b = 0; b < mBands; b++) { + bandSpecsArray[b].setOffset(results.mAverageEnergyPerBand[1]); + } + + //test points in band. + currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecsArray[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecsArray[currentBand].mFreqStart) { + double value = results.mValuesLog[i]; + if (bandSpecsArray[currentBand].isInBounds(freq, value)) { + results.mInBoundPointsPerBand[currentBand]++; + } + } + } + + appendResultsToScreen(results.toString()); + //store results + recordTestResults(results); + } else { + appendResultsToScreen("Failed testing channel " + results.mLabel); + } + } + + //append results + private void appendResultsToScreen(String str) { + String currentText = mResultText.getText().toString(); + mResultText.setText(currentText + "\n" + str); + } + + /** + * Store test results in log + */ + private void recordTestResults(Results results) { + String channelLabel = "channel_" + results.mLabel; + + for (int b = 0; b < mBands; b++) { + String bandLabel = String.format(channelLabel + "_%d", b); + getReportLog().addValue( + bandLabel + "_Level", + results.mAverageEnergyPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.NONE); + + getReportLog().addValue( + bandLabel + "_pointsinbound", + results.mInBoundPointsPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.COUNT); + + getReportLog().addValue( + bandLabel + "_pointstotal", + results.mPointsPerBand[b], + ResultType.NEUTRAL, + ResultUnit.COUNT); + } + + getReportLog().addValues(channelLabel + "_magnitudeSpectrumLog", + results.mValuesLog, + ResultType.NEUTRAL, + ResultUnit.NONE); + + Log.v(TAG, "Results Recorded"); + } + + private void startRecording() { + synchronized (mRecordingLock) { + mIsRecording = true; + } + + boolean successful = initRecord(); + if (successful) { + startRecordingForReal(); + } else { + Log.v(TAG, "Recorder initialization error."); + synchronized (mRecordingLock) { + mIsRecording = false; + } + } + } + + private void startRecordingForReal() { + // start streaming + if (mRecordThread == null) { + mRecordThread = new Thread(AudioFrequencyLineActivity.this); + mRecordThread.setName("FrequencyAnalyzerThread"); + mRecordThreadShutdown = false; + } + if (!mRecordThread.isAlive()) { + mRecordThread.start(); + } + + mPipe.flush(); + + long startTime = SystemClock.uptimeMillis(); + mRecorder.startRecording(); + if (mRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) { + stopRecording(); + return; + } + Log.v(TAG, "Start time: " + (long) (SystemClock.uptimeMillis() - startTime) + " ms"); + } + + private void stopRecording() { + synchronized (mRecordingLock) { + stopRecordingForReal(); + mIsRecording = false; + } + } + + private void stopRecordingForReal() { + + // stop streaming + Thread zeThread = mRecordThread; + mRecordThread = null; + mRecordThreadShutdown = true; + if (zeThread != null) { + zeThread.interrupt(); + try { + zeThread.join(); + } catch(InterruptedException e) { + Log.v(TAG,"Error shutting down recording thread " + e); + //we don't really care about this error, just logging it. + } + } + // release recording resources + if (mRecorder != null) { + mRecorder.stop(); + mRecorder.release(); + mRecorder = null; + } + } + + private boolean initRecord() { + int minRecordBuffSizeInBytes = AudioRecord.getMinBufferSize(mSamplingRate, + mChannelConfig, mAudioFormat); + Log.v(TAG,"FrequencyAnalyzer: min buff size = " + minRecordBuffSizeInBytes + " bytes"); + if (minRecordBuffSizeInBytes <= 0) { + return false; + } + + mMinRecordBufferSizeInSamples = minRecordBuffSizeInBytes / 2; + // allocate the byte array to read the audio data + + mAudioShortArray = new short[mMinRecordBufferSizeInSamples]; + + Log.v(TAG, "Initiating record:"); + Log.v(TAG, " using source " + mSelectedRecordSource); + Log.v(TAG, " at " + mSamplingRate + "Hz"); + + try { + mRecorder = new AudioRecord(mSelectedRecordSource, mSamplingRate, + mChannelConfig, mAudioFormat, 2 * minRecordBuffSizeInBytes); + } catch (IllegalArgumentException e) { + return false; + } + if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) { + mRecorder.release(); + mRecorder = null; + return false; + } + mRecorder.setRecordPositionUpdateListener(this); + mRecorder.setPositionNotificationPeriod(mBlockSizeSamples / 2); + return true; + } + + // --------------------------------------------------------- + // Implementation of AudioRecord.OnPeriodicNotificationListener + // -------------------- + public void onPeriodicNotification(AudioRecord recorder) { + int samplesAvailable = mPipe.availableToRead(); + int samplesNeeded = mBlockSizeSamples; + if (samplesAvailable >= samplesNeeded) { + mPipe.read(mAudioShortArray2, 0, samplesNeeded); + + //compute stuff. + double maxval = Math.pow(2, 15); + int clipcount = 0; + double cliplevel = (maxval-10) / maxval; + double sum = 0; + double maxabs = 0; + int i; + int index = 0; + + for (i = 0; i < samplesNeeded; i++) { + double value = mAudioShortArray2[i] / maxval; + double valueabs = Math.abs(value); + + if (valueabs > maxabs) { + maxabs = valueabs; + } + + if (valueabs > cliplevel) { + clipcount++; + } + + sum += value * value; + //fft stuff + if (index < mBlockSizeSamples) { + mData.mData[index] = value; + } + index++; + } + + //for the current frame, compute FFT and send to the viewer. + + //apply window and pack as complex for now. + DspBufferMath.mult(mData, mData, mWindow.mBuffer); + DspBufferMath.set(mC, mData); + mFftServer.fft(mC, 1); + + double[] halfMagnitude = new double[mBlockSizeSamples / 2]; + for (i = 0; i < mBlockSizeSamples / 2; i++) { + halfMagnitude[i] = Math.sqrt(mC.mReal[i] * mC.mReal[i] + mC.mImag[i] * mC.mImag[i]); + } + + mFreqAverageMain.setData(halfMagnitude, false); //average all of them! + + switch(mCurrentTest) { + case 0: + mFreqAverage0.setData(halfMagnitude, false); + break; + case 1: + mFreqAverage1.setData(halfMagnitude, false); + break; + } + } + } + + public void onMarkerReached(AudioRecord track) { + } + + // --------------------------------------------------------- + // Implementation of Runnable for the audio recording + playback + // -------------------- + public void run() { + int nSamplesRead = 0; + + Thread thisThread = Thread.currentThread(); + while (mRecordThread == thisThread && !mRecordThreadShutdown) { + // read from native recorder + nSamplesRead = mRecorder.read(mAudioShortArray, 0, mMinRecordBufferSizeInSamples); + if (nSamplesRead > 0) { + mPipe.write(mAudioShortArray, 0, nSamplesRead); + } + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java new file mode 100644 index 0000000..b37a721 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java
@@ -0,0 +1,851 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.audio.wavelib.*; +import com.android.compatibility.common.util.ReportLog; +import com.android.compatibility.common.util.ResultType; +import com.android.compatibility.common.util.ResultUnit; +import android.content.Context; +import android.content.BroadcastReceiver; +import android.content.Intent; +import android.content.IntentFilter; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.media.AudioRecord; +import android.media.MediaRecorder; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; + +import android.util.Log; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; +import android.widget.SeekBar; +import android.widget.LinearLayout; +import android.widget.ProgressBar; + +/** + * Tests Audio built in Microphone response using external speakers and USB reference microphone. + */ +public class AudioFrequencyMicActivity extends PassFailButtons.Activity implements Runnable, + AudioRecord.OnRecordPositionUpdateListener { + private static final String TAG = "AudioFrequencyMicActivity"; + + private static final int TEST_STARTED = 900; + private static final int TEST_ENDED = 901; + private static final int TEST_MESSAGE = 902; + private static final int TEST1_MESSAGE = 903; + private static final int TEST1_ENDED = 904; + private static final double MIN_ENERGY_BAND_1 = -50.0; //dB Full Scale + private static final double MAX_ENERGY_BAND_1_BASE = -60.0; //dB Full Scale + private static final double MIN_FRACTION_POINTS_IN_BAND = 0.3; + private static final double MAX_VAL = Math.pow(2, 15); + private static final double CLIP_LEVEL = (MAX_VAL-10) / MAX_VAL; + + final OnBtnClickListener mBtnClickListener = new OnBtnClickListener(); + Context mContext; + + Button mSpeakersReady; //user signal to have connected external speakers + Button mTest1Button; //execute test 1 + Button mUsbMicReady; //user signal to have connected USB Microphone + Button mTest2Button; //user to start test + String mUsbDevicesInfo; //usb device info for report + LinearLayout mLayoutTest1; + LinearLayout mLayoutTest2a; + LinearLayout mLayoutTest2b; + + TextView mSpeakerReadyText; + TextView mTest2Result; + TextView mUsbStatusText; + TextView mTest1Result; + ProgressBar mProgressBar; + + private boolean mIsRecording = false; + private final Object mRecordingLock = new Object(); + private AudioRecord mRecorder; + private int mMinRecordBufferSizeInSamples = 0; + private short[] mAudioShortArray; + private short[] mAudioShortArray2; + + private final int mBlockSizeSamples = 1024; + private final int mSamplingRate = 48000; + private final int mSelectedRecordSource = MediaRecorder.AudioSource.VOICE_RECOGNITION; + private final int mChannelConfig = AudioFormat.CHANNEL_IN_MONO; + private final int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + private Thread mRecordThread; + + PipeShort mPipe = new PipeShort(65536); + SoundPlayerObject mSPlayer; + + private DspBufferComplex mC; + private DspBufferDouble mData; + + private DspWindow mWindow; + private DspFftServer mFftServer; + private VectorAverage mFreqAverageMain = new VectorAverage(); + + private VectorAverage mFreqAverageBase = new VectorAverage(); + private VectorAverage mFreqAverageBuiltIn = new VectorAverage(); + private VectorAverage mFreqAverageReference = new VectorAverage(); + + private int mCurrentTest = -1; + int mBands = 4; + AudioBandSpecs[] bandSpecsArray = new AudioBandSpecs[mBands]; + AudioBandSpecs[] baseBandSpecsArray = new AudioBandSpecs[mBands]; + + int mMaxLevel; + private class OnBtnClickListener implements OnClickListener { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.audio_frequency_mic_speakers_ready_btn: + testSpeakersReady(); + break; + case R.id.audio_frequency_mic_test1_btn: + startTest1(); + break; + case R.id.audio_frequency_mic_mic_ready_btn: + testUSB(); + break; + case R.id.audio_frequency_mic_test2_btn: + startTest2(); + break; + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_frequency_mic_activity); + mContext = this; + mSpeakerReadyText = (TextView) findViewById(R.id.audio_frequency_mic_speakers_ready_status); + + mSpeakersReady = (Button)findViewById(R.id.audio_frequency_mic_speakers_ready_btn); + mSpeakersReady.setOnClickListener(mBtnClickListener); + mTest1Button = (Button)findViewById(R.id.audio_frequency_mic_test1_btn); + mTest1Button.setOnClickListener(mBtnClickListener); + mTest1Result = (TextView)findViewById(R.id.audio_frequency_mic_results1_text); + mLayoutTest1 = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test1); + mLayoutTest2a = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test2a); + mLayoutTest2b = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test2b); + mUsbMicReady = (Button)findViewById(R.id.audio_frequency_mic_mic_ready_btn); + mUsbMicReady.setOnClickListener(mBtnClickListener); + + mUsbStatusText = (TextView)findViewById(R.id.audio_frequency_mic_usb_status); + mTest2Button = (Button)findViewById(R.id.audio_frequency_mic_test2_btn); + mTest2Button.setOnClickListener(mBtnClickListener); + mTest2Result = (TextView)findViewById(R.id.audio_frequency_mic_results_text); + mProgressBar = (ProgressBar)findViewById(R.id.audio_frequency_mic_progress_bar); + showWait(false); + enableLayout(mLayoutTest1, false); + enableLayout(mLayoutTest2a, false); + enableLayout(mLayoutTest2b, false); + + mSPlayer = new SoundPlayerObject(); + mSPlayer.setSoundWithResId(getApplicationContext(), R.raw.stereo_mono_white_noise_48); + mSPlayer.setBalance(0.5f); + + //Init FFT stuff + mAudioShortArray2 = new short[mBlockSizeSamples*2]; + mData = new DspBufferDouble(mBlockSizeSamples); + mC = new DspBufferComplex(mBlockSizeSamples); + mFftServer = new DspFftServer(mBlockSizeSamples); + + int overlap = mBlockSizeSamples / 2; + + mWindow = new DspWindow(DspWindow.WINDOW_HANNING, mBlockSizeSamples, overlap); + + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + setInfoResources(R.string.audio_frequency_mic_test, + R.string.audio_frequency_mic_info, -1); + + //Init bands for BuiltIn/Reference test + bandSpecsArray[0] = new AudioBandSpecs( + 50, 500, /* frequency start,stop */ + -20.0, -50, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[1] = new AudioBandSpecs( + 500,4000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[2] = new AudioBandSpecs( + 4000, 12000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 5.0, -5.0 /* stop top,bottom value */); + + bandSpecsArray[3] = new AudioBandSpecs( + 12000, 20000, /* frequency start,stop */ + 5.0, -5.0, /* start top,bottom value */ + 5.0, -30.0 /* stop top,bottom value */); + + //Init base bands for silence + baseBandSpecsArray[0] = new AudioBandSpecs( + 50, 500, /* frequency start,stop */ + 40.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[1] = new AudioBandSpecs( + 500,4000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[2] = new AudioBandSpecs( + 4000, 12000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[3] = new AudioBandSpecs( + 12000, 20000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + } + + /** + * enable test ui elements + */ + private void enableLayout(LinearLayout layout, boolean enable) { + for (int i = 0; i < layout.getChildCount(); i++) { + View view = layout.getChildAt(i); + view.setEnabled(enable); + } + } + + /** + * show active progress bar + */ + private void showWait(boolean show) { + if (show) { + mProgressBar.setVisibility(View.VISIBLE); + } else { + mProgressBar.setVisibility(View.INVISIBLE); + } + } + + private void setMaxLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + mMaxLevel = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + am.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(mMaxLevel), 0); + } + + private void setMinLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0); + } + + /** + * Start the loopback audio test + */ + private void startTest1() { + if (mTestThread != null && !mTestThread.isAlive()) { + mTestThread = null; //kill it. + } + + if (mTestThread == null) { + Log.v(TAG,"Executing test Thread"); + mTestThread = new Thread(mTest1Runnable); + //getPassButton().setEnabled(false); + if (!mSPlayer.isAlive()) + mSPlayer.start(); + mTestThread.start(); + } else { + Log.v(TAG,"test Thread already running."); + } + } + + Thread mTestThread; + Runnable mTest1Runnable = new Runnable() { + public void run() { + Message msg = Message.obtain(); + msg.what = TEST_STARTED; + mMessageHandler.sendMessage(msg); + + setMinLevel(); + sendMessage("Testing Background Environment"); + mCurrentTest = 0; + mSPlayer.setBalance(0.5f); + mFreqAverageBase.reset(); + play(); + + setMaxLevel(); + sendMessage("Testing Built in Microphone"); + mCurrentTest = 1; + mFreqAverageBuiltIn.reset(); + mSPlayer.setBalance(0.5f); + play(); + + mCurrentTest = -1; + sendMessage("Testing Completed"); + + Message msg2 = Message.obtain(); + msg2.what = TEST1_ENDED; + mMessageHandler.sendMessage(msg2); + } + + private void play() { + startRecording(); + mSPlayer.play(true); + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + //restore interrupted status + Thread.currentThread().interrupt(); + } + + mSPlayer.play(false); + stopRecording(); + } + + private void sendMessage(String str) { + Message msg = Message.obtain(); + msg.what = TEST1_MESSAGE; + msg.obj = str; + mMessageHandler.sendMessage(msg); + } + }; + + /** + * Start the loopback audio test + */ + private void startTest2() { + if (mTestThread != null && !mTestThread.isAlive()) { + mTestThread = null; //kill it. + } + + if (mTestThread == null) { + Log.v(TAG,"Executing test2 Thread"); + mTestThread = new Thread(mTest2Runnable); + //getPassButton().setEnabled(false); + if (!mSPlayer.isAlive()) + mSPlayer.start(); + mTestThread.start(); + } else { + Log.v(TAG,"test Thread already running."); + } + } + + Runnable mTest2Runnable = new Runnable() { + public void run() { + Message msg = Message.obtain(); + msg.what = TEST_STARTED; + mMessageHandler.sendMessage(msg); + + sendMessage("Testing Reference USB Microphone"); + mCurrentTest = 2; + mFreqAverageReference.reset(); + mSPlayer.setBalance(0.5f); + play(); + + mCurrentTest = -1; + sendMessage("Testing Completed"); + + Message msg2 = Message.obtain(); + msg2.what = TEST_ENDED; + mMessageHandler.sendMessage(msg2); + } + + private void play() { + startRecording(); + mSPlayer.play(true); + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + //restore interrupted status + Thread.currentThread().interrupt(); + } + + mSPlayer.play(false); + stopRecording(); + } + + private void sendMessage(String str) { + Message msg = Message.obtain(); + msg.what = TEST_MESSAGE; + msg.obj = str; + mMessageHandler.sendMessage(msg); + } + }; + + private Handler mMessageHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case TEST_STARTED: + showWait(true); + getPassButton().setEnabled(false); + break; + case TEST_ENDED: + showWait(false); + computeTest2Results(); + break; + case TEST1_MESSAGE: { + String str = (String)msg.obj; + if (str != null) { + mTest1Result.setText(str); + } + } + break; + case TEST1_ENDED: + showWait(false); + computeTest1Results(); + break; + case TEST_MESSAGE: { + String str = (String)msg.obj; + if (str != null) { + mTest2Result.setText(str); + } + } + break; + default: + Log.e(TAG, String.format("Unknown message: %d", msg.what)); + } + } + }; + + private class Results { + private String mLabel; + public double[] mValuesLog; + int[] mPointsPerBand = new int[mBands]; + double[] mAverageEnergyPerBand = new double[mBands]; + int[] mInBoundPointsPerBand = new int[mBands]; + public boolean mIsBaseMeasurement = false; + public Results(String label) { + mLabel = label; + } + + //append results + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("Channel %s\n", mLabel)); + sb.append("Level in Band 1 : " + (testLevel() ? "OK" :"FAILED") + + (mIsBaseMeasurement ? " (Base Meas.)" : "") + "\n"); + for (int b = 0; b < mBands; b++) { + double percent = 0; + if (mPointsPerBand[b] > 0) { + percent = 100.0 * (double) mInBoundPointsPerBand[b] / mPointsPerBand[b]; + } + sb.append(String.format( + " Band %d: Av. Level: %.1f dB InBand: %d/%d (%.1f%%) %s\n", + b, mAverageEnergyPerBand[b], + mInBoundPointsPerBand[b], + mPointsPerBand[b], + percent, + (testInBand(b) ? "OK" : "FAILED"))); + } + return sb.toString(); + } + + public boolean testLevel() { + if (mIsBaseMeasurement && mAverageEnergyPerBand[1] <= MAX_ENERGY_BAND_1_BASE) { + return true; + } else if (mAverageEnergyPerBand[1] >= MIN_ENERGY_BAND_1) { + return true; + } + return false; + } + + public boolean testInBand(int b) { + if (b >= 0 && b < mBands && mPointsPerBand[b] > 0) { + if ((double) mInBoundPointsPerBand[b] / mPointsPerBand[b] > + MIN_FRACTION_POINTS_IN_BAND) { + return true; + } + } + return false; + } + + public boolean testAll() { + if (!testLevel()) { + return false; + } + for (int b = 0; b < mBands; b++) { + if (!testInBand(b)) { + return false; + } + } + return true; + } + } + + + /** + * compute test1 results + */ + private void computeTest1Results() { + + Results resultsBase = new Results("Base"); + if (computeResultsForVector(mFreqAverageBase, resultsBase, true, baseBandSpecsArray)) { + appendResultsToScreen(resultsBase.toString(), mTest1Result); + recordTestResults(resultsBase); + } + + Results resultsBuiltIn = new Results("BuiltIn"); + if (computeResultsForVector(mFreqAverageBuiltIn, resultsBuiltIn, false, bandSpecsArray)) { + appendResultsToScreen(resultsBuiltIn.toString(), mTest1Result); + recordTestResults(resultsBuiltIn); + } + + //tell user to connect USB Microphone + appendResultsToScreen("\n\n" + + getResources().getText(R.string.audio_frequency_mic_connect_mic), mTest1Result); + enableLayout(mLayoutTest2a, true); + } + + /** + * compute test results + */ + private void computeTest2Results() { + Results resultsReference = new Results("Reference"); + if (computeResultsForVector(mFreqAverageReference, resultsReference, + false, bandSpecsArray)) { + appendResultsToScreen(resultsReference.toString(),mTest2Result); + recordTestResults(resultsReference); + getPassButton().setEnabled(true); + } + } + + private boolean computeResultsForVector(VectorAverage freqAverage, Results results, + boolean isBase, AudioBandSpecs[] bandSpecs) { + + results.mIsBaseMeasurement = isBase; + int points = freqAverage.getSize(); + if (points > 0) { + //compute vector in db + double[] values = new double[points]; + freqAverage.getData(values, false); + results.mValuesLog = new double[points]; + for (int i = 0; i < points; i++) { + results.mValuesLog[i] = 20 * Math.log10(values[i]); + } + + int currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecs[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecs[currentBand].mFreqStart) { + results.mAverageEnergyPerBand[currentBand] += results.mValuesLog[i]; + results.mPointsPerBand[currentBand]++; + } + } + + for (int b = 0; b < mBands; b++) { + if (results.mPointsPerBand[b] > 0) { + results.mAverageEnergyPerBand[b] = + results.mAverageEnergyPerBand[b] / results.mPointsPerBand[b]; + } + } + + //set offset relative to band 1 level + for (int b = 0; b < mBands; b++) { + bandSpecs[b].setOffset(results.mAverageEnergyPerBand[1]); + } + + //test points in band. + currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecs[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecs[currentBand].mFreqStart) { + double value = results.mValuesLog[i]; + if (bandSpecs[currentBand].isInBounds(freq, value)) { + results.mInBoundPointsPerBand[currentBand]++; + } + } + } + return true; + } else { + return false; + } + } + + //append results + private void appendResultsToScreen(String str, TextView text) { + String currentText = text.getText().toString(); + text.setText(currentText + "\n" + str); + } + + /** + * Store test results in log + */ + private void recordTestResults(Results results) { + String channelLabel = "channel_" + results.mLabel; + + for (int b = 0; b < mBands; b++) { + String bandLabel = String.format(channelLabel + "_%d", b); + getReportLog().addValue( + bandLabel + "_Level", + results.mAverageEnergyPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.NONE); + + getReportLog().addValue( + bandLabel + "_pointsinbound", + results.mInBoundPointsPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.COUNT); + + getReportLog().addValue( + bandLabel + "_pointstotal", + results.mPointsPerBand[b], + ResultType.NEUTRAL, + ResultUnit.COUNT); + } + + getReportLog().addValues(channelLabel + "_magnitudeSpectrumLog", + results.mValuesLog, + ResultType.NEUTRAL, + ResultUnit.NONE); + + Log.v(TAG, "Results Recorded"); + } + + private void startRecording() { + synchronized (mRecordingLock) { + mIsRecording = true; + } + + boolean successful = initRecord(); + if (successful) { + startRecordingForReal(); + } else { + Log.v(TAG, "Recorder initialization error."); + synchronized (mRecordingLock) { + mIsRecording = false; + } + } + } + + private void startRecordingForReal() { + // start streaming + if (mRecordThread == null) { + mRecordThread = new Thread(AudioFrequencyMicActivity.this); + mRecordThread.setName("FrequencyAnalyzerThread"); + } + if (!mRecordThread.isAlive()) { + mRecordThread.start(); + } + + mPipe.flush(); + + long startTime = SystemClock.uptimeMillis(); + mRecorder.startRecording(); + if (mRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) { + stopRecording(); + return; + } + Log.v(TAG, "Start time: " + (long) (SystemClock.uptimeMillis() - startTime) + " ms"); + } + + private void stopRecording() { + synchronized (mRecordingLock) { + stopRecordingForReal(); + mIsRecording = false; + } + } + + private void stopRecordingForReal() { + + // stop streaming + Thread zeThread = mRecordThread; + mRecordThread = null; + if (zeThread != null) { + zeThread.interrupt(); + try { + zeThread.join(); + } catch(InterruptedException e) { + //restore interrupted status of recording thread + zeThread.interrupt(); + } + } + // release recording resources + if (mRecorder != null) { + mRecorder.stop(); + mRecorder.release(); + mRecorder = null; + } + } + + private boolean initRecord() { + int minRecordBuffSizeInBytes = AudioRecord.getMinBufferSize(mSamplingRate, + mChannelConfig, mAudioFormat); + Log.v(TAG,"FrequencyAnalyzer: min buff size = " + minRecordBuffSizeInBytes + " bytes"); + if (minRecordBuffSizeInBytes <= 0) { + return false; + } + + mMinRecordBufferSizeInSamples = minRecordBuffSizeInBytes / 2; + // allocate the byte array to read the audio data + + mAudioShortArray = new short[mMinRecordBufferSizeInSamples]; + + Log.v(TAG, "Initiating record:"); + Log.v(TAG, " using source " + mSelectedRecordSource); + Log.v(TAG, " at " + mSamplingRate + "Hz"); + + try { + mRecorder = new AudioRecord(mSelectedRecordSource, mSamplingRate, + mChannelConfig, mAudioFormat, 2 * minRecordBuffSizeInBytes); + } catch (IllegalArgumentException e) { + return false; + } + if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) { + mRecorder.release(); + mRecorder = null; + return false; + } + mRecorder.setRecordPositionUpdateListener(this); + mRecorder.setPositionNotificationPeriod(mBlockSizeSamples / 2); + return true; + } + + // --------------------------------------------------------- + // Implementation of AudioRecord.OnPeriodicNotificationListener + // -------------------- + public void onPeriodicNotification(AudioRecord recorder) { + int samplesAvailable = mPipe.availableToRead(); + int samplesNeeded = mBlockSizeSamples; + if (samplesAvailable >= samplesNeeded) { + mPipe.read(mAudioShortArray2, 0, samplesNeeded); + + //compute stuff. + int clipcount = 0; + double sum = 0; + double maxabs = 0; + int i; + + for (i = 0; i < samplesNeeded; i++) { + double value = mAudioShortArray2[i] / MAX_VAL; + double valueabs = Math.abs(value); + + if (valueabs > maxabs) { + maxabs = valueabs; + } + + if (valueabs > CLIP_LEVEL) { + clipcount++; + } + + sum += value * value; + //fft stuff + mData.mData[i] = value; + } + + //for the current frame, compute FFT and send to the viewer. + + //apply window and pack as complex for now. + DspBufferMath.mult(mData, mData, mWindow.mBuffer); + DspBufferMath.set(mC, mData); + mFftServer.fft(mC, 1); + + double[] halfMagnitude = new double[mBlockSizeSamples / 2]; + for (i = 0; i < mBlockSizeSamples / 2; i++) { + halfMagnitude[i] = Math.sqrt(mC.mReal[i] * mC.mReal[i] + mC.mImag[i] * mC.mImag[i]); + } + + mFreqAverageMain.setData(halfMagnitude, false); //average all of them! + + switch(mCurrentTest) { + case 0: + mFreqAverageBase.setData(halfMagnitude, false); + break; + case 1: + mFreqAverageBuiltIn.setData(halfMagnitude, false); + break; + case 2: + mFreqAverageReference.setData(halfMagnitude, false); + break; + } + } + } + + public void onMarkerReached(AudioRecord track) { + } + + // --------------------------------------------------------- + // Implementation of Runnable for the audio recording + playback + // -------------------- + public void run() { + Thread thisThread = Thread.currentThread(); + while (!thisThread.isInterrupted()) { + // read from native recorder + int nSamplesRead = mRecorder.read(mAudioShortArray, 0, mMinRecordBufferSizeInSamples); + if (nSamplesRead > 0) { + mPipe.write(mAudioShortArray, 0, nSamplesRead); + } + } + } + + private void testSpeakersReady() { + boolean isUsbConnected = + UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext()); + if (isUsbConnected) { + mSpeakerReadyText.setText(" USB device detected, please remove it"); + enableLayout(mLayoutTest1, false); + //fail + } else { + mSpeakerReadyText.setText(" No USB device detected. OK"); + enableLayout(mLayoutTest1, true); + } + } + + private void testUSB() { + boolean isConnected = UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext()); + mUsbDevicesInfo = UsbMicrophoneTester.getUSBDeviceListString(getApplicationContext()); + + if (isConnected) { + mUsbStatusText.setText( + getResources().getText(R.string.audio_frequency_mic_mic_ready_text)); + enableLayout(mLayoutTest2b, true); + } else { + mUsbStatusText.setText( + getResources().getText(R.string.audio_frequency_mic_mic_not_ready_text)); + enableLayout(mLayoutTest2b, false); + } + } + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencySpeakerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencySpeakerActivity.java new file mode 100644 index 0000000..f9334b3 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencySpeakerActivity.java
@@ -0,0 +1,732 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.audio.wavelib.*; +import com.android.compatibility.common.util.ReportLog; +import com.android.compatibility.common.util.ResultType; +import com.android.compatibility.common.util.ResultUnit; +import android.content.Context; +import android.content.BroadcastReceiver; +import android.content.Intent; +import android.content.IntentFilter; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.media.AudioRecord; +import android.media.MediaRecorder; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; + +import android.util.Log; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; +import android.widget.SeekBar; +import android.widget.LinearLayout; +import android.widget.ProgressBar; + +/** + * Tests Audio Device roundtrip latency by using a loopback plug. + */ +public class AudioFrequencySpeakerActivity extends PassFailButtons.Activity implements Runnable, + AudioRecord.OnRecordPositionUpdateListener { + private static final String TAG = "AudioFrequencySpeakerActivity"; + + static final int TEST_STARTED = 900; + static final int TEST_ENDED = 901; + static final int TEST_MESSAGE = 902; + static final double MIN_ENERGY_BAND_1 = -50.0; //dB Full Scale + static final double MAX_ENERGY_BAND_1_BASE = -60.0; //dB Full Scale + static final double MIN_FRACTION_POINTS_IN_BAND = 0.3; + + final OnBtnClickListener mBtnClickListener = new OnBtnClickListener(); + Context mContext; + + Button mLoopbackPlugReady; //user signal to have connected USB Microphone + Button mTestButton; //user to start test + String mUsbDevicesInfo; //usb device info for report + LinearLayout mLinearLayout; + TextView mResultText; + TextView mUsbStatusText; + ProgressBar mProgressBar; + + private boolean mIsRecording = false; + private final Object mRecordingLock = new Object(); + private AudioRecord mRecorder; + private int mMinRecordBufferSizeInSamples = 0; + private short[] mAudioShortArray; + private short[] mAudioShortArray2; + + private final int mBlockSizeSamples = 1024; + private final int mSamplingRate = 48000; + private final int mSelectedRecordSource = MediaRecorder.AudioSource.VOICE_RECOGNITION; + private final int mChannelConfig = AudioFormat.CHANNEL_IN_MONO; + private final int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + private Thread mRecordThread; + private boolean mRecordThreadShutdown = false; + + PipeShort mPipe = new PipeShort(65536); + SoundPlayerObject mSPlayer; + + private DspBufferComplex mC; + private DspBufferDouble mData; + + private DspWindow mWindow; + private DspFftServer mFftServer; + private VectorAverage mFreqAverageMain = new VectorAverage(); + + private VectorAverage mFreqAverageBase = new VectorAverage(); + private VectorAverage mFreqAverageLeft = new VectorAverage(); + private VectorAverage mFreqAverageRight = new VectorAverage(); + + private int mCurrentTest = -1; + int mBands = 4; + AudioBandSpecs[] bandSpecsArray = new AudioBandSpecs[mBands]; + AudioBandSpecs[] baseBandSpecsArray = new AudioBandSpecs[mBands]; + + int mMaxLevel; + private class OnBtnClickListener implements OnClickListener { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.audio_frequency_speaker_mic_ready_btn: + testUSB(); + break; + case R.id.audio_frequency_speaker_test_btn: + startAudioTest(); + break; + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_frequency_speaker_activity); + + mContext = this; + + mLoopbackPlugReady = (Button)findViewById(R.id.audio_frequency_speaker_mic_ready_btn); + mLoopbackPlugReady.setOnClickListener(mBtnClickListener); + mLinearLayout = (LinearLayout)findViewById(R.id.audio_frequency_speaker_layout); + mUsbStatusText = (TextView)findViewById(R.id.audio_frequency_speaker_usb_status); + mTestButton = (Button)findViewById(R.id.audio_frequency_speaker_test_btn); + mTestButton.setOnClickListener(mBtnClickListener); + mResultText = (TextView)findViewById(R.id.audio_frequency_speaker_results_text); + mProgressBar = (ProgressBar)findViewById(R.id.audio_frequency_speaker_progress_bar); + showWait(false); + enableLayout(false); //disabled all content + + mSPlayer = new SoundPlayerObject(); + mSPlayer.setSoundWithResId(getApplicationContext(), R.raw.stereo_mono_white_noise_48); + mSPlayer.setBalance(0.5f); + + //Init FFT stuff + mAudioShortArray2 = new short[mBlockSizeSamples*2]; + mData = new DspBufferDouble(mBlockSizeSamples); + mC = new DspBufferComplex(mBlockSizeSamples); + mFftServer = new DspFftServer(mBlockSizeSamples); + + int overlap = mBlockSizeSamples / 2; + + mWindow = new DspWindow(DspWindow.WINDOW_HANNING, mBlockSizeSamples, overlap); + + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + setInfoResources(R.string.audio_frequency_speaker_test, + R.string.audio_frequency_speaker_info, -1); + + //Init bands for Left/Right test + bandSpecsArray[0] = new AudioBandSpecs( + 50, 500, /* frequency start,stop */ + -20.0, -50, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[1] = new AudioBandSpecs( + 500,4000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 4.0, -4.0 /* stop top,bottom value */); + + bandSpecsArray[2] = new AudioBandSpecs( + 4000, 12000, /* frequency start,stop */ + 4.0, -4.0, /* start top,bottom value */ + 5.0, -5.0 /* stop top,bottom value */); + + bandSpecsArray[3] = new AudioBandSpecs( + 12000, 20000, /* frequency start,stop */ + 5.0, -5.0, /* start top,bottom value */ + 5.0, -30.0 /* stop top,bottom value */); + + //Init base bands for silence + baseBandSpecsArray[0] = new AudioBandSpecs( + 50, 500, /* frequency start,stop */ + 40.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[1] = new AudioBandSpecs( + 500,4000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[2] = new AudioBandSpecs( + 4000, 12000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + baseBandSpecsArray[3] = new AudioBandSpecs( + 12000, 20000, /* frequency start,stop */ + 5.0, -50.0, /* start top,bottom value */ + 5.0, -50.0 /* stop top,bottom value */); + + } + + /** + * enable test ui elements + */ + private void enableLayout(boolean enable) { + for (int i = 0; i < mLinearLayout.getChildCount(); i++) { + View view = mLinearLayout.getChildAt(i); + view.setEnabled(enable); + } + } + + /** + * show active progress bar + */ + private void showWait(boolean show) { + if (show) { + mProgressBar.setVisibility(View.VISIBLE); + } else { + mProgressBar.setVisibility(View.INVISIBLE); + } + } + + private void setMaxLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + mMaxLevel = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + am.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(mMaxLevel), 0); + } + + private void setMinLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0); + } + + /** + * Start the loopback audio test + */ + private void startAudioTest() { + if (mTestThread != null && !mTestThread.isAlive()) { + mTestThread = null; //kill it. + } + + if (mTestThread == null) { + Log.v(TAG,"Executing test Thread"); + mTestThread = new Thread(mPlayRunnable); + getPassButton().setEnabled(false); + if (!mSPlayer.isAlive()) + mSPlayer.start(); + mTestThread.start(); + } else { + Log.v(TAG,"test Thread already running."); + } + } + + Thread mTestThread; + Runnable mPlayRunnable = new Runnable() { + public void run() { + Message msg = Message.obtain(); + msg.what = TEST_STARTED; + mMessageHandler.sendMessage(msg); + + setMinLevel(); + sendMessage("Testing Background Environment"); + mCurrentTest = 0; + mSPlayer.setBalance(0.5f); + mFreqAverageBase.reset(); + play(); + + setMaxLevel(); + sendMessage("Testing Left Capture"); + mCurrentTest = 1; + mFreqAverageLeft.reset(); + mSPlayer.setBalance(0.0f); + play(); + + sendMessage("Testing Right Capture"); + mCurrentTest = 2; + mFreqAverageRight.reset(); + mSPlayer.setBalance(1.0f); + play(); + + mCurrentTest = -1; + sendMessage("Testing Completed"); + + Message msg2 = Message.obtain(); + msg2.what = TEST_ENDED; + mMessageHandler.sendMessage(msg2); + } + + private void play() { + startRecording(); + mSPlayer.play(true); + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + mSPlayer.play(false); + stopRecording(); + } + + private void sendMessage(String str) { + Message msg = Message.obtain(); + msg.what = TEST_MESSAGE; + msg.obj = str; + mMessageHandler.sendMessage(msg); + } + }; + + private Handler mMessageHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case TEST_STARTED: + showWait(true); + getPassButton().setEnabled(false); + break; + case TEST_ENDED: + showWait(false); + computeResults(); + break; + case TEST_MESSAGE: + String str = (String)msg.obj; + if (str != null) { + mResultText.setText(str); + } + break; + default: + Log.e(TAG, String.format("Unknown message: %d", msg.what)); + } + } + }; + + private class Results { + private String mLabel; + public double[] mValuesLog; + int[] mPointsPerBand = new int[mBands]; + double[] mAverageEnergyPerBand = new double[mBands]; + int[] mInBoundPointsPerBand = new int[mBands]; + public boolean mIsBaseMeasurement = false; + public Results(String label) { + mLabel = label; + } + + //append results + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("Channel %s\n", mLabel)); + sb.append("Level in Band 1 : " + (testLevel() ? "OK" :"FAILED") + + (mIsBaseMeasurement ? " (Base Meas.)" : "") + "\n"); + for (int b = 0; b < mBands; b++) { + double percent = 0; + if (mPointsPerBand[b] > 0) { + percent = 100.0 * (double)mInBoundPointsPerBand[b] / mPointsPerBand[b]; + } + sb.append(String.format( + " Band %d: Av. Level: %.1f dB InBand: %d/%d (%.1f%%) %s\n", + b, mAverageEnergyPerBand[b], + mInBoundPointsPerBand[b], + mPointsPerBand[b], + percent, + (testInBand(b) ? "OK" : "FAILED"))); + } + return sb.toString(); + } + + public boolean testLevel() { + if (mIsBaseMeasurement && mAverageEnergyPerBand[1] <= MAX_ENERGY_BAND_1_BASE) { + return true; + } else if (mAverageEnergyPerBand[1] >= MIN_ENERGY_BAND_1) { + return true; + } + return false; + } + + public boolean testInBand(int b) { + if (b >= 0 && b < mBands && mPointsPerBand[b] > 0) { + if ((double)mInBoundPointsPerBand[b] / mPointsPerBand[b] > + MIN_FRACTION_POINTS_IN_BAND) + return true; + } + return false; + } + + public boolean testAll() { + if (!testLevel()) { + return false; + } + for (int b = 0; b < mBands; b++) { + if (!testInBand(b)) { + return false; + } + } + return true; + } + } + + /** + * compute test results + */ + private void computeResults() { + + Results resultsBase = new Results("Base"); + computeResultsForVector(mFreqAverageBase, resultsBase, true, baseBandSpecsArray); + Results resultsLeft = new Results("Left"); + computeResultsForVector(mFreqAverageLeft, resultsLeft, false, bandSpecsArray); + Results resultsRight = new Results("Right"); + computeResultsForVector(mFreqAverageRight, resultsRight, false, bandSpecsArray); + if (resultsLeft.testAll() && resultsRight.testAll() && resultsBase.testAll()) { + //enable button + getPassButton().setEnabled(true); + } + } + + private void computeResultsForVector(VectorAverage freqAverage,Results results, boolean isBase, + AudioBandSpecs[] bandSpecs) { + + results.mIsBaseMeasurement = isBase; + int points = freqAverage.getSize(); + if (points > 0) { + //compute vector in db + double[] values = new double[points]; + freqAverage.getData(values, false); + results.mValuesLog = new double[points]; + for (int i = 0; i < points; i++) { + results.mValuesLog[i] = 20 * Math.log10(values[i]); + } + + int currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecs[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecs[currentBand].mFreqStart) { + results.mAverageEnergyPerBand[currentBand] += results.mValuesLog[i]; + results.mPointsPerBand[currentBand]++; + } + } + + for (int b = 0; b < mBands; b++) { + if (results.mPointsPerBand[b] > 0) { + results.mAverageEnergyPerBand[b] = + results.mAverageEnergyPerBand[b] / results.mPointsPerBand[b]; + } + } + + //set offset relative to band 1 level + for (int b = 0; b < mBands; b++) { + bandSpecs[b].setOffset(results.mAverageEnergyPerBand[1]); + } + + //test points in band. + currentBand = 0; + for (int i = 0; i < points; i++) { + double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples; + if (freq > bandSpecs[currentBand].mFreqStop) { + currentBand++; + if (currentBand >= mBands) + break; + } + + if (freq >= bandSpecs[currentBand].mFreqStart) { + double value = results.mValuesLog[i]; + if (bandSpecs[currentBand].isInBounds(freq, value)) { + results.mInBoundPointsPerBand[currentBand]++; + } + } + } + + appendResultsToScreen(results.toString()); + //store results + recordTestResults(results); + } else { + appendResultsToScreen("Failed testing channel " + results.mLabel); + } + } + + //append results + private void appendResultsToScreen(String str) { + String currentText = mResultText.getText().toString(); + mResultText.setText(currentText + "\n" + str); + } + + /** + * Store test results in log + */ + private void recordTestResults(Results results) { + String channelLabel = "channel_" + results.mLabel; + + for (int b = 0; b < mBands; b++) { + String bandLabel = String.format(channelLabel + "_%d", b); + getReportLog().addValue( + bandLabel + "_Level", + results.mAverageEnergyPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.NONE); + + getReportLog().addValue( + bandLabel + "_pointsinbound", + results.mInBoundPointsPerBand[b], + ResultType.HIGHER_BETTER, + ResultUnit.COUNT); + + getReportLog().addValue( + bandLabel + "_pointstotal", + results.mPointsPerBand[b], + ResultType.NEUTRAL, + ResultUnit.COUNT); + } + + getReportLog().addValues(channelLabel + "_magnitudeSpectrumLog", + results.mValuesLog, + ResultType.NEUTRAL, + ResultUnit.NONE); + + Log.v(TAG, "Results Recorded"); + } + + private void startRecording() { + synchronized (mRecordingLock) { + mIsRecording = true; + } + + boolean successful = initRecord(); + if (successful) { + startRecordingForReal(); + } else { + Log.v(TAG, "Recorder initialization error."); + synchronized (mRecordingLock) { + mIsRecording = false; + } + } + } + + private void startRecordingForReal() { + // start streaming + if (mRecordThread == null) { + mRecordThread = new Thread(AudioFrequencySpeakerActivity.this); + mRecordThread.setName("FrequencyAnalyzerThread"); + mRecordThreadShutdown = false; + } + if (!mRecordThread.isAlive()) { + mRecordThread.start(); + } + + mPipe.flush(); + + long startTime = SystemClock.uptimeMillis(); + mRecorder.startRecording(); + if (mRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) { + stopRecording(); + return; + } + Log.v(TAG, "Start time: " + (long) (SystemClock.uptimeMillis() - startTime) + " ms"); + } + + private void stopRecording() { + synchronized (mRecordingLock) { + stopRecordingForReal(); + mIsRecording = false; + } + } + + private void stopRecordingForReal() { + + // stop streaming + Thread zeThread = mRecordThread; + mRecordThread = null; + mRecordThreadShutdown = true; + if (zeThread != null) { + zeThread.interrupt(); + try { + zeThread.join(); + } catch(InterruptedException e) { + Log.v(TAG,"Error shutting down recording thread " + e); + //we don't really care about this error, just logging it. + } + } + // release recording resources + if (mRecorder != null) { + mRecorder.stop(); + mRecorder.release(); + mRecorder = null; + } + } + + private boolean initRecord() { + int minRecordBuffSizeInBytes = AudioRecord.getMinBufferSize(mSamplingRate, + mChannelConfig, mAudioFormat); + Log.v(TAG,"FrequencyAnalyzer: min buff size = " + minRecordBuffSizeInBytes + " bytes"); + if (minRecordBuffSizeInBytes <= 0) { + return false; + } + + mMinRecordBufferSizeInSamples = minRecordBuffSizeInBytes / 2; + // allocate the byte array to read the audio data + + mAudioShortArray = new short[mMinRecordBufferSizeInSamples]; + + Log.v(TAG, "Initiating record:"); + Log.v(TAG, " using source " + mSelectedRecordSource); + Log.v(TAG, " at " + mSamplingRate + "Hz"); + + try { + mRecorder = new AudioRecord(mSelectedRecordSource, mSamplingRate, + mChannelConfig, mAudioFormat, 2 * minRecordBuffSizeInBytes); + } catch (IllegalArgumentException e) { + return false; + } + if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) { + mRecorder.release(); + mRecorder = null; + return false; + } + mRecorder.setRecordPositionUpdateListener(this); + mRecorder.setPositionNotificationPeriod(mBlockSizeSamples / 2); + return true; + } + + // --------------------------------------------------------- + // Implementation of AudioRecord.OnPeriodicNotificationListener + // -------------------- + public void onPeriodicNotification(AudioRecord recorder) { + int samplesAvailable = mPipe.availableToRead(); + int samplesNeeded = mBlockSizeSamples; + if (samplesAvailable >= samplesNeeded) { + mPipe.read(mAudioShortArray2, 0, samplesNeeded); + + //compute stuff. + double maxval = Math.pow(2, 15); + int clipcount = 0; + double cliplevel = (maxval-10) / maxval; + double sum = 0; + double maxabs = 0; + int i; + int index = 0; + + for (i = 0; i < samplesNeeded; i++) { + double value = mAudioShortArray2[i] / maxval; + double valueabs = Math.abs(value); + + if (valueabs > maxabs) { + maxabs = valueabs; + } + + if (valueabs > cliplevel) { + clipcount++; + } + + sum += value * value; + //fft stuff + if (index < mBlockSizeSamples) { + mData.mData[index] = value; + } + index++; + } + + //for the current frame, compute FFT and send to the viewer. + + //apply window and pack as complex for now. + DspBufferMath.mult(mData, mData, mWindow.mBuffer); + DspBufferMath.set(mC, mData); + mFftServer.fft(mC, 1); + + double[] halfMagnitude = new double[mBlockSizeSamples / 2]; + for (i = 0; i < mBlockSizeSamples / 2; i++) { + halfMagnitude[i] = Math.sqrt(mC.mReal[i] * mC.mReal[i] + mC.mImag[i] * mC.mImag[i]); + } + + mFreqAverageMain.setData(halfMagnitude, false); //average all of them! + + switch(mCurrentTest) { + case 0: + mFreqAverageBase.setData(halfMagnitude, false); + break; + case 1: + mFreqAverageLeft.setData(halfMagnitude, false); + break; + case 2: + mFreqAverageRight.setData(halfMagnitude, false); + break; + } + } + } + + public void onMarkerReached(AudioRecord track) { + } + + // --------------------------------------------------------- + // Implementation of Runnable for the audio recording + playback + // -------------------- + public void run() { + int nSamplesRead = 0; + + Thread thisThread = Thread.currentThread(); + while (mRecordThread == thisThread && !mRecordThreadShutdown) { + // read from native recorder + nSamplesRead = mRecorder.read(mAudioShortArray, 0, mMinRecordBufferSizeInSamples); + if (nSamplesRead > 0) { + mPipe.write(mAudioShortArray, 0, nSamplesRead); + } + } + } + + private void testUSB() { + boolean isConnected = UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext()); + mUsbDevicesInfo = UsbMicrophoneTester.getUSBDeviceListString(getApplicationContext()); + + if (isConnected) { + mUsbStatusText.setText( + getResources().getText(R.string.audio_frequency_speaker_mic_ready_text)); + enableLayout(true); + } else { + mUsbStatusText.setText( + getResources().getText(R.string.audio_frequency_speaker_mic_not_ready_text)); + enableLayout(false); + } + } + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java new file mode 100644 index 0000000..e603a69 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java
@@ -0,0 +1,307 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.compatibility.common.util.ReportLog; +import com.android.compatibility.common.util.ResultType; +import com.android.compatibility.common.util.ResultUnit; +import android.content.Context; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioManager; +import android.media.AudioTrack; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; + +import android.util.Log; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; +import android.widget.SeekBar; +import android.widget.LinearLayout; +import android.widget.ProgressBar; + +/** + * Tests Audio Device roundtrip latency by using a loopback plug. + */ +public class AudioLoopbackActivity extends PassFailButtons.Activity { + private static final String TAG = "AudioLoopbackActivity"; + + public static final int BYTES_PER_FRAME = 2; + + NativeAudioThread nativeAudioThread = null; + + private int mSamplingRate = 44100; + private int mMinBufferSizeInFrames = 0; + private static final double CONFIDENCE_THRESHOLD = 0.6; + private Correlation mCorrelation = new Correlation(); + + OnBtnClickListener mBtnClickListener = new OnBtnClickListener(); + Context mContext; + + Button mLoopbackPlugReady; + TextView mAudioLevelText; + SeekBar mAudioLevelSeekbar; + LinearLayout mLinearLayout; + Button mTestButton; + TextView mResultText; + ProgressBar mProgressBar; + + int mMaxLevel; + private class OnBtnClickListener implements OnClickListener { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.audio_loopback_plug_ready_btn: + Log.i(TAG, "audio loopback plug ready"); + //enable all the other views. + enableLayout(true); + break; + case R.id.audio_loopback_test_btn: + Log.i(TAG, "audio loopback test"); + startAudioTest(); + break; + + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_loopback_activity); + + mContext = this; + + mLoopbackPlugReady = (Button)findViewById(R.id.audio_loopback_plug_ready_btn); + mLoopbackPlugReady.setOnClickListener(mBtnClickListener); + mLinearLayout = (LinearLayout)findViewById(R.id.audio_loopback_layout); + mAudioLevelText = (TextView)findViewById(R.id.audio_loopback_level_text); + mAudioLevelSeekbar = (SeekBar)findViewById(R.id.audio_loopback_level_seekbar); + mTestButton =(Button)findViewById(R.id.audio_loopback_test_btn); + mTestButton.setOnClickListener(mBtnClickListener); + mResultText = (TextView)findViewById(R.id.audio_loopback_results_text); + mProgressBar = (ProgressBar)findViewById(R.id.audio_loopback_progress_bar); + showWait(false); + + enableLayout(false); //disabled all content + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + mMaxLevel = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + mAudioLevelSeekbar.setMax(mMaxLevel); + am.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(0.7 * mMaxLevel), 0); + refreshLevel(); + + mAudioLevelSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + am.setStreamVolume(AudioManager.STREAM_MUSIC, + progress, 0); + refreshLevel(); + Log.i(TAG,"Changed stream volume to: " + progress); + } + }); + + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + setInfoResources(R.string.sample_test, R.string.audio_loopback_info, -1); + } + + /** + * refresh Audio Level seekbar and text + */ + private void refreshLevel() { + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + + int currentLevel = am.getStreamVolume(AudioManager.STREAM_MUSIC); + mAudioLevelSeekbar.setProgress(currentLevel); + + String levelText = String.format("%s: %d/%d", + getResources().getString(R.string.audio_loopback_level_text), + currentLevel, mMaxLevel); + mAudioLevelText.setText(levelText); + } + + /** + * enable test ui elements + */ + private void enableLayout(boolean enable) { + for (int i = 0; i<mLinearLayout.getChildCount(); i++) { + View view = mLinearLayout.getChildAt(i); + view.setEnabled(enable); + } + } + + /** + * show active progress bar + */ + private void showWait(boolean show) { + if (show) { + mProgressBar.setVisibility(View.VISIBLE) ; + } else { + mProgressBar.setVisibility(View.INVISIBLE) ; + } + } + + /** + * Start the loopback audio test + */ + private void startAudioTest() { + getPassButton().setEnabled(false); + + //get system defaults for sampling rate, buffers. + AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + String value = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER); + mMinBufferSizeInFrames = Integer.parseInt(value); + + int minBufferSizeInBytes = BYTES_PER_FRAME * mMinBufferSizeInFrames; + + mSamplingRate = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC); + + Log.i(TAG, String.format("startAudioTest sr:%d , buffer:%d frames", + mSamplingRate, mMinBufferSizeInFrames)); + + nativeAudioThread = new NativeAudioThread(); + if (nativeAudioThread != null) { + nativeAudioThread.setMessageHandler(mMessageHandler); + nativeAudioThread.mSessionId = 0; + nativeAudioThread.setParams(mSamplingRate, + minBufferSizeInBytes, + minBufferSizeInBytes, + 0x03 /*voice recognition*/); + nativeAudioThread.start(); + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + nativeAudioThread.runTest(); + + } + } + + /** + * handler for messages from audio thread + */ + private Handler mMessageHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch(msg.what) { + case NativeAudioThread.NATIVE_AUDIO_THREAD_MESSAGE_REC_STARTED: + Log.v(TAG,"got message native rec started!!"); + showWait(true); + mResultText.setText("Test Running..."); + break; + case NativeAudioThread.NATIVE_AUDIO_THREAD_MESSAGE_REC_ERROR: + Log.v(TAG,"got message native rec can't start!!"); + showWait(false); + mResultText.setText("Test Error."); + break; + case NativeAudioThread.NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE: + case NativeAudioThread.NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE_ERRORS: + if (nativeAudioThread != null) { + Log.v(TAG,"Finished recording."); + double [] waveData = nativeAudioThread.getWaveData(); + mCorrelation.computeCorrelation(waveData, mSamplingRate); + mResultText.setText(String.format( + "Test Finished\nLatency:%.2f ms\nConfidence: %.2f", + mCorrelation.mEstimatedLatencyMs, + mCorrelation.mEstimatedLatencyConfidence)); + + recordTestResults(); + if (mCorrelation.mEstimatedLatencyConfidence >= CONFIDENCE_THRESHOLD) { + getPassButton().setEnabled(true); + } + + //close + if (nativeAudioThread != null) { + nativeAudioThread.isRunning = false; + try { + nativeAudioThread.finish(); + nativeAudioThread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + nativeAudioThread = null; + } + showWait(false); + } + break; + default: + break; + } + } + }; + + /** + * Store test results in log + */ + private void recordTestResults() { + + getReportLog().addValue( + "Estimated Latency", + mCorrelation.mEstimatedLatencyMs, + ResultType.LOWER_BETTER, + ResultUnit.MS); + + getReportLog().addValue( + "Confidence", + mCorrelation.mEstimatedLatencyConfidence, + ResultType.HIGHER_BETTER, + ResultUnit.NONE); + + int audioLevel = mAudioLevelSeekbar.getProgress(); + getReportLog().addValue( + "Audio Level", + audioLevel, + ResultType.NEUTRAL, + ResultUnit.NONE); + + getReportLog().addValue( + "Frames Buffer Size", + mMinBufferSizeInFrames, + ResultType.NEUTRAL, + ResultUnit.NONE); + + getReportLog().addValue( + "Sampling Rate", + mSamplingRate, + ResultType.NEUTRAL, + ResultUnit.NONE); + + Log.v(TAG,"Results Recorded"); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRecordHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRecordHelper.java new file mode 100644 index 0000000..80dd250 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRecordHelper.java
@@ -0,0 +1,144 @@ +package com.android.cts.verifier.audio; + +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioRecord; +import android.media.AudioTrack; +import android.media.MediaRecorder; +import android.util.Log; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * A wrapper on AudioRecord class. + */ +public class AudioRecordHelper { + + private static final int[] SOURCE = { + MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.VOICE_RECOGNITION}; + private static final int[] SAMPLE_RATES_HZ = { + AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC), 48000, 44100}; + + private static final int CHANNEL = AudioFormat.CHANNEL_CONFIGURATION_MONO; + private static final int ENCODING = AudioFormat.ENCODING_PCM_16BIT; + private static final String TAG = "AudioRecordHelper"; + private static AudioRecordHelper instance; + private final int bufferSize; + private final int sampleRate; + private final int source; + private ByteArrayOutputStream os; + private AudioRecord audioRecord; + private volatile boolean isRecording = false; + + private AudioRecordHelper() { + int tmpBufferSize = 0; + int tmpSampleRate = 0; + int tmpSource = 0; + initialization: + for (int source : SOURCE) { + for (int rate : SAMPLE_RATES_HZ) { + tmpBufferSize = AudioRecord.getMinBufferSize(rate, CHANNEL, ENCODING); + AudioRecord testAudioRecord = new AudioRecord(source, rate, CHANNEL, ENCODING, + tmpBufferSize); + if (testAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) { + testAudioRecord.release(); + tmpSampleRate = rate; + tmpSource = source; + break initialization; + } + } + } + if (tmpBufferSize == 0 || tmpSampleRate == 0) { + Log.e(TAG, "Failed to initialize"); + } + bufferSize = tmpBufferSize; + sampleRate = tmpSampleRate; + source = tmpSource; + Log.d(TAG, "Sample rate = " + sampleRate + "Hz, Source = " + + source + " (VOICE_RECOGNITION = 6 , MIC = 1)"); + } + + public static AudioRecordHelper getInstance() { + if (instance == null) { + instance = new AudioRecordHelper(); + } + return instance; + } + + /** + * Start recording. + */ + public void start() { + if (!isRecording) { + isRecording = true; + os = new ByteArrayOutputStream(); + audioRecord = new AudioRecord(source, sampleRate, CHANNEL, ENCODING, bufferSize); + audioRecord.startRecording(); + startPullingData(); + } + } + + /** + * Stop recording + */ + public void stop() { + if (isRecording) { + isRecording = false; + audioRecord.stop(); + audioRecord.release(); + audioRecord = null; + try { + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private void startPullingData() { + new Thread() { + @Override + public void run(){ + byte data[] = new byte[bufferSize]; + while (isRecording) { + int read = audioRecord.read(data, 0, bufferSize); + if (read > 0) { + os.write(data, 0, read); + } + if (read < 0) { + break; + } + } + } + }.start(); + } + + /** + * Returns the sample rate for this recorder. + */ + public int getSampleRate() { + return sampleRate; + } + + /** + * Returns the audio source currently being used. + */ + public int getAudioSource() { + return source; + } + + /** + * Returns true if recorder is recording; False if not. + */ + public boolean isRecording() { + return isRecording; + } + + /** + * Returns the raw data. + */ + public byte[] getByte() { + return os.toByteArray(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRoutingNotificationsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRoutingNotificationsActivity.java new file mode 100644 index 0000000..47bc48a --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioRoutingNotificationsActivity.java
@@ -0,0 +1,146 @@ +/* + * Copyright (C) 2015 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.content.Context; + +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioManager; +import android.media.AudioRecord; +import android.media.AudioTrack; + +import android.os.Bundle; +import android.os.Handler; + +import android.util.Log; + +import android.view.View; +import android.view.View.OnClickListener; + +import android.widget.Button; +import android.widget.TextView; + +/** + * Tests AudioTrack and AudioRecord (re)Routing messages. + */ +public class AudioRoutingNotificationsActivity extends PassFailButtons.Activity { + private static final String TAG = "AudioRoutingNotificationsActivity"; + + Context mContext; + + OnBtnClickListener mBtnClickListener = new OnBtnClickListener(); + + int mNumTrackNotifications = 0; + int mNumRecordNotifications = 0; + + TrivialPlayer mAudioPlayer = new TrivialPlayer(); + TrivialRecorder mAudioRecorder = new TrivialRecorder(); + + private class OnBtnClickListener implements OnClickListener { + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.audio_routingnotification_playBtn: + mAudioPlayer.start(); + break; + + case R.id.audio_routingnotification_playStopBtn: + mAudioPlayer.stop(); + break; + + case R.id.audio_routingnotification_recordBtn: + mAudioRecorder.start(); + break; + + case R.id.audio_routingnotification_recordStopBtn: + mAudioRecorder.stop(); + break; + } + } + } + + private class AudioTrackRoutingChangeListener implements AudioTrack.OnRoutingChangedListener { + public void onRoutingChanged(AudioTrack audioTrack) { + mNumTrackNotifications++; + TextView textView = + (TextView)findViewById(R.id.audio_routingnotification_audioTrack_change); + String msg = mContext.getResources().getString( + R.string.audio_routingnotification_trackRoutingMsg); + AudioDeviceInfo routedDevice = audioTrack.getRoutedDevice(); + CharSequence deviceName = routedDevice != null ? routedDevice.getProductName() : "none"; + int deviceType = routedDevice != null ? routedDevice.getType() : -1; + textView.setText(msg + " - " + + deviceName + " [0x" + Integer.toHexString(deviceType) + "]" + + " - " + mNumTrackNotifications); + } + } + + private class AudioRecordRoutingChangeListener implements AudioRecord.OnRoutingChangedListener { + public void onRoutingChanged(AudioRecord audioRecord) { + mNumRecordNotifications++; + TextView textView = + (TextView)findViewById(R.id.audio_routingnotification_audioRecord_change); + String msg = mContext.getResources().getString( + R.string.audio_routingnotification_recordRoutingMsg); + AudioDeviceInfo routedDevice = audioRecord.getRoutedDevice(); + CharSequence deviceName = routedDevice != null ? routedDevice.getProductName() : "none"; + int deviceType = routedDevice != null ? routedDevice.getType() : -1; + textView.setText(msg + " - " + + deviceName + " [0x" + Integer.toHexString(deviceType) + "]" + + " - " + mNumRecordNotifications); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.audio_routingnotifications_test); + + Button btn; + btn = (Button)findViewById(R.id.audio_routingnotification_playBtn); + btn.setOnClickListener(mBtnClickListener); + btn = (Button)findViewById(R.id.audio_routingnotification_playStopBtn); + btn.setOnClickListener(mBtnClickListener); + btn = (Button)findViewById(R.id.audio_routingnotification_recordBtn); + btn.setOnClickListener(mBtnClickListener); + btn = (Button)findViewById(R.id.audio_routingnotification_recordStopBtn); + btn.setOnClickListener(mBtnClickListener); + + mContext = this; + + AudioTrack audioTrack = mAudioPlayer.getAudioTrack(); + audioTrack.addOnRoutingChangedListener( + new AudioTrackRoutingChangeListener(), new Handler()); + + AudioRecord audioRecord = mAudioRecorder.getAudioRecord(); + audioRecord.addOnRoutingChangedListener( + new AudioRecordRoutingChangeListener(), new Handler()); + + setPassFailButtonClickListeners(); + } + + @Override + public void onBackPressed () { + mAudioPlayer.shutDown(); + mAudioRecorder.shutDown(); + super.onBackPressed(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/Common.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Common.java new file mode 100644 index 0000000..df7460a --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Common.java
@@ -0,0 +1,142 @@ +package com.android.cts.verifier.audio; + +import android.media.AudioManager; +import android.media.AudioTrack; + +import java.util.ArrayList; +import java.util.Random; + +/** + * This class stores common constants and methods. + */ +public class Common { + + public static final int RECORDING_SAMPLE_RATE_HZ + = AudioRecordHelper.getInstance().getSampleRate(); + public static final int PLAYING_SAMPLE_RATE_HZ + = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC); + + // Default constants. + public static final double PASSING_THRESHOLD_DB = -40.0; + public static final double PIP_DURATION_S = 0.004; + public static final double PAUSE_DURATION_S = 0.016; + public static final int PREFIX_NUM_CHIPS = 1023; + public static final int PREFIX_SAMPLES_PER_CHIP = 4; + public static final double PREFIX_LENGTH_S = 0.1; + public static final double PAUSE_BEFORE_PREFIX_DURATION_S = 0.5; + public static final double PAUSE_AFTER_PREFIX_DURATION_S = 0.4; + public static final double MIN_FREQUENCY_HZ = 500; + public static final double MAX_FREQUENCY_HZ = 21000; + public static final double FREQUENCY_STEP_HZ = 100; + public static final int SIGNAL_MIN_STRENGTH_DB_ABOVE_NOISE = 10; + public static final int REPETITIONS = 5; + public static final int NOISE_SAMPLES = 3; + + public static final double[] FREQUENCIES_ORIGINAL = originalFrequencies(); + public static final int PIP_NUM = FREQUENCIES_ORIGINAL.length; + public static final int[] ORDER = order(); + public static final double[] FREQUENCIES = frequencies(); + + public static final double[] WINDOW_FOR_RECORDER = + hann(Util.toLength(PIP_DURATION_S, RECORDING_SAMPLE_RATE_HZ)); + public static final double[] WINDOW_FOR_PLAYER = + hann(Util.toLength(PIP_DURATION_S, PLAYING_SAMPLE_RATE_HZ)); + + public static final double[] PREFIX_FOR_RECORDER = prefix(RECORDING_SAMPLE_RATE_HZ); + public static final double[] PREFIX_FOR_PLAYER = prefix(PLAYING_SAMPLE_RATE_HZ); + + /** + * Get a Hann window. + */ + private static double[] hann(int windowWidth) { + double[] envelopeArray = new double[windowWidth]; + for (int i = 0; i < windowWidth; i++) { + envelopeArray[i] = 0.5 + * (1 - Math.cos(2 * Math.PI * i / windowWidth)); + } + return envelopeArray; + } + + /** + * Get a maximum length sequence, used as prefix to indicate start of signal. + */ + private static double[] prefix(int rate) { + double[] codeSequence = new double[PREFIX_NUM_CHIPS]; + for (int i = 0; i < PREFIX_NUM_CHIPS; i++) { + if (i < 10) { + codeSequence[i] = 1; + } else { + codeSequence[i] = -codeSequence[i - 6] * codeSequence[i - 7] + * codeSequence[i - 9] * codeSequence[i - 10]; + } + } + double[] prefixArray = new double[PREFIX_NUM_CHIPS * PREFIX_SAMPLES_PER_CHIP]; + int offset = 0; + for (int i = 0; i < PREFIX_NUM_CHIPS; i++) { + double value = codeSequence[i]; + for (int j = 0; j < PREFIX_SAMPLES_PER_CHIP; j++) { + prefixArray[offset + j] = value; + } + offset += PREFIX_SAMPLES_PER_CHIP; + } + int prefixLength = (int) Math.round(PREFIX_LENGTH_S * rate); + double[] samplePrefixArray = new double[prefixLength]; + for (int i = 0; i < prefixLength; i++) { + double index = (double) i / prefixLength * (prefixArray.length - 1); + samplePrefixArray[i] = (1 - index + Math.floor(index)) * prefixArray[(int) Math.floor(index)] + + (1 + index - Math.ceil(index)) * prefixArray[(int) Math.ceil(index)]; + } + return samplePrefixArray; + } + + /** + * Returns array consists the frequencies of the test pips in the order that will be used in test. + */ + private static double[] frequencies() { + double[] originalFrequencies = originalFrequencies(); + + double[] randomFrequencies = new double[Common.REPETITIONS * originalFrequencies.length]; + for (int i = 0; i < REPETITIONS * originalFrequencies.length; i++) { + randomFrequencies[i] = originalFrequencies[ORDER[i] % originalFrequencies.length]; + } + + return randomFrequencies; + } + + /** + * Returns array consists the frequencies of the test pips. + */ + private static double[] originalFrequencies() { + ArrayList<Double> frequencies = new ArrayList<Double>(); + double frequency = Common.MIN_FREQUENCY_HZ; + while (frequency <= Common.MAX_FREQUENCY_HZ) { + frequencies.add(new Double(frequency)); + if ((frequency >= 18500) && (frequency < 20000)) { + frequency += Common.FREQUENCY_STEP_HZ; + } else { + frequency += Common.FREQUENCY_STEP_HZ * 10; + } + } + Double[] frequenciesArray = frequencies.toArray(new Double[frequencies.size()]); + double[] frequenciesPrimitiveArray = new double[frequenciesArray.length]; + for (int i = 0; i < frequenciesArray.length; i++) { + frequenciesPrimitiveArray[i] = frequenciesArray[i]; + } + return frequenciesPrimitiveArray; + } + + /** + * Fisher-Yates shuffle. + */ + private static int[] order() { + int[] order = new int[REPETITIONS * PIP_NUM]; + long seed = 0; + Random generator = new Random(seed); + for (int i = 0; i < REPETITIONS * PIP_NUM; i++) { + int j = generator.nextInt(i + 1); + order[i] = order[j]; + order[j] = i; + } + return order; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/Correlation.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Correlation.java new file mode 100644 index 0000000..75b04eb --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Correlation.java
@@ -0,0 +1,156 @@ +/* + * Copyright (C) 2015 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.audio; + +import android.util.Log; + + +public class Correlation { + + private int mBlockSize = 4096; + private int mSamplingRate = 44100; + private double [] mDataDownsampled = new double [mBlockSize]; + private double [] mDataAutocorrelated = new double[mBlockSize]; + + public double mEstimatedLatencySamples = 0; + public double mEstimatedLatencyMs = 0; + public double mEstimatedLatencyConfidence = 0.0; + + public void init(int blockSize, int samplingRate) { + mBlockSize = blockSize; + mSamplingRate = samplingRate; + } + + public boolean computeCorrelation(double [] data, int samplingRate) { + boolean status = false; + log("Started Auto Correlation for data with " + data.length + " points"); + mSamplingRate = samplingRate; + + downsampleData(data, mDataDownsampled); + + //correlation vector + autocorrelation(mDataDownsampled, mDataAutocorrelated); + + int N = data.length; //all samples available + double groupSize = (double) N / mBlockSize; //samples per downsample point. + + double maxValue = 0; + int maxIndex = -1; + + double minLatencyMs = 8; //min latency expected. This algorithm should be improved. + int minIndex = (int)(0.5 + minLatencyMs * mSamplingRate / (groupSize*1000)); + + double average = 0; + double rms = 0; + //find max + for (int i=minIndex; i<mDataAutocorrelated.length; i++) { + average += mDataAutocorrelated[i]; + rms += mDataAutocorrelated[i]*mDataAutocorrelated[i]; + if (mDataAutocorrelated[i] > maxValue) { + maxValue = mDataAutocorrelated[i]; + maxIndex = i; + } + } + + rms = Math.sqrt(rms/mDataAutocorrelated.length); + average = average/mDataAutocorrelated.length; + log(String.format(" Maxvalue %f, max Index : %d/%d (%d) minIndex=%d",maxValue, maxIndex, + mDataAutocorrelated.length, data.length, minIndex)); + + log(String.format(" average : %.3f rms: %.3f", average, rms)); + + mEstimatedLatencyConfidence = 0.0; + if (average>0) { + double factor = 3.0; + + double raw = (rms-average) /(factor*average); + log(String.format("Raw: %.3f",raw)); + mEstimatedLatencyConfidence = Math.max(Math.min(raw, 1.0),0.0); + } + + log(String.format(" ****Confidence: %.2f",mEstimatedLatencyConfidence)); + + mEstimatedLatencySamples = maxIndex*groupSize; + + mEstimatedLatencyMs = mEstimatedLatencySamples *1000/mSamplingRate; + + log(String.format(" latencySamples: %.2f %.2f ms", mEstimatedLatencySamples, + mEstimatedLatencyMs)); + + status = true; + return status; + } + + private boolean downsampleData(double [] data, double [] dataDownsampled) { + + boolean status = false; + // mDataDownsampled = new double[mBlockSize]; + for (int i=0; i<mBlockSize; i++) { + dataDownsampled[i] = 0; + } + + int N = data.length; //all samples available + double groupSize = (double) N / mBlockSize; + + int currentIndex = 0; + double nextGroup = groupSize; + for (int i = 0; i<N && currentIndex<mBlockSize; i++) { + + if (i> nextGroup) { //advanced to next group. + currentIndex++; + nextGroup += groupSize; + } + + if (currentIndex>=mBlockSize) { + break; + } + dataDownsampled[currentIndex] += Math.abs(data[i]); + } + + status = true; + return status; + } + + private boolean autocorrelation(double [] data, double [] dataOut) { + boolean status = false; + + double sumsquared = 0; + int N = data.length; + for (int i=0; i<N; i++) { + double value = data[i]; + sumsquared += value*value; + } + + if (sumsquared>0) { + for (int i = 0; i < N; i++) { + dataOut[i] = 0; + for (int j = 0; j < N - i; j++) { + + dataOut[i] += data[j] * data[i + j]; + } + dataOut[i] = dataOut[i] / sumsquared; + } + status = true; + } + + return status; + } + + private static void log(String msg) { + Log.v("Recorder", msg); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundSpeakerTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundSpeakerTestActivity.java new file mode 100644 index 0000000..dc81e19 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundSpeakerTestActivity.java
@@ -0,0 +1,430 @@ +/* + * Copyright (C) 2011 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.content.Context; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.os.AsyncTask; +import android.os.Bundle; +import android.text.method.ScrollingMovementMethod; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.LinearLayout.LayoutParams; +import android.widget.PopupWindow; +import android.widget.TextView; +import java.util.Arrays; + +import com.androidplot.xy.SimpleXYSeries; +import com.androidplot.xy.XYSeries; +import com.androidplot.xy.*; + +public class HifiUltrasoundSpeakerTestActivity extends PassFailButtons.Activity { + + public enum Status { + START, RECORDING, DONE, PLAYER + } + + private static final String TAG = "HifiUltrasoundTestActivity"; + + private Status status = Status.START; + private boolean onPlotScreen = false; + private boolean onInstruScreen = false; + private TextView info; + private Button playerButton; + private Button recorderButton; + private AudioTrack audioTrack; + private LayoutInflater layoutInflater; + private View popupView; + private View instruView; + private PopupWindow popupWindow; + private PopupWindow instruWindow; + private boolean micSupport = true; + private boolean spkrSupport = true; + + @Override + public void onBackPressed () { + if (onPlotScreen) { + popupWindow.dismiss(); + onPlotScreen = false; + recorderButton.setEnabled(true); + } else if (onInstruScreen) { + instruWindow.dismiss(); + onInstruScreen = false; + if (status == Status.PLAYER) { + playerButton.setEnabled(spkrSupport); + } else { + recorderButton.setEnabled(micSupport); + } + if (status == Status.PLAYER) { + getPassButton().setEnabled(true); + } + } else { + super.onBackPressed(); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.hifi_ultrasound); + setInfoResources(R.string.hifi_ultrasound_speaker_test, + R.string.hifi_ultrasound_speaker_test_info, -1); + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + + info = (TextView) findViewById(R.id.info_text); + info.setMovementMethod(new ScrollingMovementMethod()); + info.setText(R.string.hifi_ultrasound_speaker_test_instruction1); + + AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + String micSupportString = audioManager.getProperty( + AudioManager.PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND); + String spkrSupportString = audioManager.getProperty( + AudioManager.PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND); + Log.d(TAG, "PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND = " + micSupportString); + Log.d(TAG, "PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND = " + spkrSupportString); + + if (micSupportString == null) { + micSupportString = "null"; + } + if (spkrSupportString == null) { + spkrSupportString = "null"; + } + if (micSupportString.equalsIgnoreCase(getResources().getString( + R.string.hifi_ultrasound_test_default_false_string))) { + micSupport = false; + getPassButton().setEnabled(true); + info.append(getResources().getString(R.string.hifi_ultrasound_speaker_test_mic_no_support)); + } + if (spkrSupportString.equalsIgnoreCase(getResources().getString( + R.string.hifi_ultrasound_test_default_false_string))) { + spkrSupport = false; + info.append(getResources().getString(R.string.hifi_ultrasound_speaker_test_spkr_no_support)); + } + + layoutInflater = (LayoutInflater) getBaseContext().getSystemService( + LAYOUT_INFLATER_SERVICE); + popupView = layoutInflater.inflate(R.layout.hifi_ultrasound_popup, null); + popupWindow = new PopupWindow( + popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + instruView = layoutInflater.inflate(R.layout.hifi_ultrasound_popup_instru, null); + instruWindow = new PopupWindow( + instruView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + + final AudioRecordHelper audioRecorder = AudioRecordHelper.getInstance(); + final int recordRate = audioRecorder.getSampleRate(); + + recorderButton = (Button) findViewById(R.id.recorder_button); + recorderButton.setEnabled(micSupport); + recorderButton.setOnClickListener(new View.OnClickListener() { + private WavAnalyzerTask wavAnalyzerTask = null; + private void stopRecording() { + audioRecorder.stop(); + wavAnalyzerTask = new WavAnalyzerTask(audioRecorder.getByte()); + wavAnalyzerTask.execute(); + status = Status.DONE; + } + @Override + public void onClick(View v) { + switch (status) { + case START: + info.append("Recording at " + recordRate + "Hz using "); + final int source = audioRecorder.getAudioSource(); + switch (source) { + case 1: + info.append("MIC"); + break; + case 6: + info.append("VOICE_RECOGNITION"); + break; + default: + info.append("UNEXPECTED " + source); + break; + } + info.append("\n"); + status = Status.RECORDING; + playerButton.setEnabled(false); + recorderButton.setEnabled(false); + audioRecorder.start(); + + final View finalV = v; + new Thread() { + @Override + public void run() { + Double recordingDuration_millis = new Double(1000 * (2.5 + + Common.PREFIX_LENGTH_S + + Common.PAUSE_BEFORE_PREFIX_DURATION_S + + Common.PAUSE_AFTER_PREFIX_DURATION_S + + Common.PIP_NUM * (Common.PIP_DURATION_S + Common.PAUSE_DURATION_S) + * Common.REPETITIONS)); + Log.d(TAG, "Recording for " + recordingDuration_millis + "ms"); + try { + Thread.sleep(recordingDuration_millis.intValue()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + runOnUiThread(new Runnable() { + @Override + public void run() { + stopRecording(); + } + }); + } + }.start(); + + break; + + case DONE: + plotResponse(wavAnalyzerTask); + break; + + default: break; + } + } + }); + + playerButton = (Button) findViewById(R.id.player_button); + playerButton.setEnabled(spkrSupport); + playerButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + recorderButton.setEnabled(false); + status = Status.PLAYER; + play(); + + Button okButton = (Button)instruView.findViewById(R.id.ok); + okButton.setOnClickListener(new Button.OnClickListener() { + @Override + public void onClick(View v) { + instruWindow.dismiss(); + onInstruScreen = false; + if (status == Status.PLAYER) { + playerButton.setEnabled(spkrSupport); + } else { + recorderButton.setEnabled(micSupport); + } + getPassButton().setEnabled(true); + } + }); + TextView instruction = (TextView)instruView.findViewById(R.id.instru); + instruction.setText(R.string.hifi_ultrasound_speaker_test_test_side); + instruWindow.showAtLocation(info, Gravity.CENTER, 0, 0); + recorderButton.setEnabled(false); + playerButton.setEnabled(false); + onInstruScreen = true; + } + }); + } + + private void plotResponse(WavAnalyzerTask wavAnalyzerTask) { + Button dismissButton = (Button)popupView.findViewById(R.id.dismiss); + dismissButton.setOnClickListener(new Button.OnClickListener(){ + @Override + public void onClick(View v) { + popupWindow.dismiss(); + onPlotScreen = false; + recorderButton.setEnabled(true); + }}); + popupWindow.showAtLocation(info, Gravity.CENTER, 0, 0); + onPlotScreen = true; + + recorderButton.setEnabled(false); + + XYPlot plot = (XYPlot) popupView.findViewById(R.id.responseChart); + plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 2000); + + Double[] frequencies = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + frequencies[i] = new Double(Common.FREQUENCIES_ORIGINAL[i]); + } + + if (wavAnalyzerTask != null) { + + double[][] power = wavAnalyzerTask.getPower(); + for(int i = 0; i < Common.REPETITIONS; i++) { + Double[] powerWrap = new Double[Common.PIP_NUM]; + for (int j = 0; j < Common.PIP_NUM; j++) { + powerWrap[j] = new Double(10 * Math.log10(power[j][i])); + } + XYSeries series = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(powerWrap), + ""); + LineAndPointFormatter seriesFormat = new LineAndPointFormatter(); + seriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_trials); + seriesFormat.setPointLabelFormatter(null); + plot.addSeries(series, seriesFormat); + } + + double[] noiseDB = wavAnalyzerTask.getNoiseDB(); + Double[] noiseDBWrap = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + noiseDBWrap[i] = new Double(noiseDB[i]); + } + + XYSeries noiseSeries = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(noiseDBWrap), + "background noise"); + LineAndPointFormatter noiseSeriesFormat = new LineAndPointFormatter(); + noiseSeriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_noise); + noiseSeriesFormat.setPointLabelFormatter(null); + plot.addSeries(noiseSeries, noiseSeriesFormat); + + double[] dB = wavAnalyzerTask.getDB(); + Double[] dBWrap = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + dBWrap[i] = new Double(dB[i]); + } + + XYSeries series = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(dBWrap), + "median"); + LineAndPointFormatter seriesFormat = new LineAndPointFormatter(); + seriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_median); + seriesFormat.setPointLabelFormatter(null); + plot.addSeries(series, seriesFormat); + + Double[] passX = new Double[] {Common.MIN_FREQUENCY_HZ, Common.MAX_FREQUENCY_HZ}; + Double[] passY = new Double[] {wavAnalyzerTask.getThreshold(), wavAnalyzerTask.getThreshold()}; + XYSeries passSeries = new SimpleXYSeries( + Arrays.asList(passX), Arrays.asList(passY), "passing"); + LineAndPointFormatter passSeriesFormat = new LineAndPointFormatter(); + passSeriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_pass); + passSeriesFormat.setPointLabelFormatter(null); + plot.addSeries(passSeries, passSeriesFormat); + } + } + + /** + * Plays the generated pips. + */ + private void play() { + play(SoundGenerator.getInstance().getByte(), Common.PLAYING_SAMPLE_RATE_HZ); + } + + /** + * Plays the sound data. + */ + private void play(byte[] data, int sampleRate) { + if (audioTrack != null) { + audioTrack.stop(); + audioTrack.release(); + } + audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, + sampleRate, AudioFormat.CHANNEL_OUT_MONO, + AudioFormat.ENCODING_PCM_16BIT, Math.max(data.length, AudioTrack.getMinBufferSize( + sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)), + AudioTrack.MODE_STATIC); + audioTrack.write(data, 0, data.length); + audioTrack.play(); + } + + /** + * AsyncTask class for the analyzing. + */ + private class WavAnalyzerTask extends AsyncTask<Void, String, String> + implements WavAnalyzer.Listener { + + private static final String TAG = "WavAnalyzerTask"; + WavAnalyzer wavAnalyzer; + + public WavAnalyzerTask(byte[] recording) { + wavAnalyzer = new WavAnalyzer(recording, Common.RECORDING_SAMPLE_RATE_HZ, + WavAnalyzerTask.this); + } + + double[] getDB() { + return wavAnalyzer.getDB(); + } + + double[][] getPower() { + return wavAnalyzer.getPower(); + } + + double[] getNoiseDB() { + return wavAnalyzer.getNoiseDB(); + } + + double getThreshold() { + return wavAnalyzer.getThreshold(); + } + + @Override + protected String doInBackground(Void... params) { + boolean result = wavAnalyzer.doWork(); + if (result) { + return getString(R.string.hifi_ultrasound_test_pass); + } + return getString(R.string.hifi_ultrasound_test_fail); + } + + @Override + protected void onPostExecute(String result) { + info.append(result); + recorderButton.setEnabled(true); + recorderButton.setText(R.string.hifi_ultrasound_test_plot); + + Button okButton = (Button)instruView.findViewById(R.id.ok); + okButton.setOnClickListener(new Button.OnClickListener() { + @Override + public void onClick(View v) { + instruWindow.dismiss(); + onInstruScreen = false; + if (status == HifiUltrasoundSpeakerTestActivity.Status.PLAYER) { + playerButton.setEnabled(spkrSupport); + } else { + recorderButton.setEnabled(micSupport); + } + } + }); + TextView instruction = (TextView) instruView.findViewById(R.id.instru); + instruction.setText(R.string.hifi_ultrasound_speaker_test_reference_side); + instruWindow.showAtLocation(info, Gravity.CENTER, 0, 0); + recorderButton.setEnabled(false); + playerButton.setEnabled(false); + onInstruScreen = true; + } + + @Override + protected void onProgressUpdate(String... values) { + for (String message : values) { + info.append(message); + Log.d(TAG, message); + } + } + + @Override + public void sendMessage(String message) { + publishProgress(message); + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java new file mode 100644 index 0000000..85b3e37 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java
@@ -0,0 +1,374 @@ +/* + * Copyright (C) 2011 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.audio; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.content.Context; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.os.AsyncTask; +import android.os.Bundle; +import android.text.method.ScrollingMovementMethod; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.LinearLayout.LayoutParams; +import android.widget.PopupWindow; +import android.widget.TextView; +import java.util.Arrays; + +import com.androidplot.xy.SimpleXYSeries; +import com.androidplot.xy.XYSeries; +import com.androidplot.xy.*; + +public class HifiUltrasoundTestActivity extends PassFailButtons.Activity { + + public enum Status { + START, RECORDING, DONE, PLAYER + } + + private static final String TAG = "HifiUltrasoundTestActivity"; + + private Status status = Status.START; + private boolean onPlotScreen = false; + private TextView info; + private Button playerButton; + private Button recorderButton; + private AudioTrack audioTrack; + private LayoutInflater layoutInflater; + private View popupView; + private PopupWindow popupWindow; + private boolean micSupport = true; + private boolean spkrSupport = true; + + @Override + public void onBackPressed () { + if (onPlotScreen) { + popupWindow.dismiss(); + onPlotScreen = false; + recorderButton.setEnabled(true); + } else { + super.onBackPressed(); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.hifi_ultrasound); + setInfoResources(R.string.hifi_ultrasound_test, R.string.hifi_ultrasound_test_info, -1); + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + + info = (TextView) findViewById(R.id.info_text); + info.setMovementMethod(new ScrollingMovementMethod()); + info.setText(R.string.hifi_ultrasound_test_instruction1); + + AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + String micSupportString = audioManager.getProperty( + AudioManager.PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND); + String spkrSupportString = audioManager.getProperty( + AudioManager.PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND); + Log.d(TAG, "PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND = " + micSupportString); + Log.d(TAG, "PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND = " + spkrSupportString); + + if (micSupportString == null) { + micSupportString = "null"; + } + if (spkrSupportString == null) { + spkrSupportString = "null"; + } + if (micSupportString.equalsIgnoreCase(getResources().getString( + R.string.hifi_ultrasound_test_default_false_string))) { + micSupport = false; + getPassButton().setEnabled(true); + info.append(getResources().getString(R.string.hifi_ultrasound_test_mic_no_support)); + } + if (spkrSupportString.equalsIgnoreCase(getResources().getString( + R.string.hifi_ultrasound_test_default_false_string))) { + spkrSupport = false; + info.append(getResources().getString(R.string.hifi_ultrasound_test_spkr_no_support)); + } + + layoutInflater = (LayoutInflater) getBaseContext().getSystemService( + LAYOUT_INFLATER_SERVICE); + popupView = layoutInflater.inflate(R.layout.hifi_ultrasound_popup, null); + popupWindow = new PopupWindow( + popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + + final AudioRecordHelper audioRecorder = AudioRecordHelper.getInstance(); + final int recordRate = audioRecorder.getSampleRate(); + + recorderButton = (Button) findViewById(R.id.recorder_button); + recorderButton.setEnabled(micSupport); + recorderButton.setOnClickListener(new View.OnClickListener() { + private WavAnalyzerTask wavAnalyzerTask = null; + private void stopRecording() { + audioRecorder.stop(); + wavAnalyzerTask = new WavAnalyzerTask(audioRecorder.getByte()); + wavAnalyzerTask.execute(); + status = Status.DONE; + } + @Override + public void onClick(View v) { + switch (status) { + case START: + info.append("Recording at " + recordRate + "Hz using "); + final int source = audioRecorder.getAudioSource(); + switch (source) { + case 1: + info.append("MIC"); + break; + case 6: + info.append("VOICE_RECOGNITION"); + break; + default: + info.append("UNEXPECTED " + source); + break; + } + info.append("\n"); + status = Status.RECORDING; + playerButton.setEnabled(false); + recorderButton.setEnabled(false); + audioRecorder.start(); + + final View finalV = v; + new Thread() { + @Override + public void run() { + Double recordingDuration_millis = new Double(1000 * (2.5 + + Common.PREFIX_LENGTH_S + + Common.PAUSE_BEFORE_PREFIX_DURATION_S + + Common.PAUSE_AFTER_PREFIX_DURATION_S + + Common.PIP_NUM * (Common.PIP_DURATION_S + Common.PAUSE_DURATION_S) + * Common.REPETITIONS)); + Log.d(TAG, "Recording for " + recordingDuration_millis + "ms"); + try { + Thread.sleep(recordingDuration_millis.intValue()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + runOnUiThread(new Runnable() { + @Override + public void run() { + stopRecording(); + } + }); + } + }.start(); + + break; + + case DONE: + plotResponse(wavAnalyzerTask); + break; + + default: break; + } + } + }); + + playerButton = (Button) findViewById(R.id.player_button); + playerButton.setEnabled(spkrSupport); + playerButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + recorderButton.setEnabled(false); + status = Status.PLAYER; + play(); + } + }); + } + + private void plotResponse(WavAnalyzerTask wavAnalyzerTask) { + Button dismissButton = (Button)popupView.findViewById(R.id.dismiss); + dismissButton.setOnClickListener(new Button.OnClickListener(){ + @Override + public void onClick(View v) { + popupWindow.dismiss(); + onPlotScreen = false; + recorderButton.setEnabled(true); + }}); + popupWindow.showAtLocation(info, Gravity.CENTER, 0, 0); + onPlotScreen = true; + + recorderButton.setEnabled(false); + + XYPlot plot = (XYPlot) popupView.findViewById(R.id.responseChart); + plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 2000); + + Double[] frequencies = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + frequencies[i] = new Double(Common.FREQUENCIES_ORIGINAL[i]); + } + + if (wavAnalyzerTask != null) { + + double[][] power = wavAnalyzerTask.getPower(); + for(int i = 0; i < Common.REPETITIONS; i++) { + Double[] powerWrap = new Double[Common.PIP_NUM]; + for (int j = 0; j < Common.PIP_NUM; j++) { + powerWrap[j] = new Double(10 * Math.log10(power[j][i])); + } + XYSeries series = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(powerWrap), + ""); + LineAndPointFormatter seriesFormat = new LineAndPointFormatter(); + seriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_trials); + seriesFormat.setPointLabelFormatter(null); + plot.addSeries(series, seriesFormat); + } + + double[] noiseDB = wavAnalyzerTask.getNoiseDB(); + Double[] noiseDBWrap = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + noiseDBWrap[i] = new Double(noiseDB[i]); + } + + XYSeries noiseSeries = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(noiseDBWrap), + "background noise"); + LineAndPointFormatter noiseSeriesFormat = new LineAndPointFormatter(); + noiseSeriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_noise); + noiseSeriesFormat.setPointLabelFormatter(null); + plot.addSeries(noiseSeries, noiseSeriesFormat); + + double[] dB = wavAnalyzerTask.getDB(); + Double[] dBWrap = new Double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + dBWrap[i] = new Double(dB[i]); + } + + XYSeries series = new SimpleXYSeries( + Arrays.asList(frequencies), + Arrays.asList(dBWrap), + "median"); + LineAndPointFormatter seriesFormat = new LineAndPointFormatter(); + seriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_median); + seriesFormat.setPointLabelFormatter(null); + plot.addSeries(series, seriesFormat); + + Double[] passX = new Double[] {Common.MIN_FREQUENCY_HZ, Common.MAX_FREQUENCY_HZ}; + Double[] passY = new Double[] {wavAnalyzerTask.getThreshold(), wavAnalyzerTask.getThreshold()}; + XYSeries passSeries = new SimpleXYSeries( + Arrays.asList(passX), Arrays.asList(passY), "passing"); + LineAndPointFormatter passSeriesFormat = new LineAndPointFormatter(); + passSeriesFormat.configure(getApplicationContext(), + R.xml.ultrasound_line_formatter_pass); + passSeriesFormat.setPointLabelFormatter(null); + plot.addSeries(passSeries, passSeriesFormat); + } + } + + /** + * Plays the generated pips. + */ + private void play() { + play(SoundGenerator.getInstance().getByte(), Common.PLAYING_SAMPLE_RATE_HZ); + } + + /** + * Plays the sound data. + */ + private void play(byte[] data, int sampleRate) { + if (audioTrack != null) { + audioTrack.stop(); + audioTrack.release(); + } + audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, + sampleRate, AudioFormat.CHANNEL_OUT_MONO, + AudioFormat.ENCODING_PCM_16BIT, Math.max(data.length, AudioTrack.getMinBufferSize( + sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)), + AudioTrack.MODE_STATIC); + audioTrack.write(data, 0, data.length); + audioTrack.play(); + } + + /** + * AsyncTask class for the analyzing. + */ + private class WavAnalyzerTask extends AsyncTask<Void, String, String> + implements WavAnalyzer.Listener { + + private static final String TAG = "WavAnalyzerTask"; + WavAnalyzer wavAnalyzer; + + public WavAnalyzerTask(byte[] recording) { + wavAnalyzer = new WavAnalyzer(recording, Common.RECORDING_SAMPLE_RATE_HZ, + WavAnalyzerTask.this); + } + + double[] getDB() { + return wavAnalyzer.getDB(); + } + + double[][] getPower() { + return wavAnalyzer.getPower(); + } + + double[] getNoiseDB() { + return wavAnalyzer.getNoiseDB(); + } + + double getThreshold() { + return wavAnalyzer.getThreshold(); + } + + @Override + protected String doInBackground(Void... params) { + boolean result = wavAnalyzer.doWork(); + if (result) { + return getString(R.string.hifi_ultrasound_test_pass); + } + return getString(R.string.hifi_ultrasound_test_fail); + } + + @Override + protected void onPostExecute(String result) { + info.append(result); + recorderButton.setEnabled(true); + if (wavAnalyzer.getResult()) { + getPassButton().setEnabled(true); + } + recorderButton.setText(R.string.hifi_ultrasound_test_plot); + } + + @Override + protected void onProgressUpdate(String... values) { + for (String message : values) { + info.append(message); + Log.d(TAG, message); + } + } + + @Override + public void sendMessage(String message) { + publishProgress(message); + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/NativeAudioThread.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/NativeAudioThread.java new file mode 100644 index 0000000..224d4c8 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/NativeAudioThread.java
@@ -0,0 +1,273 @@ +/* + * Copyright (C) 2015 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 org.drrickorang.loopback; + +package com.android.cts.verifier.audio; + +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +//import android.media.MediaPlayer; +import android.media.AudioRecord; +import android.media.MediaRecorder; +import android.util.Log; + +import android.os.Handler; +import android.os.Message; + +/** + * A thread/audio track based audio synth. + */ +public class NativeAudioThread extends Thread { + + public boolean isRunning = false; + double twoPi = 6.28318530718; + + public int mSessionId; + + public double[] mvSamples; //captured samples + int mSamplesIndex; + + private final int mSecondsToRun = 2; + public int mSamplingRate = 48000; + private int mChannelConfigIn = AudioFormat.CHANNEL_IN_MONO; + private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + + int mMinPlayBufferSizeInBytes = 0; + int mMinRecordBuffSizeInBytes = 0; + private int mChannelConfigOut = AudioFormat.CHANNEL_OUT_MONO; + + int mMicSource = 0; + +// private double [] samples = new double[50000]; + + boolean isPlaying = false; + private Handler mMessageHandler; + boolean isDestroying = false; + boolean hasDestroyingErrors = false; + + static final int NATIVE_AUDIO_THREAD_MESSAGE_REC_STARTED = 892; + static final int NATIVE_AUDIO_THREAD_MESSAGE_REC_ERROR = 893; + static final int NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE = 894; + static final int NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE_ERRORS = 895; + + public void setParams(int samplingRate, int playBufferInBytes, int recBufferInBytes, + int micSource) { + mSamplingRate = samplingRate; + mMinPlayBufferSizeInBytes = playBufferInBytes; + mMinRecordBuffSizeInBytes = recBufferInBytes; + mMicSource = micSource; + } + + //JNI load + static { + try { + System.loadLibrary("audioloopback_jni"); + } catch (UnsatisfiedLinkError e) { + log("Error loading loopback JNI library"); + e.printStackTrace(); + } + + /* TODO: gracefully fail/notify if the library can't be loaded */ + } + + //jni calls + public native long slesInit(int samplingRate, int frameCount, int micSource); + public native int slesProcessNext(long sles_data, double[] samples, long offset); + public native int slesDestroy(long sles_data); + + public void run() { + + setPriority(Thread.MAX_PRIORITY); + isRunning = true; + + //erase output buffer + if (mvSamples != null) + mvSamples = null; + + //resize + int nNewSize = (int)(1.1* mSamplingRate * mSecondsToRun ); //10% more just in case + mvSamples = new double[nNewSize]; + mSamplesIndex = 0; //reset index + + //clear samples + for (int i=0; i<nNewSize; i++) { + mvSamples[i] = 0; + } + + //start playing + isPlaying = true; + + + log(" Started capture test"); + if (mMessageHandler != null) { + Message msg = Message.obtain(); + msg.what = NATIVE_AUDIO_THREAD_MESSAGE_REC_STARTED; + mMessageHandler.sendMessage(msg); + } + + + + log(String.format("about to init, sampling rate: %d, buffer:%d", mSamplingRate, + mMinPlayBufferSizeInBytes/2 )); + long sles_data = slesInit(mSamplingRate, mMinPlayBufferSizeInBytes/2, mMicSource); + log(String.format("sles_data = 0x%X",sles_data)); + + if (sles_data == 0 ) { + log(" ERROR at JNI initialization"); + if (mMessageHandler != null) { + Message msg = Message.obtain(); + msg.what = NATIVE_AUDIO_THREAD_MESSAGE_REC_ERROR; + mMessageHandler.sendMessage(msg); + } + } else { + + //wait a little bit... + try { + sleep(10); //just to let it start properly? + } catch (InterruptedException e) { + e.printStackTrace(); + } + + + + mSamplesIndex = 0; + int totalSamplesRead = 0; + long offset = 0; + for (int ii = 0; ii < mSecondsToRun; ii++) { + log(String.format("block %d...", ii)); + int samplesRead = slesProcessNext(sles_data, mvSamples,offset); + totalSamplesRead += samplesRead; + + offset += samplesRead; + log(" [" + ii + "] jni samples read:" + samplesRead + " currentOffset:" + offset); + } + + log(String.format(" samplesRead: %d, sampleOffset:%d", totalSamplesRead, offset)); + log(String.format("about to destroy...")); + + runDestroy(sles_data); + + int maxTry = 20; + int tryCount = 0; + //isDestroying = true; + while (isDestroying) { + + try { + sleep(40); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + tryCount++; + + log("destroy try: " + tryCount); + + if (tryCount >= maxTry) { + hasDestroyingErrors = true; + log("WARNING: waited for max time to properly destroy JNI."); + break; + } + } + log(String.format("after destroying. TotalSamplesRead = %d", totalSamplesRead)); + + if (totalSamplesRead==0) + { + hasDestroyingErrors = true; + } + + endTest(); + } + } + + public void setMessageHandler(Handler messageHandler) { + mMessageHandler = messageHandler; + } + + private void runDestroy(final long sles_data ) { + isDestroying = true; + + //start thread + + final long local_sles_data = sles_data; + //// + Thread thread = new Thread(new Runnable() { + public void run() { + isDestroying = true; + log("**Start runnable destroy"); + + int status = slesDestroy(local_sles_data); + log(String.format("**End runnable destroy sles delete status: %d", status)); + isDestroying = false; + } + }); + + thread.start(); + + + + log("end of runDestroy()"); + + + } + + public void togglePlay() { + + } + + public void runTest() { + + + } + + public void endTest() { + log("--Ending capture test--"); + isPlaying = false; + + + if (mMessageHandler != null) { + Message msg = Message.obtain(); + if (hasDestroyingErrors) + msg.what = NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE_ERRORS; + else + msg.what = NATIVE_AUDIO_THREAD_MESSAGE_REC_COMPLETE; + mMessageHandler.sendMessage(msg); + } + + } + + public void finish() { + + if (isRunning) { + isRunning = false; + try { + sleep(20); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + private static void log(String msg) { + Log.v("Loopback", msg); + } + + double [] getWaveData () { + return mvSamples; + } + +} //end thread.
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundGenerator.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundGenerator.java new file mode 100644 index 0000000..0ad9371 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundGenerator.java
@@ -0,0 +1,81 @@ +package com.android.cts.verifier.audio; + +/** + * Sound generator. + */ +public class SoundGenerator { + + private static SoundGenerator instance; + + private final byte[] generatedSound; + private final double[] sample; + + private SoundGenerator() { + // Initialize sample. + int pipNum = Common.PIP_NUM; + int prefixTotalLength = Util.toLength(Common.PREFIX_LENGTH_S, Common.PLAYING_SAMPLE_RATE_HZ) + + Util.toLength(Common.PAUSE_BEFORE_PREFIX_DURATION_S, Common.PLAYING_SAMPLE_RATE_HZ) + + Util.toLength(Common.PAUSE_AFTER_PREFIX_DURATION_S, Common.PLAYING_SAMPLE_RATE_HZ); + int repetitionLength = pipNum * Util.toLength( + Common.PIP_DURATION_S + Common.PAUSE_DURATION_S, Common.PLAYING_SAMPLE_RATE_HZ); + int sampleLength = prefixTotalLength + Common.REPETITIONS * repetitionLength; + sample = new double[sampleLength]; + + // Fill sample with prefix. + System.arraycopy(Common.PREFIX_FOR_PLAYER, 0, sample, + Util.toLength(Common.PAUSE_BEFORE_PREFIX_DURATION_S, Common.PLAYING_SAMPLE_RATE_HZ), + Common.PREFIX_FOR_PLAYER.length); + + // Fill the sample. + for (int i = 0; i < pipNum * Common.REPETITIONS; i++) { + double[] pip = getPip(Common.WINDOW_FOR_PLAYER, Common.FREQUENCIES[i]); + System.arraycopy(pip, 0, sample, + prefixTotalLength + i * Util.toLength( + Common.PIP_DURATION_S + Common.PAUSE_DURATION_S, Common.PLAYING_SAMPLE_RATE_HZ), + pip.length); + } + + // Convert sample to byte. + generatedSound = new byte[2 * sample.length]; + int i = 0; + for (double dVal : sample) { + short val = (short) ((dVal * 32767)); + generatedSound[i++] = (byte) (val & 0x00ff); + generatedSound[i++] = (byte) ((val & 0xff00) >>> 8); + } + } + + public static SoundGenerator getInstance() { + if (instance == null) { + instance = new SoundGenerator(); + } + return instance; + } + + /** + * Gets a pip sample. + */ + private static double[] getPip(double[] window, double frequency) { + int pipArrayLength = window.length; + double[] pipArray = new double[pipArrayLength]; + double radPerSample = 2 * Math.PI / (Common.PLAYING_SAMPLE_RATE_HZ / frequency); + for (int i = 0; i < pipArrayLength; i++) { + pipArray[i] = window[i] * Math.sin(i * radPerSample); + } + return pipArray; + } + + /** + * Get generated sound in byte[]. + */ + public byte[] getByte() { + return generatedSound; + } + + /** + * Get sample in double[]. + */ + public double[] getSample() { + return sample; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundPlayerObject.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundPlayerObject.java new file mode 100644 index 0000000..23b71c0 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/SoundPlayerObject.java
@@ -0,0 +1,215 @@ +/* + * Copyright (C) 2015 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.audio; + +import android.content.Context; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.media.MediaPlayer; +import android.net.Uri; +import android.net.rtp.AudioStream; +import android.util.Log; + +import com.android.cts.verifier.audio.wavelib.PipeShort; + +import java.io.IOException; + +public class SoundPlayerObject extends Thread { + private static final String LOGTAG = "SoundPlayerObject"; + private MediaPlayer mMediaPlayer; + private boolean isInitialized = false; + private boolean isRunning = false; + + public PipeShort mPipe = new PipeShort(65536); + private short[] mAudioShortArray; + + public AudioTrack mAudioTrack; + public int mSamplingRate = 48000; + private int mChannelConfigOut = AudioFormat.CHANNEL_OUT_MONO; + private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT; + int mMinPlayBufferSizeInBytes = 0; + int mMinBufferSizeInSamples = 0; + + private int mStreamType = AudioManager.STREAM_MUSIC; + private int mResId = -1; + private boolean mUseMediaPlayer = true; + private float mBalance = 0.5f; //0 left, 1 right + + public int getCurrentResId() { + return mResId; + } + + public int getStreamType () { + return mStreamType; + } + + public void run() { + setPriority(Thread.MAX_PRIORITY); + isRunning = true; + while (isRunning) { + + if (!mUseMediaPlayer && isInitialized && isPlaying()) { + int valuesAvailable = mPipe.availableToRead(); + if (valuesAvailable > 0) { + + int valuesOfInterest = valuesAvailable; + if (mMinBufferSizeInSamples < valuesOfInterest) { + valuesOfInterest = mMinBufferSizeInSamples; + } + mPipe.read(mAudioShortArray, 0,valuesOfInterest); + //inject into output. + mAudioTrack.write(mAudioShortArray, 0, valuesOfInterest); + } + } else { + try { + sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public void setBalance(float balance) { + mBalance = balance; + if (mUseMediaPlayer) { + if (mMediaPlayer != null) { + float left = Math.min(2.0f * (1.0f - mBalance), 1.0f); + float right = Math.min(2.0f * mBalance, 1.0f); + mMediaPlayer.setVolume(left, right); + log(String.format("Setting balance to %f", mBalance)); + } + } + } + + public void setStreamType(int streamType) { + mStreamType = streamType; + } + + public void rewind() { + if (mUseMediaPlayer) { + if (mMediaPlayer != null) { + mMediaPlayer.seekTo(0); + } + } + } + + public void setSoundWithResId(Context context, int resId) { + boolean playing = isPlaying(); + //release player + releasePlayer(); + mResId = resId; + if (mUseMediaPlayer) { + mMediaPlayer = new MediaPlayer(); + try { + log("opening resource with stream type: " + mStreamType); + mMediaPlayer.setAudioStreamType(mStreamType); + mMediaPlayer.setDataSource(context.getApplicationContext(), + Uri.parse("android.resource://com.android.cts.verifier/" + resId)); + mMediaPlayer.prepare(); + } catch (IOException e) { + e.printStackTrace(); + } + mMediaPlayer.setLooping(true); + setBalance(mBalance); + } else { + mMinPlayBufferSizeInBytes = AudioTrack.getMinBufferSize(mSamplingRate, + mChannelConfigOut, mAudioFormat); + + mMinBufferSizeInSamples = mMinPlayBufferSizeInBytes / 2; + mAudioShortArray = new short[mMinBufferSizeInSamples * 4]; + + mAudioTrack = new AudioTrack(mStreamType, + mSamplingRate, + mChannelConfigOut, + mAudioFormat, + mMinPlayBufferSizeInBytes, + AudioTrack.MODE_STREAM /* FIXME runtime test for API level 9 , + mSessionId */); + mPipe.flush(); + isInitialized = true; + } + + log("done preparing media player"); + if (playing) + play(true); //start playing if it was playing before + } + + public boolean isPlaying() { + boolean result = false; + if (mUseMediaPlayer) { + if (mMediaPlayer != null) { + result = mMediaPlayer.isPlaying(); + } + } else { + if (mAudioTrack != null) { + result = mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING; + } + } + return result; + } + + public void play(boolean play) { + if (mUseMediaPlayer) { + if (mMediaPlayer != null) { + if (play) { + mMediaPlayer.start(); + } else { + mMediaPlayer.pause(); + } + } + } else { + if (mAudioTrack != null && isInitialized) { + if (play) { + mPipe.flush(); + mAudioTrack.flush(); + mAudioTrack.play(); + } else { + mAudioTrack.pause(); + } + } + } + } + + public void finish() { + play(false); + releasePlayer(); + } + + private void releasePlayer() { + if (mMediaPlayer != null) { + mMediaPlayer.stop(); + mMediaPlayer.release(); + mMediaPlayer = null; + } + + if (mAudioTrack != null) { + mAudioTrack.stop(); + mAudioTrack.release(); + mAudioTrack = null; + } + isInitialized = false; + } + + /* + Misc + */ + private static void log(String msg) { + Log.v(LOGTAG, msg); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialPlayer.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialPlayer.java new file mode 100644 index 0000000..af09504 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialPlayer.java
@@ -0,0 +1,111 @@ +/* + * Copyright (C) 2015 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.audio; + +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; + +import java.lang.InterruptedException; +import java.lang.Math; +import java.lang.Runnable; + +public class TrivialPlayer implements Runnable { + AudioTrack mAudioTrack; + int mBufferSize; + + boolean mPlay; + boolean mIsPlaying; + + short[] mAudioData; + + Thread mFillerThread = null; + + public TrivialPlayer() { + mBufferSize = + AudioTrack.getMinBufferSize( + 41000, + AudioFormat.CHANNEL_OUT_STEREO, + AudioFormat.ENCODING_PCM_16BIT); + mAudioTrack = + new AudioTrack( + AudioManager.STREAM_MUSIC, + 41000, + AudioFormat.CHANNEL_OUT_STEREO, + AudioFormat.ENCODING_PCM_16BIT, + mBufferSize, + AudioTrack.MODE_STREAM); + + mPlay = false; + mIsPlaying = false; + + // setup audio data (silence will suffice) + mAudioData = new short[mBufferSize]; + for (int index = 0; index < mBufferSize; index++) { + // mAudioData[index] = 0; + // keep this code since one might want to hear the playnig audio + // for debugging/verification. + mAudioData[index] = + (short)(((Math.random() * 2.0) - 1.0) * (double)Short.MAX_VALUE/2.0); + } + } + + public AudioTrack getAudioTrack() { return mAudioTrack; } + + public boolean isPlaying() { + synchronized (this) { + return mIsPlaying; + } + } + + public void start() { + mPlay = true; + mFillerThread = new Thread(this); + mFillerThread.start(); + } + + public void stop() { + mPlay = false; + mFillerThread = null; + } + + public void shutDown() { + stop(); + while (isPlaying()) { + try { + Thread.sleep(10); + } catch (InterruptedException ex) { + } + } + mAudioTrack.release(); + } + + @Override + public void run() { + mAudioTrack.play(); + synchronized (this) { + mIsPlaying = true; + } + while (mAudioTrack != null && mPlay) { + mAudioTrack.write(mAudioData, 0, mBufferSize); + } + synchronized (this) { + mIsPlaying = false; + } + mAudioTrack.stop(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialRecorder.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialRecorder.java new file mode 100644 index 0000000..f684681 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/TrivialRecorder.java
@@ -0,0 +1,104 @@ +/* + * Copyright (C) 2015 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.audio; + +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioRecord; + +import android.media.MediaRecorder; + +import java.lang.InterruptedException; +import java.lang.Runnable; + +public class TrivialRecorder implements Runnable { + AudioRecord mAudioRecord; + int mBufferSize; + + boolean mRecord; + boolean mIsRecording; + + short[] mAudioData; + + Thread mReaderThread = null; + + public TrivialRecorder() { + mBufferSize = + AudioRecord.getMinBufferSize( + 41000, + AudioFormat.CHANNEL_IN_MONO, + AudioFormat.ENCODING_PCM_16BIT); + mAudioRecord = + new AudioRecord( + MediaRecorder.AudioSource.DEFAULT, + 41000, + AudioFormat.CHANNEL_IN_MONO, + AudioFormat.ENCODING_PCM_16BIT, + mBufferSize); + + mRecord = false; + mIsRecording = false; + + // setup audio data (silence will suffice) + mAudioData = new short[mBufferSize]; + } + + public AudioRecord getAudioRecord() { return mAudioRecord; } + + public boolean mIsRecording() { + synchronized (this) { + return mIsRecording; + } + } + + public void start() { + mRecord = true; + mReaderThread = new Thread(this); + mReaderThread.start(); + } + + public void stop() { + mRecord = false; + mReaderThread = null; + } + + public void shutDown() { + stop(); + while (mIsRecording()) { + try { + Thread.sleep(10); + } catch (InterruptedException ex) { + } + } + mAudioRecord.release(); + } + + @Override + public void run() { + mAudioRecord.startRecording(); + synchronized (this) { + mIsRecording = true; + } + while (mRecord) { + mAudioRecord.read(mAudioData, 0, mBufferSize); + } + mAudioRecord.stop(); + synchronized (this) { + mIsRecording = false; + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/UsbMicrophoneTester.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/UsbMicrophoneTester.java new file mode 100644 index 0000000..c0b6b6a --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/UsbMicrophoneTester.java
@@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 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.audio; + +import android.content.Context; + +import android.hardware.usb.UsbAccessory; +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbInterface; +import android.hardware.usb.UsbManager; + +import java.util.HashMap; +import java.util.Iterator; + +public class UsbMicrophoneTester { + + public static String getUSBDeviceListString(Context context) { + UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); + StringBuilder sb = new StringBuilder(); + HashMap<String, UsbDevice> devicelist = manager.getDeviceList(); + for(UsbDevice usbDevice : devicelist.values()) { + sb.append("Model : " + usbDevice.getDeviceName() + "\n"); + sb.append(" Id : " + usbDevice.getDeviceId() + "\n"); + sb.append(" Class : " + usbDevice.getDeviceClass() + "\n"); + sb.append(" Prod.Id : " + usbDevice.getProductId() + "\n"); + sb.append(" Vendor.Id : " + usbDevice.getVendorId() + "\n"); + int iCount = usbDevice.getInterfaceCount(); + for (int i = 0; i < iCount; i++) { + UsbInterface usbInterface = usbDevice.getInterface(i); + sb.append(" Interface " + i + " :\n"); + sb.append(" Class: " + usbInterface.getInterfaceClass() + "\n"); + } + } + return sb.toString(); + } + + public static boolean getIsMicrophoneConnected(Context context) { + UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); + StringBuilder sb = new StringBuilder(); + HashMap<String, UsbDevice> devicelist = manager.getDeviceList(); + for(UsbDevice usbDevice : devicelist.values()) { + int iCount = usbDevice.getInterfaceCount(); + for (int i = 0; i < iCount; i++) { + UsbInterface usbInterface = usbDevice.getInterface(i); + if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_AUDIO) { + return true; + } + } + } + return false; + } +} \ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/Util.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Util.java new file mode 100644 index 0000000..4ef62d9 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/Util.java
@@ -0,0 +1,152 @@ +package com.android.cts.verifier.audio; + +import org.apache.commons.math.complex.Complex; +import org.apache.commons.math.stat.descriptive.moment.Mean; +import org.apache.commons.math.stat.descriptive.moment.StandardDeviation; +import org.apache.commons.math.stat.descriptive.rank.Median; +import org.apache.commons.math.transform.FastFourierTransformer; + +/** + * This class contains util functions used in the WavAnalyzer. + */ +public class Util { + + /** + * Convert time in second to sample array length. + */ + public static int toLength(double duration, int sampleRate) { + return (int) Math.round(duration * sampleRate); + } + + /** + * Calculate mean of data. + */ + public static double mean(double[] data) { + Mean mean = new Mean(); + return mean.evaluate(data); + } + + /** + * Calculate standard deviation of data. + */ + public static double std(double[] data) { + StandardDeviation std = new StandardDeviation(); + return std.evaluate(data); + } + + /** + * Calculate median of data. + */ + public static double median(double[] data) { + Median median = new Median(); + median.setData(data); + return median.evaluate(); + } + + /** + * Pad zeros at the end, total length of array will be specified as length. If length is smaller + * than the length of the data, it returns the data truncated to the length. + */ + public static Complex[] padZeros(Complex[] data, int length) { + Complex[] result = new Complex[length]; + if (length < data.length) { + System.arraycopy(data, 0, result, 0, length); + } else { + System.arraycopy(data, 0, result, 0, data.length); + for (int i = data.length; i < result.length; i++) { + result[i] = new Complex(0, 0); + } + } + return result; + } + + /** + * Calculate cross correlation using FFT with periodic boundary handling. + */ + public static double[] computeCrossCorrelation(Complex[] data1, Complex[] data2) { + FastFourierTransformer fft = new FastFourierTransformer(); + int n = nextPowerOfTwo(Math.max(data1.length, data2.length)); + Complex[] data1Fft = fft.transform(padZeros(data1, n)); + Complex[] data2Fft = fft.transform(padZeros(data2, n)); + Complex[] dottedData = new Complex[n]; + for (int i = 0; i < n; i++) { + dottedData[i] = data1Fft[i].multiply(data2Fft[i].conjugate()); + } + Complex[] resultComplex = fft.inversetransform(dottedData); + double[] resultDouble = new double[resultComplex.length]; + for (int i = 0; i < resultComplex.length; i++) { + resultDouble[i] = resultComplex[i].abs(); + } + return resultDouble; + } + + /** + * Convert an short array to a double array. + */ + public static double[] toDouble(short[] data) { + double[] result = new double[data.length]; + for (int i = 0; i < data.length; i++) { + result[i] = data[i]; + } + return result; + } + + /** + * Convert a double array to a complex array. + */ + public static Complex[] toComplex(double[] data) { + Complex[] result = new Complex[data.length]; + for (int i = 0; i < data.length; i++) { + result[i] = new Complex(data[i], 0.0); + } + return result; + } + + /** + * Calculates the next power of 2, greater than or equal to the input positive integer. If the + * input is not a positive integer, it returns 1. + */ + public static int nextPowerOfTwo(int n) { + return 1 << (32 - Integer.numberOfLeadingZeros(n - 1)); + } + + /** + * Find the index with the max value in an array. + */ + public static int findMaxIndex(double[] data) { + return findMaxIndex(data, 0, data.length - 1); + } + + /** + * Find the index with the max value in a sub-array. + */ + public static int findMaxIndex(double[] data, int startIndex, int endIndex) { + int maxIndex = startIndex; + for (int i = startIndex + 1; i <= endIndex; i++) { + if (data[i] > data[maxIndex]) { + maxIndex = i; + } + } + return maxIndex; + } + + /** + * Returns the index of an array with the array value closest to the desired value. + */ + public static int findClosest(double[] array, double value) { + double[] diffArray = new double[array.length]; + for (int i = 0; i < array.length; i++) { + diffArray[i] = Math.abs(value - array[i]); + } + int index = 0; + for (int i = 1; i < array.length; i++) { + if (diffArray[i] < diffArray[index]) { + index = i; + if (diffArray[index] == 0) { + break; + } + } + } + return index; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/WavAnalyzer.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/WavAnalyzer.java new file mode 100644 index 0000000..b75c40b --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/WavAnalyzer.java
@@ -0,0 +1,263 @@ +package com.android.cts.verifier.audio; + +import org.apache.commons.math.complex.Complex; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * Class contains the analysis to calculate frequency response. + */ +public class WavAnalyzer { + private final Listener listener; + private final int sampleRate; // Recording sampling rate. + private double[] data; // Whole recording data. + private double[] dB; // Average response + private double[][] power; // power of each trial + private double[] noiseDB; // background noise + private double[][] noisePower; + private double threshold; // threshold of passing, drop off compared to 2000 kHz + private boolean result = false; // result of the test + + /** + * Constructor of WavAnalyzer. + */ + public WavAnalyzer(byte[] byteData, int sampleRate, Listener listener) { + this.listener = listener; + this.sampleRate = sampleRate; + + short[] shortData = new short[byteData.length >> 1]; + ByteBuffer.wrap(byteData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortData); + this.data = Util.toDouble(shortData); + for (int i = 0; i < data.length; i++) { + data[i] = data[i] / Short.MAX_VALUE; + } + } + + /** + * Do the analysis. Returns true if passing, false if failing. + */ + public boolean doWork() { + if (isClipped()) { + return false; + } + // Calculating the pip strength. + listener.sendMessage("Calculating... Please wait...\n"); + try { + dB = measurePipStrength(); + } catch (IndexOutOfBoundsException e) { + listener.sendMessage("WARNING: May have missed the prefix." + + " Turn up the volume of the playback device or move to a quieter location.\n"); + return false; + } + if (!isConsistent()) { + return false; + } + result = responsePassesHifiTest(dB); + return result; + } + + /** + * Check if the recording is clipped. + */ + boolean isClipped() { + for (int i = 1; i < data.length; i++) { + if ((Math.abs(data[i]) >= Short.MAX_VALUE) && (Math.abs(data[i - 1]) >= Short.MAX_VALUE)) { + listener.sendMessage("WARNING: Data is clipped." + + " Turn down the volume of the playback device and redo the procedure.\n"); + return true; + } + } + return false; + } + + /** + * Check if the result is consistant across trials. + */ + boolean isConsistent() { + double[] coeffOfVar = new double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + double[] powerAtFreq = new double[Common.REPETITIONS]; + for (int j = 0; j < Common.REPETITIONS; j++) { + powerAtFreq[j] = power[i][j]; + } + coeffOfVar[i] = Util.std(powerAtFreq) / Util.mean(powerAtFreq); + } + if (Util.mean(coeffOfVar) > 1.0) { + listener.sendMessage("WARNING: Inconsistent result across trials." + + " Turn up the volume of the playback device or move to a quieter location.\n"); + return false; + } + return true; + } + + /** + * Determine test pass/fail using the frequency response. Package visible for unit testing. + */ + boolean responsePassesHifiTest(double[] dB) { + for (int i = 0; i < dB.length; i++) { + // Precautionary; NaN should not happen. + if (Double.isNaN(dB[i])) { + listener.sendMessage( + "WARNING: Unexpected NaN in result. Redo the test.\n"); + return false; + } + } + + if (Util.mean(dB) - Util.mean(noiseDB) < Common.SIGNAL_MIN_STRENGTH_DB_ABOVE_NOISE) { + listener.sendMessage("WARNING: Signal is too weak or background noise is too strong." + + " Turn up the volume of the playback device or move to a quieter location.\n"); + return false; + } + + int indexOf2000Hz = Util.findClosest(Common.FREQUENCIES_ORIGINAL, 2000.0); + threshold = dB[indexOf2000Hz] + Common.PASSING_THRESHOLD_DB; + int indexOf18500Hz = Util.findClosest(Common.FREQUENCIES_ORIGINAL, 18500.0); + int indexOf20000Hz = Util.findClosest(Common.FREQUENCIES_ORIGINAL, 20000.0); + double[] responseInRange = new double[indexOf20000Hz - indexOf18500Hz]; + System.arraycopy(dB, indexOf18500Hz, responseInRange, 0, responseInRange.length); + if (Util.mean(responseInRange) < threshold) { + listener.sendMessage( + "WARNING: Failed. Retry with different orientations or report failed.\n"); + return false; + } + return true; + } + + /** + * Calculate the Fourier Coefficient at the pip frequency to calculate the frequency response. + * Package visible for unit testing. + */ + double[] measurePipStrength() { + listener.sendMessage("Aligning data... Please wait...\n"); + final int dataStartI = alignData(); + final int prefixTotalLength = dataStartI + + Util.toLength(Common.PREFIX_LENGTH_S + Common.PAUSE_AFTER_PREFIX_DURATION_S, sampleRate); + listener.sendMessage("Done.\n"); + listener.sendMessage("Prefix starts at " + (double) dataStartI / sampleRate + " s \n"); + if (dataStartI > Math.round(sampleRate * (Common.PREFIX_LENGTH_S + + Common.PAUSE_BEFORE_PREFIX_DURATION_S + Common.PAUSE_AFTER_PREFIX_DURATION_S))) { + listener.sendMessage("WARNING: Unexpected prefix start time. May have missed the prefix.\n" + + "PLAY button should be pressed on the playback device within one second" + + " after RECORD is pressed on the recording device.\n" + + "If this happens repeatedly," + + " turn up the volume of the playback device or move to a quieter location.\n"); + } + + listener.sendMessage("Analyzing noise strength... Please wait...\n"); + noisePower = new double[Common.PIP_NUM][Common.NOISE_SAMPLES]; + noiseDB = new double[Common.PIP_NUM]; + for (int s = 0; s < Common.NOISE_SAMPLES; s++) { + double[] noisePoints = new double[Common.WINDOW_FOR_RECORDER.length]; + System.arraycopy(data, dataStartI - (s + 1) * noisePoints.length - 1, + noisePoints, 0, noisePoints.length); + for (int j = 0; j < noisePoints.length; j++) { + noisePoints[j] = noisePoints[j] * Common.WINDOW_FOR_RECORDER[j]; + } + for (int i = 0; i < Common.PIP_NUM; i++) { + double freq = Common.FREQUENCIES_ORIGINAL[i]; + Complex fourierCoeff = new Complex(0, 0); + final Complex rotator = new Complex(0, + -2.0 * Math.PI * freq / sampleRate).exp(); + Complex phasor = new Complex(1, 0); + for (int j = 0; j < noisePoints.length; j++) { + fourierCoeff = fourierCoeff.add(phasor.multiply(noisePoints[j])); + phasor = phasor.multiply(rotator); + } + fourierCoeff = fourierCoeff.multiply(1.0 / noisePoints.length); + noisePower[i][s] = fourierCoeff.multiply(fourierCoeff.conjugate()).abs(); + } + } + for (int i = 0; i < Common.PIP_NUM; i++) { + double meanNoisePower = 0; + for (int j = 0; j < Common.NOISE_SAMPLES; j++) { + meanNoisePower += noisePower[i][j]; + } + meanNoisePower /= Common.NOISE_SAMPLES; + noiseDB[i] = 10 * Math.log10(meanNoisePower); + } + + listener.sendMessage("Analyzing pips... Please wait...\n"); + power = new double[Common.PIP_NUM][Common.REPETITIONS]; + for (int i = 0; i < Common.PIP_NUM * Common.REPETITIONS; i++) { + if (i % Common.PIP_NUM == 0) { + listener.sendMessage("#" + (i / Common.PIP_NUM + 1) + "\n"); + } + + int pipExpectedStartI; + pipExpectedStartI = prefixTotalLength + + Util.toLength(i * (Common.PIP_DURATION_S + Common.PAUSE_DURATION_S), sampleRate); + // Cut out the data points for the current pip. + double[] pipPoints = new double[Common.WINDOW_FOR_RECORDER.length]; + System.arraycopy(data, pipExpectedStartI, pipPoints, 0, pipPoints.length); + for (int j = 0; j < Common.WINDOW_FOR_RECORDER.length; j++) { + pipPoints[j] = pipPoints[j] * Common.WINDOW_FOR_RECORDER[j]; + } + Complex fourierCoeff = new Complex(0, 0); + final Complex rotator = new Complex(0, + -2.0 * Math.PI * Common.FREQUENCIES[i] / sampleRate).exp(); + Complex phasor = new Complex(1, 0); + for (int j = 0; j < pipPoints.length; j++) { + fourierCoeff = fourierCoeff.add(phasor.multiply(pipPoints[j])); + phasor = phasor.multiply(rotator); + } + fourierCoeff = fourierCoeff.multiply(1.0 / pipPoints.length); + int j = Common.ORDER[i]; + power[j % Common.PIP_NUM][j / Common.PIP_NUM] = + fourierCoeff.multiply(fourierCoeff.conjugate()).abs(); + } + + // Calculate median of trials. + double[] dB = new double[Common.PIP_NUM]; + for (int i = 0; i < Common.PIP_NUM; i++) { + dB[i] = 10 * Math.log10(Util.median(power[i])); + } + return dB; + } + + /** + * Align data using prefix. Package visible for unit testing. + */ + int alignData() { + // Zeropadding samples to add in the correlation to avoid FFT wraparound. + final int zeroPad = Util.toLength(Common.PREFIX_LENGTH_S, Common.RECORDING_SAMPLE_RATE_HZ) - 1; + int fftSize = Util.nextPowerOfTwo((int) Math.round(sampleRate * (Common.PREFIX_LENGTH_S + + Common.PAUSE_BEFORE_PREFIX_DURATION_S + Common.PAUSE_AFTER_PREFIX_DURATION_S + 0.5)) + + zeroPad); + + double[] dataCut = new double[fftSize - zeroPad]; + System.arraycopy(data, 0, dataCut, 0, fftSize - zeroPad); + double[] xCorrDataPrefix = Util.computeCrossCorrelation( + Util.padZeros(Util.toComplex(dataCut), fftSize), + Util.padZeros(Util.toComplex(Common.PREFIX_FOR_RECORDER), fftSize)); + return Util.findMaxIndex(xCorrDataPrefix); + } + + double[] getDB() { + return dB; + } + + double[][] getPower() { + return power; + } + + double[] getNoiseDB() { + return noiseDB; + } + + double getThreshold() { + return threshold; + } + + boolean getResult() { + return result; + } + + /** + * An interface for listening a message publishing the progress of the analyzer. + */ + public interface Listener { + + void sendMessage(String message); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferBase.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferBase.java new file mode 100644 index 0000000..0a8bdde --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferBase.java
@@ -0,0 +1,46 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +public abstract class DspBufferBase { + private int mSize; + + public DspBufferBase() { + setSize(0); + } + + public DspBufferBase(int size) { + setSize(size); + } + + public int getSize() { + return mSize; + } + + public void setSize(int size) { + mSize = size; + } + + public abstract void setValue(int index, double value); + + public abstract void setValues(int index, double... values); + + @Override + public String toString() { + return String.format("Size: %d", mSize); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferComplex.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferComplex.java new file mode 100644 index 0000000..2b71343 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferComplex.java
@@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +public class DspBufferComplex extends DspBufferBase { + public double[] mReal; + public double[] mImag; + + public DspBufferComplex(int size) { + super(size); + } + + @Override + public void setSize(int size) { + if (size == getSize()) { + return; + } + mReal = new double[size]; + mImag = new double[size]; + super.setSize(size); + } + + // Warning, these methods don't check for bounds! + @Override + public void setValues(int index, double... values) { + mReal[index] = values[0]; + mImag[index] = values[1]; + } + + @Override + public void setValue(int index, double value) { + mReal[index] = value; + mImag[index] = 0; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + int size = getSize(); + sb.append(String.format("Size: %d { ", size)); + for (int i = 0; i < size; i++) { + sb.append(String.format("(%.3f, %3f) ", mReal[i], mImag[i])); + } + sb.append("}"); + return sb.toString(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferDouble.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferDouble.java new file mode 100644 index 0000000..1b75da6 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferDouble.java
@@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +public class DspBufferDouble extends DspBufferBase { + public double[] mData; + + public DspBufferDouble(int size) { + super(size); + } + + @Override + public void setSize(int size) { + if (size == getSize()) { + return; + } + mData = new double[size]; + super.setSize(size); + } + + // Warning, these methods don't check for bounds! + @Override + public void setValues(int index, double... values) { + mData[index] = values[0]; + } + + @Override + public void setValue(int index, double value) { + mData[index] = value; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + int size = getSize(); + sb.append(String.format("Size: %d { ", size)); + int i = 0; + for (; i < size - 1; i++) { + sb.append(String.format("%.3f, ", mData[i])); + } + for(; i < size; i++) { + sb.append(String.format("%.3f", mData[i])); + } + sb.append(" }"); + return sb.toString(); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferMath.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferMath.java new file mode 100644 index 0000000..a9cbbd0 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspBufferMath.java
@@ -0,0 +1,329 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +import android.util.Log; + +public class DspBufferMath { + private static final String TAG = "DspBufferMath"; + public static final int OPERANDS_TYPE_UNKNOWN = -1; + public static final int OPERANDS_TYPE_REAL = 0; + public static final int OPERANDS_TYPE_COMPLEX = 1; + public static final int OPERANDS_TYPE_MIXED = 2; + + public static final int MATH_RESULT_UNDEFINED = -1; + public static final int MATH_RESULT_SUCCESS = 0; + public static final int MATH_RESULT_ERROR = 1; + + static private<T extends DspBufferBase> int estimateOperandsType(T a, T b) { + if (a instanceof DspBufferComplex) { + if (b instanceof DspBufferComplex) { + return OPERANDS_TYPE_COMPLEX; + } else if (b instanceof DspBufferDouble) { + return OPERANDS_TYPE_MIXED; + } + } else if (a instanceof DspBufferDouble) { + if (b instanceof DspBufferComplex) { + return OPERANDS_TYPE_MIXED; + } else if (b instanceof DspBufferDouble) { + return OPERANDS_TYPE_REAL; + } + } + return OPERANDS_TYPE_UNKNOWN; + } + + /** + * adds r = a + b; element by element + * + * If the result is double vector, the imaginary part of complex operations is ignored. + */ + static public <T extends DspBufferBase> int add(T r, T a, T b) { + int size = Math.min(a.getSize(), b.getSize()); + r.setSize(size); + + T x = a; + T y = b; + int opType = estimateOperandsType(a, b); + + if (opType == OPERANDS_TYPE_MIXED) { + if (a instanceof DspBufferDouble) { + x = b; //Complex first + y = a; + } + } + + if (opType == OPERANDS_TYPE_UNKNOWN) { + return MATH_RESULT_UNDEFINED; + } + + if (r instanceof DspBufferComplex) { + switch (opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = + ((DspBufferDouble) x).mData[i] + ((DspBufferDouble) y).mData[i]; + ((DspBufferComplex) r).mImag[i] = 0; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = + ((DspBufferComplex) x).mReal[i] + ((DspBufferComplex) y).mReal[i]; + ((DspBufferComplex) r).mImag[i] = + ((DspBufferComplex) x).mImag[i] + ((DspBufferComplex) y).mImag[i]; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = + ((DspBufferComplex) x).mReal[i] + ((DspBufferDouble) y).mData[i]; + ((DspBufferComplex) r).mImag[i] = ((DspBufferComplex) x).mImag[i]; + } + return MATH_RESULT_SUCCESS; + } + } else if (r instanceof DspBufferDouble) { + switch (opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = + ((DspBufferDouble) x).mData[i] + ((DspBufferDouble) y).mData[i]; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = + ((DspBufferComplex) x).mReal[i] + ((DspBufferComplex) y).mReal[i]; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = + ((DspBufferComplex) x).mReal[i] + ((DspBufferDouble) y).mData[i]; + } + return MATH_RESULT_SUCCESS; + } + } + return MATH_RESULT_ERROR; + } + + /** + * mult r = a * b; element by element + */ + static public <T extends DspBufferBase> int mult(T r, T a, T b) { + int size = Math.min(a.getSize(), b.getSize()); + r.setSize(size); + + T x = a; + T y = b; + int opType = estimateOperandsType(a, b); + + if (opType == OPERANDS_TYPE_MIXED) { + if (a instanceof DspBufferDouble) { + x = b; //Complex first + y = a; + } + } + + if (opType == OPERANDS_TYPE_UNKNOWN) { + return MATH_RESULT_UNDEFINED; + } + + if (r instanceof DspBufferComplex) { + switch (opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = + ((DspBufferDouble) x).mData[i] * ((DspBufferDouble) y).mData[i]; + ((DspBufferComplex) r).mImag[i] = 0; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + double A = ((DspBufferComplex) x).mReal[i]; + double B = ((DspBufferComplex) x).mImag[i]; + double C = ((DspBufferComplex) y).mReal[i]; + double D = ((DspBufferComplex) y).mImag[i]; + ((DspBufferComplex) r).mReal[i] = (C * A) - (B * D); + ((DspBufferComplex) r).mImag[i] = (C * B) + (A * D); + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + double A = ((DspBufferComplex) x).mReal[i]; + double B = ((DspBufferComplex) x).mImag[i]; + double C = ((DspBufferDouble) y).mData[i]; + //double D = 0; + ((DspBufferComplex) r).mReal[i] = C * A; + ((DspBufferComplex) r).mImag[i] = C * B; + } + return MATH_RESULT_SUCCESS; + } + } else if (r instanceof DspBufferDouble) { + switch (opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = + ((DspBufferDouble) x).mData[i] * ((DspBufferDouble) y).mData[i]; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + double A = ((DspBufferComplex) x).mReal[i]; + double B = ((DspBufferComplex) x).mImag[i]; + double C = ((DspBufferComplex) y).mReal[i]; + double D = ((DspBufferComplex) y).mImag[i]; + ((DspBufferDouble) r).mData[i] = (C * A) - (B * D); + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + double A = ((DspBufferComplex) x).mReal[i]; + double B = ((DspBufferComplex) x).mImag[i]; + double C = ((DspBufferDouble) y).mData[i]; + //double D = 0; + ((DspBufferDouble) r).mData[i] = C * A; + } + return MATH_RESULT_SUCCESS; + } + } + return MATH_RESULT_ERROR; + } + + /** + * mult r = a * v; element by element + */ + static public <T extends DspBufferBase> int mult(T r, T a, double v) { + int size = a.getSize(); + r.setSize(size); + + T x = a; + int opType = estimateOperandsType(r, a); + + if (opType == OPERANDS_TYPE_UNKNOWN) { + return MATH_RESULT_UNDEFINED; + } + + if (r instanceof DspBufferComplex) { + switch (opType) { + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = ((DspBufferDouble) x).mData[i] * v; + ((DspBufferComplex) r).mImag[i] = 0; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = ((DspBufferComplex) x).mReal[i] * v; + ((DspBufferComplex) r).mImag[i] = ((DspBufferComplex) x).mImag[i] * v; + } + return MATH_RESULT_SUCCESS; + } + } else if (r instanceof DspBufferDouble) { + switch (opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = ((DspBufferDouble) x).mData[i] * v; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = ((DspBufferComplex) x).mReal[i] * v; + } + return MATH_RESULT_SUCCESS; + } + } + return MATH_RESULT_ERROR; + } + + /** + * set r = a ; element by element + */ + static public <T extends DspBufferBase> int set(T r, T a) { + int size = a.getSize(); + r.setSize(size); + + T x = a; + int opType = estimateOperandsType(r, a); + + if (opType == OPERANDS_TYPE_UNKNOWN) { + return MATH_RESULT_UNDEFINED; + } + + if (r instanceof DspBufferComplex) { + switch (opType) { + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = ((DspBufferDouble) x).mData[i]; + ((DspBufferComplex) r).mImag[i] = 0; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_COMPLEX: + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = ((DspBufferComplex) x).mReal[i]; + ((DspBufferComplex) r).mImag[i] = ((DspBufferComplex) x).mImag[i]; + } + return MATH_RESULT_SUCCESS; + } + } else if (r instanceof DspBufferDouble) { + switch(opType) { + case OPERANDS_TYPE_REAL: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = ((DspBufferDouble) x).mData[i]; + } + return MATH_RESULT_SUCCESS; + case OPERANDS_TYPE_MIXED: + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = ((DspBufferComplex) x).mReal[i]; + } + return MATH_RESULT_SUCCESS; + } + } + return MATH_RESULT_ERROR; + } + + + /** + * set r = v ; all elements the same + * It keeps the size of the return vector + */ + static public <T extends DspBufferBase> int set(T r, double ...values) { + int size = r.getSize(); + + double a = 0; + double b = 0; + if (values.length > 0) { + a = values[0]; + } + if (values.length > 1) { + b = values[1]; + } + + if (r instanceof DspBufferComplex) { + for (int i = 0; i < size; i++) { + ((DspBufferComplex) r).mReal[i] = a; + ((DspBufferComplex) r).mImag[i] = b; + } + return MATH_RESULT_SUCCESS; + } else if (r instanceof DspBufferDouble) { + for (int i = 0; i < size; i++) { + ((DspBufferDouble) r).mData[i] = a; + } + return MATH_RESULT_SUCCESS; + } + return MATH_RESULT_ERROR; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspFftServer.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspFftServer.java new file mode 100644 index 0000000..09337f1 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspFftServer.java
@@ -0,0 +1,100 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +public class DspFftServer { + private int mN = 0; + private int mOrder = 0; + + DspBufferDouble mCos; + DspBufferDouble mSin; + public boolean isInitialized = false; + + public DspFftServer(int size) { + init(size); + } + + public boolean init(int size) { + boolean status = false; + mN=size; + + mOrder = (int) (Math.log(mN) / Math.log(2)); + if (mN == (1 << mOrder)) { + mCos = new DspBufferDouble(mN / 2); + mSin = new DspBufferDouble(mN / 2); + for (int i = 0; i < mN / 2; i++) { + mCos.mData[i] = Math.cos(-2 * Math.PI * i / mN); + mSin.mData[i] = Math.sin(-2 * Math.PI * i / mN); + } + status = true; + } else { + mN = 0; + throw new RuntimeException("FFT must be power of 2"); + } + isInitialized = status; + return status; + } + + public void fft(DspBufferComplex r, int sign) { + int ii, jj, kk, n1, n2, aa; + double cc, ss, t1, t2; + + // Bit-reverse + jj = 0; + n2 = mN / 2; + for (ii = 1; ii < mN - 1; ii++) { + n1 = n2; + while (jj >= n1) { + jj = jj - n1; + n1 = n1 / 2; + } + jj = jj + n1; + + if (ii < jj) { + t1 = r.mReal[ii]; + r.mReal[ii] = r.mReal[jj]; + r.mReal[jj] = t1; + t1 = r.mImag[ii]; + r.mImag[ii] = r.mImag[jj]; + r.mImag[jj] = t1; + } + } + + // FFT + n1 = 0; + n2 = 1; + for (ii = 0; ii < mOrder; ii++) { + n1 = n2; + n2 = n2 + n2; + aa = 0; + + for (jj = 0; jj < n1; jj++) { + cc = mCos.mData[aa]; + ss = sign * mSin.mData[aa]; + aa += 1 << (mOrder - ii - 1); + for (kk = jj; kk < mN; kk = kk + n2) { + t1 = cc * r.mReal[kk + n1] - ss * r.mImag[kk + n1]; + t2 = ss * r.mReal[kk + n1] + cc * r.mImag[kk + n1]; + r.mReal[kk + n1] = r.mReal[kk] - t1; + r.mImag[kk + n1] = r.mImag[kk] - t2; + r.mReal[kk] = r.mReal[kk] + t1; + r.mImag[kk] = r.mImag[kk] + t2; + } + } + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspWindow.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspWindow.java new file mode 100644 index 0000000..3ccca43 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/DspWindow.java
@@ -0,0 +1,201 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +public class DspWindow { + public DspBufferDouble mBuffer; + private int mWindowType = WINDOW_RECTANGULAR; + private int mSize; + private int mOverlap; + + private static final double TWOPI = Math.PI * 2; + + public static final int WINDOW_RECTANGULAR = 0; + public static final int WINDOW_TRIANGULAR = 1; + public static final int WINDOW_TRIANGULAR_FLAT_TOP = 2; + public static final int WINDOW_HAMMING = 3; + public static final int WINDOW_HAMMING_FLAT_TOP = 4; + public static final int WINDOW_HANNING = 5; + public static final int WINDOW_HANNING_FLAT_TOP = 6; + + public DspWindow(int windowType, int size, int overlap) { + init(windowType, size, overlap); + } + + public DspWindow(int windowType, int size) { + init(windowType, size, size / 2); + } + + public void init(int windowType, int size, int overlap) { + if (size > 0 && overlap > 0) { + mSize = size; + mOverlap = overlap; + if (mOverlap > mSize / 2) { + mOverlap = mSize / 2; + } + + mBuffer = new DspBufferDouble(mSize); + if (fillWindow(mBuffer, windowType, mOverlap)) { + mWindowType = windowType; + } + } + } + + public void scale(double scale) { + DspBufferMath.mult(mBuffer, mBuffer, scale); + } + + public static boolean fillWindow(DspBufferDouble r, int type, int overlap) { + boolean status = false; + int size = r.getSize(); + if (overlap > size / 2) { + overlap = size / 2; + } + + switch(type) { + case WINDOW_RECTANGULAR: + status = fillRectangular(r); + break; + case WINDOW_TRIANGULAR: + status = fillTriangular(r, size / 2); + break; + case WINDOW_TRIANGULAR_FLAT_TOP: + status = fillTriangular(r, overlap); + break; + case WINDOW_HAMMING: + status = fillHamming(r, size / 2); + break; + case WINDOW_HAMMING_FLAT_TOP: + status = fillHamming(r, overlap); + break; + case WINDOW_HANNING: + status = fillHanning(r, size / 2); + break; + case WINDOW_HANNING_FLAT_TOP: + status = fillHanning(r, overlap); + break; + } + return status; + } + + private static boolean fillRectangular(DspBufferDouble r) { + if (DspBufferMath.set(r, 1.0) == DspBufferMath.MATH_RESULT_SUCCESS) { + return true; + } + return false; + } + + private static boolean fillTriangular(DspBufferDouble b, int overlap) { + int size = b.getSize(); + if (overlap > size / 2) { + overlap = size / 2; + } + + double value; + //ramp up + int i = 0; + if (overlap > 0) { + for (i = 0; i < overlap; i++) { + value = (2.0 * i + 1) / (2 * overlap); + b.mData[i] = value; + } + } + + //flat top + for (; i < size - overlap; i++) { + b.mData[i] = 1.0; + } + + //ramp down + if (overlap > 0) { + for (; i < size; i++) { + value = (2.0 * (size - i) - 1) / (2 * overlap); + b.mData[i] = value; + } + } + return true; + } + + private static boolean fillHamming(DspBufferDouble b, int overlap) { + int size = b.getSize(); + if (overlap > size / 2) + overlap = size / 2; + + //create window, then copy + double value; + + int twoOverlap = 2 * overlap; + //ramp up + int i = 0; + if (overlap > 0) { + for (i = 0; i < overlap; i++) { + value = 0.54 - 0.46 * Math.cos(TWOPI * i / (twoOverlap - 1)); + b.mData[i] = value; + } + } + + //flat top + for (; i < size - overlap; i++) { + b.mData[i] = 1.0; + } + + //ramp down + int k; + if (overlap > 0) { + for (; i < size; i++) { + k = i - (size - 2 * overlap); + value = 0.54 - 0.46 * Math.cos(TWOPI * k / (twoOverlap - 1)); + b.mData[i] = value; + } + } + return true; + } + + private static boolean fillHanning(DspBufferDouble b, int overlap) { + int size = b.getSize(); + if (overlap > size / 2) + overlap = size / 2; + + //create window, then copy + double value; + + int twoOverlap = 2*overlap; + //ramp up + int i = 0; + if (overlap > 0) { + for (i = 0; i < overlap; i++) { + value = 0.5 * (1.0 - Math.cos(TWOPI * i / (twoOverlap - 1))); + b.mData[i] = value; + } + } + + //flat top + for (; i < size - overlap; i++) { + b.mData[i] = 1.0; + } + + //ramp down + if (overlap > 0) { + for (; i < size; i++) { + int k = i - (size - 2 * overlap); + value = 0.5 * (1.0 - Math.cos(TWOPI * k / (twoOverlap - 1))); + b.mData[i] = value; + } + } + return true; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/PipeShort.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/PipeShort.java new file mode 100644 index 0000000..83b171f --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/PipeShort.java
@@ -0,0 +1,140 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +// Non-blocking pipe supports a single writer and single reader. +// The write side of a pipe permits overruns; flow control is the caller's responsibility. + +public class PipeShort { + private int mFront; + private int mRear; + private short mBuffer[]; + private volatile int mVolatileRear; // written by write(), read by read() + private int mMaxValues; + private int mBytesOverrun; + private int mOverruns; + public static final int OVERRUN = -2; + + // maxBytes will be rounded up to a power of 2, and all slots are available. Must be >= 2. + public PipeShort(int maxValues) + { + mMaxValues = roundup(maxValues); + mBuffer = new short[mMaxValues]; + } + + // buffer must != null. + // offset must be >= 0. + // count is maximum number of bytes to copy, and must be >= 0. + // offset + count must be <= buffer.length. + // Returns actual number of bytes copied >= 0. + public int write(short[] buffer, int offset, int count) + { + int rear = mRear & (mMaxValues - 1); + int written = mMaxValues - rear; + if (written > count) { + written = count; + } + System.arraycopy(buffer, offset, mBuffer, rear, written); + if (rear + written == mMaxValues) { + if ((count -= written) > rear) { + count = rear; + } + if (count > 0) { + System.arraycopy(buffer, offset + written, mBuffer, 0, count); + written += count; + } + } + mRear += written; + mVolatileRear = mRear; + return written; + } + + public int availableToRead() + { + int rear = mVolatileRear; + int avail = rear - mFront; + if (avail > mMaxValues) { + // Discard 1/16 of the most recent data in pipe to avoid another overrun immediately + int oldFront = mFront; + mFront = rear - mMaxValues + (mMaxValues >> 4); + mBytesOverrun += mFront - oldFront; + ++mOverruns; + return OVERRUN; + } + return avail; + } + + // buffer must != null. + // offset must be >= 0. + // count is maximum number of bytes to copy, and must be >= 0. + // offset + count must be <= buffer.length. + // Returns actual number of bytes copied >= 0. + public int read(short[] buffer, int offset, int count) + { + int avail = availableToRead(); + if (avail <= 0) { + return avail; + } + // An overrun can occur from here on and be silently ignored, + // but it will be caught at next read() + if (count > avail) { + count = avail; + } + int front = mFront & (mMaxValues - 1); + int red = mMaxValues - front; + if (red > count) { + red = count; + } + // In particular, an overrun during the System.arraycopy will result in reading corrupt data + System.arraycopy(mBuffer, front, buffer, offset, red); + // We could re-read the rear pointer here to detect the corruption, but why bother? + if (front + red == mMaxValues) { + if ((count -= red) > front) { + count = front; + } + if (count > 0) { + System.arraycopy(mBuffer, 0, buffer, offset + red, count); + red += count; + } + } + mFront += red; + return red; + } + + public void flush() + { + mRear = mFront; + mVolatileRear = mFront; + } + + // Round up to the next highest power of 2 + private static int roundup(int v) + { + // Integer.numberOfLeadingZeros() returns 32 for zero input + if (v == 0) { + v = 1; + } + int lz = Integer.numberOfLeadingZeros(v); + int rounded = 0x80000000 >>> lz; + // 0x800000001 and higher are actually rounded _down_ to prevent overflow + if (v > rounded && lz > 0) { + rounded <<= 1; + } + return rounded; + } + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/VectorAverage.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/VectorAverage.java new file mode 100644 index 0000000..41f0411 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/wavelib/VectorAverage.java
@@ -0,0 +1,158 @@ +/* + * Copyright (C) 2015 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.audio.wavelib; + +import android.util.Log; + +public class VectorAverage { + private static final String LOGTAG = "VectorAverage"; + private static final int mVersion = 0; + private double[] mData; + private int mValueCount = 0; + + public void setData(double[] data, boolean replace) { + int size = data.length; + if (mData == null || mData.length != size) { + mData = new double[size]; + mValueCount = 0; + } + if (replace || mValueCount == 0) { + System.arraycopy(data, 0, mData, 0, size); + mValueCount = 1; + } else { + for (int i = 0; i < size; i++) { + mData[i] += data[i]; + } + mValueCount++; + } + } + + public int getData(double[] data, boolean raw) { + int nCount = 0; + if (mData != null && mData.length <= data.length) { + nCount = mData.length; + if (mValueCount == 0) { + for (int i = 0; i < nCount; i++) { + data[i] = 0; + } + } else if (!raw && mValueCount > 1) { + for (int i = 0; i < nCount; i++) { + data[i] = mData[i] / mValueCount; + } + } else { + for (int i = 0; i < nCount; i++) { + data[i] = mData[i]; + } + } + } + return nCount; + } + + public int getCount() { + return mValueCount; + } + + public int getSize() { + if (mData != null) { + return mData.length; + } + return 0; + } + + public void reset() { + mValueCount = 0; + } + + private final String SERIALIZED_VERSION = "VECTOR_AVERAGE_VERSION"; + private final String SERIALIZED_COUNT = "COUNT"; + + public String toString() { + StringBuffer sb = new StringBuffer(); + + //version + sb.append(SERIALIZED_VERSION +"="+ mVersion +"\n"); + + double[] data = new double[getSize()]; + getData(data,false); + + //element count + int nCount = data.length; + sb.append(SERIALIZED_COUNT + "=" + nCount +"\n"); + + for (int i = 0; i < nCount; i++) { + sb.append(String.format("%f\n",data[i])); + } + + return sb.toString(); + } + + public boolean initFromString(String string) { + boolean success = false; + + String[] lines = string.split(System.getProperty("line.separator")); + + int lineCount = lines.length; + if (lineCount > 3) { + int nVersion = -1; + int nCount = -1; + int nIndex = 0; + + //search for version: + while (nIndex < lineCount) { + String[] separated = lines[nIndex].split("="); + nIndex++; + if (separated.length > 1 && separated[0].equalsIgnoreCase(SERIALIZED_VERSION)) { + nVersion = Integer.parseInt(separated[1]); + break; + } + } + + if (nVersion >= 0) { + //get count + + while (nIndex < lineCount) { + String[] separated = lines[nIndex].split("="); + nIndex++; + if (separated.length > 1 && separated[0].equalsIgnoreCase(SERIALIZED_COUNT)) { + nCount = Integer.parseInt(separated[1]); + break; + } + } + + if (nCount > 0 && nCount <= lineCount-2 && nCount < 20000) { //foolproof + //now add nCount to the vector. + double[] data = new double[nCount]; + int dataIndex=0; + + while (nIndex < lineCount) { + double value = Double.parseDouble(lines[nIndex]); + data[dataIndex++] = value; + nIndex++; + } + setData(data, true); + success = true; + } + } + } + + return success; + } + + private static void log(String msg) { + Log.v(LOGTAG, msg); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleAdvertiserService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleAdvertiserService.java index b4a6416..5a60ad0 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleAdvertiserService.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleAdvertiserService.java
@@ -42,7 +42,7 @@ public class BleAdvertiserService extends Service { public static final boolean DEBUG = true; - public static final String TAG = "BleAdvertiseService"; + public static final String TAG = "BleAdvertiserService"; public static final int COMMAND_START_ADVERTISE = 0; public static final int COMMAND_STOP_ADVERTISE = 1;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/AutoLockTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/AutoLockTest.java deleted file mode 100644 index 9181b29..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/AutoLockTest.java +++ /dev/null
@@ -1,1078 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.ImageFormat; -import android.hardware.Camera; -import android.hardware.usb.UsbAccessory; -import android.hardware.usb.UsbManager; -import android.os.ParcelFileDescriptor; -import android.util.Log; -import android.view.SurfaceView; -import android.widget.ImageView; -import android.widget.Toast; - -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Implements a test to verify whether the Auto Exposure Lock functions as - * described in the API. - * - * The test consists three sub-categories. The first set of tests focus on - * testing whether the auto exposure lock works in various situations. - * For all tests in this set, the lock is set during the period when the camera - * preview is open. In this way the lock locks exposure according to the - * lighting at the moment of setting the lock. The second set of tests focus on - * testing whether the auto exposure lock works as expected after turning the - * preview off and on. The lock is set during the period when the camera - * preview is turned off. The lock is expected to lock an exposure level - * identical to the one before the preview is turned off. One special case in - * this category is to set lock before the preview is turned on for the first - * time. - */ -public class AutoLockTest extends CameraTests { - - private static final String TAG = "AutoLockTest"; - /** USB permission to connect to ADK. */ - private static final String ACTION_USB_PERMISSION = "com.android.cts.verifier.USB_PERMISSION"; - /** Defines a long sleep period.*/ - private static final int SHORT_SLEEP = 2000; - /** Defines a short sleep period. */ - private static final int LONG_SLEEP = 4000; - - /** Test results in text format. */ - private String mDebugText = new String(); - /** Detailed report. */ - private String mResultText = new String(); - /** Thread lock of the camera callbacks. */ - private final Object mProcessingImage = new Object(); - /** Memory address of the native test handler. */ - private long mTestHandler; - /** Array storing the reference test results. */ - private ArrayList<Boolean> mReferenceCompareResults; - /** Array storing the reference test scenario logs. */ - private ArrayList<String> mReferenceLogs; - /** Number of tests so far. */ - private int mTestCount; - - /** Usb Manager of the USB connections. */ - private UsbManager mUsbManager; - /** Intent for getting the permission to access the ADK. */ - private PendingIntent mPermissionIntent; - /** Boolean to represent whether a permission is gained. */ - private boolean mPermissionRequestPending; - /** USB accessory pointing to the ADK. */ - private UsbAccessory mAccessory; - /** File descriptor of the USB communication port. */ - private ParcelFileDescriptor mFileDescriptor; - /** Output stream to write commands for ADK to. */ - private FileOutputStream mOutputStream; - - /** Pointer to the CameraAnalyzerActivity activity. */ - private CameraAnalyzerActivity mActivity; - /** Boolean to tell whether the accessory is opened. */ - private boolean mSetupReady; - /** Thread lock for setting up the usb. */ - private final Object mUsbSetup = new Object(); - /** Boolean to indicate whether there is an ADK attached. */ - private boolean mUsingUsb = false; - /** Test results.*/ - private int[] mTestResults; - /** Number of tests. */ - private int mNumTests; - /** Singleton test instance.*/ - private static AutoLockTest singletonTest = null; - - /** - * Receives the notice of whether the connection to ADK is granted or - * denied. - */ - private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - Log.v(TAG, String.format("Received USB broadcast with action %s ", action)); - - if (ACTION_USB_PERMISSION.equals(action)) { - synchronized (this) { - UsbAccessory accessory = - (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); - - if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { - // Grants the permission to connect to the ADK. - Log.v(TAG, "Open accessory 3"); - openAccessory(accessory); - // Overwrites the old camera instsance with the one currently opened - // by the CameraAnalyzerActivity instance, since the permission - // dialogue pauses the CameraAnalyzerActivity and forces the camera to - // be released and reopened when the dialogue disappears. - mTestCamera = mActivity.getCameraInstance(); - } else { - // Denies the permission to connect to the ADK. - Log.d(TAG, "permission denied for accessory " + accessory); - } - // Marks that the permission request has been processed. - mPermissionRequestPending = false; - } - } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) { - // Invokes when the USB is detached. - // Closes the accessory if it has not been closed. - Log.v(TAG, "Usb device detached"); - mUsingUsb = false; - UsbAccessory accessory = - (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); - if (accessory != null && accessory.equals(mAccessory)) { - closeAccessory(); - } - } - } - }; - - /** - * Opens the ADK from USB and attaches the output stream with it. - * - * Notifies the tread lock that the USB setup is ready. - */ - private void openAccessory(UsbAccessory accessory) { - Log.d(TAG, "openAccessory: " + accessory); - mFileDescriptor = mUsbManager.openAccessory(accessory); - - if (mFileDescriptor != null) { - mAccessory = accessory; - FileDescriptor fd = mFileDescriptor.getFileDescriptor(); - mOutputStream = new FileOutputStream(fd); - Log.d(TAG, "accessory opened"); - } else { - Log.d(TAG, "accessory open fail"); - } - - // Unlocks the thread lock of waiting for the USB to be ready. - synchronized (mUsbSetup) { - mSetupReady = true; - Log.v(TAG, "Setup ready"); - mUsbSetup.notifyAll(); - } - } - - /** - * Closes the ADK and detaches the output stream from it. - */ - private void closeAccessory() { - try { - if (mFileDescriptor != null) { - mFileDescriptor.close(); - } - } catch (IOException e) { - } finally { - mFileDescriptor = null; - mAccessory = null; - } - } - - /** - * Constructs the AutoLockTest class, which can execute a series of tests - * to verify whether the device's Auto Exposure Lock is working properly. - * - * The test uses the LED lights on an ADK device as light source to change - * the lighting condition of the environment. The usb connection to the - * ADK board is established in the constructor. - * - * @param hostActivity pointer to the <code>CameraAnalyzerActivity</code> - * that instructs the Auto Lock Test - * @param mCamera pointer to the current camera instance - */ - private AutoLockTest(){ - super(); - } - - public static synchronized AutoLockTest getSingletonTest() { - if (singletonTest == null) { - Log.v(TAG, "Creating a new AutoLockTest instance"); - singletonTest = new AutoLockTest(); - singletonTest.initializeTest(); - } - return singletonTest; - } - - private void initializeTest() { - // Creates a native test handler with a 120x160 pixel debug output - mTestHandler = createAutoLockTest(); - mReferenceCompareResults = new ArrayList<Boolean>(); - mReferenceLogs = new ArrayList<String>(); - mNumTests = 4; - mTestResults = new int[mNumTests]; - for (int i = 0; i < mNumTests; ++i) { - mTestResults[i] = CameraTests.CAMERA_TEST_NOT_RUN; - } - } - - public void updateCamera() {} - - public void setActivity(CameraAnalyzerActivity hostActivity){ - if (mUsingUsb) { - closeConnection(); - } - - mActivity = hostActivity; - - mSetupReady = false; - - Log.v(TAG, "Start to test ADK connection"); - // Starts to establish the connection to the ADK board. - mUsbManager = (UsbManager) mActivity.getSystemService(Context.USB_SERVICE); - mPermissionIntent = PendingIntent.getBroadcast(mActivity, 0, - new Intent(ACTION_USB_PERMISSION), 0); - IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); - filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); - filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED); - mActivity.registerReceiver(mUsbReceiver, filter); - - if (mActivity.getLastNonConfigurationInstance() != null) { - mAccessory = (UsbAccessory) mActivity.getLastNonConfigurationInstance(); - Log.v(TAG, "Open acceossory 1"); - openAccessory(mAccessory); - } - - // Skips the permission listener if the user already grants the ADK - // permission previously in the app. - UsbAccessory[] accessories = mUsbManager.getAccessoryList(); - UsbAccessory accessory = (accessories == null ? null : accessories[0]); - if (accessory != null) { - if (mUsbManager.hasPermission(accessory)) { - Log.v(TAG, "Open accessory 2"); - openAccessory(accessory); - } else { - synchronized (mUsbReceiver) { - if (!mPermissionRequestPending) { - mUsbManager.requestPermission(accessory, mPermissionIntent); - mPermissionRequestPending = true; - } - } - } - mUsingUsb = true; - } else { - Log.d(TAG, "accessory is null"); - mUsingUsb = false; - } - - } - - /** - * Closes the accessories and unregister the USB listener at the end of - * tests. - */ - public void closeConnection() { - closeAccessory(); - mActivity.unregisterReceiver(mUsbReceiver); - } - - protected void finalize () { - if (mUsingUsb) { - closeConnection(); - } - } - - /** - * Runs the Auto Lock tests. A total of 19 tests have been coded and - * included. Developers can freely comment out tests not interested. In - * the release version, all tests will be executed. - */ - @Override - public synchronized void run(int index){ - if (index == 0) { - for (int i = 1; i < mNumTests; ++i) { - run(i); - } - return; - } - - Log.v(TAG, "AutoLockTest thread started!"); - - if (mUsingUsb && (!mSetupReady)) { - // USB connection is not set up. Locks thread and wait. - Log.v(TAG, "Setup not ready, waiting"); - synchronized (mUsbSetup) { - try{ - Log.v(TAG, "Start waiting for Image"); - mUsbSetup.wait(); - } catch (InterruptedException e) { - Log.v(TAG, "Callback wait fails!"); - } - } - } - - // Restarts the camera intance and attach the preview to the corrent - // UI elements. - restartCamera(); - startPreview(); - - mTestCount = 0; - switch (index) { - case 1: - Log.v(TAG, "SP -> TP1 -> SP -> +1 -> Lock -> -1 -> TP2"); - test0(); - Log.v(TAG, "SP -> TP1 -> SP -> Lock -> +1 -> TP2 -> -1"); - test1(); - Log.v(TAG, "SP -> Lock -> +1 -> TP1 -> SP -> -1 -> Lock -> TP2"); - test2(); - Log.v(TAG, "SP -> Lock -> +1 -> TP1 -> SP -> Lock -> -1 -> TP2"); - test3(); - break; - case 2: - Log.v(TAG, "SP -> +1 -> TP1 -> -1 -> Lock -> SP -> TP2"); - test4(); - Log.v(TAG, "SP -> +1 -> TP1 -> Lock -> SP -> -1 -> TP2"); - test5(); - Log.v(TAG, "SP -> TP1 -> +1 -> Lock -> SP -> -1 -> TP2"); - test6(); - Log.v(TAG, "SP -> TP1 -> +1 -> Lock -> SP -> TP2"); - test7(); - Log.v(TAG, "SP -> TP1 -> Lock -> SP -> +1 -> TP2"); - test8(); - Log.v(TAG, "SP -> +1 -> Lock -> -1 -> TP1 -> Lock -> SP -> TP2"); - test9(); - Log.v(TAG, "SP -> +1 -> Lock -> TP1 -> -1 -> Lock -> SP -> TP2"); - test10(); - Log.v(TAG, "SP -> Lock -> TP1 -> +1 -> Lock -> SP -> -1 -> TP2"); - test11(); - break; - case 3: - Log.v(TAG, "Restart -> Lock -> SP -> TP1 -> Restart -> Lock -> SP -> +1 -> TP2"); - test12(); - Log.v(TAG, "Restart -> Lock -> SP -> +1 -> TP1 -> -1 -> Lock -> SP -> TP2"); - test13(); - Log.v(TAG, "Restart -> Lock -> SP -> +1 -> TP1 -> Lock -> SP -> -1 -> TP2"); - test14(); - Log.v(TAG, "Restart -> Lock -> SP -> TP1 -> +1 -> Lock -> SP -> -1 -> TP2"); - test15(); - Log.v(TAG, "Restart -> Lock -> SP -> TP1 -> +1 -> Lock -> SP -> TP2"); - test16(); - Log.v(TAG, "Restart -> Lock -> SP -> TP1 -> Lock -> SP -> +1 -> TP2"); - test17(); - Log.v(TAG, "Restart -> Lock -> SP -> TP1 -> Lock -> SP -> TP2"); - test18(); - break; - default: - break; - } - - releaseLock(); - - Log.v(TAG, "Ready to process data"); - boolean[] testCompareResults = new boolean[2 * mTestCount]; - - // Processes the data stored in the native test handler instance. - // Stores the test results into a boolean array. - processAutoLockTest(mTestHandler, testCompareResults); - - // Prepares the test result text output with the booelan result array. - prepareDebugText(testCompareResults, index); - mReferenceCompareResults.clear(); - mReferenceLogs.clear(); - } - - /** - * Compares two images taken under the same lighting, Image 1 without AE - * lock and Image 2 with AE locked under a bright light. Image 1 is - * expected to be brighter than Image 2. - * Tests whether AE lock works compared to no AE lock. - */ - private void test0() { - releaseLock(); - takePicture(); - startPreview(); - turnOnLight(); - setLock(); - turnOffLight(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Same lighting condition with one different lock"); - ++mTestCount; - } - - /** - * Compares two images taken under different lighting, Image 1 without AE - * lock and Image 2 with with AE locked under the same light Image 1 is - * taken. Image 2 is taken under a bright light. Image 1 is expected to be - * darker than Image 2. - * Tests whether AE lock works compared to no AE lock. - */ - private void test1() { - releaseLock(); - takePicture(); - startPreview(); - setLock(); - turnOnLight(); - takePicture(); - turnOffLight(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("One same lock with different lighting"); - ++mTestCount; - } - - /** - * Compares two images taken under different light, both with AE locked - * under the same lighting. Image 1 is taken under a brighter light. - * Image 1 is expected to be brighter than Image 2. - * Tests whether AE locks the exposure to the same level in the same - * lighting condition after preview restarts. - */ - private void test2() { - releaseLock(); - setLock(); - turnOnLight(); - takePicture(); - startPreview(); - turnOffLight(); - setLock(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Same locking locations with different lighting"); - ++mTestCount; - } - - /** - * Compares two images taken under different light, Image 1 with AE locked - * under normal light and Image 2 with AE locked under a bright light. - * Image 1 is taken under a bright light and Image 2 is taken in the normal - * lighting. Image 1 is expected to be brighter than Image 2. - * Tests whether AE lock can adjust to change of lighting conditions. - */ - private void test3() { - releaseLock(); - setLock(); - turnOnLight(); - takePicture(); - startPreview(); - setLock(); - turnOffLight(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Different locking locations with different lighting"); - ++mTestCount; - } - - /** - * Compares two images taken under different lighting, Image 1 without - * AE lock and Image 2 with AE lock set before camera preview resumes. - * Image 1 is taken under a bright light and the light is turned off before - * camera preview starts again. Image 1 is expected to be brighter than - * Image 2. - * Tests whether setting AE lock between camera preview stops and restarts - * can retain the exposure level of the previous AE-unlocked photo. - */ - private void test4() { - releaseLock(); - turnOnLight(); - takePicture(); - turnOffLight(); - setLock(); - startPreview(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after takePicture and light change, before preview"); - ++mTestCount; - } - - /** - * Compares two images taken under different lighting, Image 1 without - * AE lock and Image 2 with AE lock set before camera preview resumes. - * Image 1 is taken under a bright light and the light is turned off after - * preview restars but before Image 2 is taken. Image 1 is expected to be - * brighter than Image 2. - * Tests whether setting AE lock between camera preview stops and restarts - * can retain the exposure level of the previous AE-unlocked photo. - */ - private void test5() { - releaseLock(); - turnOnLight(); - takePicture(); - setLock(); - startPreview(); - turnOffLight(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock between takePicture and light change, w/o light change"); - ++mTestCount; - } - - private void test6() { - releaseLock(); - takePicture(); - turnOnLight(); - setLock(); - startPreview(); - turnOffLight(); - takePicture(); - startPreview(); - releaseLock(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add("Lock after takePicture and light change, before preview."); - ++mTestCount; - } - - private void test7() { - releaseLock(); - takePicture(); - turnOnLight(); - setLock(); - startPreview(); - takePicture(); - startPreview(); - releaseLock(); - turnOffLight(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after takePicture and light change, before preview."); - ++mTestCount; - } - - private void test8() { - releaseLock(); - takePicture(); - setLock(); - startPreview(); - turnOnLight(); - takePicture(); - startPreview(); - releaseLock(); - turnOffLight(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after takePicture and before startPreview."); - ++mTestCount; - } - - private void test9() { - releaseLock(); - turnOnLight(); - setLock(); - turnOffLight(); - takePicture(); - setLock(); - startPreview(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test10() { - releaseLock(); - turnOnLight(); - setLock(); - takePicture(); - turnOffLight(); - setLock(); - startPreview(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test11() { - releaseLock(); - setLock(); - takePicture(); - turnOnLight(); - setLock(); - startPreview(); - turnOffLight(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test12() { - //"Restart -> Lock -> SP -> TP1 -> Restart -> Lock -> SP -> +1 -> TP2" - restartCamera(); - setLock(); - startPreview(); - takePicture(); - releaseLock(); - restartCamera(); - setLock(); - startPreview(); - turnOnLight(); - takePicture(); - releaseLock(); - turnOffLight(); - startPreview(); - //mTestCamera.release(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock before first preview"); - ++mTestCount; - } - - private void test13() { - //"Restart -> Lock -> SP -> +1 -> TP1 -> -1 -> Lock -> SP -> TP2" - restartCamera(); - setLock(); - startPreview(); - turnOnLight(); - takePicture(); - turnOffLight(); - setLock(); - startPreview(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test14() { - //"Restart -> Lock -> SP -> +1 -> TP1 -> Lock -> SP -> -1 -> TP2" - restartCamera(); - setLock(); - startPreview(); - turnOnLight(); - takePicture(); - setLock(); - startPreview(); - turnOffLight(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test15() { - //"Restart -> Lock -> SP -> TP1 -> +1 -> Lock -> SP -> -1 -> TP2" - restartCamera(); - setLock(); - startPreview(); - takePicture(); - turnOnLight(); - setLock(); - startPreview(); - turnOffLight(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test16() { - //"Restart -> Lock -> SP -> TP1 -> +1 -> Lock -> SP -> TP2" - restartCamera(); - setLock(); - startPreview(); - takePicture(); - turnOnLight(); - setLock(); - startPreview(); - takePicture(); - turnOffLight(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test17() { - //"Restart -> Lock -> SP -> TP1 -> Lock -> SP -> +1 -> TP2" - restartCamera(); - setLock(); - startPreview(); - takePicture(); - setLock(); - startPreview(); - turnOnLight(); - takePicture(); - turnOffLight(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(false); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - private void test18() { - //"Restart -> Lock -> SP -> TP1 -> Lock -> SP -> TP2" - restartCamera(); - setLock(); - startPreview(); - takePicture(); - setLock(); - startPreview(); - takePicture(); - releaseLock(); - startPreview(); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add("Lock after first lock with changing light"); - ++mTestCount; - } - - /** - * Restarts the camera by releasing the current instance and get a new - * instance. Also connects this new camera instance's preview to the proper - * UI surfaceview. - */ - private void restartCamera() { - Log.v(TAG, "Restarting Camera"); - - mTestCamera.release(); - Log.v(TAG, "Camera released"); - - try { - mTestCamera = Camera.open(mActivity.getCameraIdx()); - } catch (RuntimeException e) { - throw new RuntimeException("Failed to open the camera", e); - } - - Camera.Parameters params = mTestCamera.getParameters(); - params.setPictureFormat(ImageFormat.JPEG); - params.setPictureSize(640, 480); - mTestCamera.setParameters(params); - - try { - mTestCamera.setPreviewDisplay(super.getCameraView().getHolder()); - } catch (IOException e) { - throw new RuntimeException("Unable to connect camera to display: " + e); - } - } - - /** - * Starts Camera preview with a delay of 2 seconds to let it adjust to - * the lighting condition. - */ - private void startPreview() { - mTestCamera.startPreview(); - try{ - Log.v(TAG, "Waiting"); - Thread.sleep(2000); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - } - - /** - * Sends command to ADK to turn on all the LED lights to white. - * Waits for 4 seconds for the camera to adjust to the new lighting. - */ - private void turnOnLight() { - Log.v(TAG, "Turn on light"); - if (mUsingUsb) { - byte[] buffer = new byte[3]; - - buffer[0] = (byte) 3; - buffer[1] = (byte) 0; - buffer[2] = (byte) 1; - if (mOutputStream != null && buffer[1] != -1) { - try { - mOutputStream.write(buffer); - } catch (IOException e) { - Log.e(TAG, "write failed", e); - } - } - } else { - mActivity.runOnUiThread(new Runnable() { - public void run() { - Toast.makeText(mActivity.getApplicationContext(), "Turn on light!", 4).show(); - - } - }); - } - - try{ - Log.v(TAG, "Waiting, Please Turn on light"); - Thread.sleep(LONG_SLEEP); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - } - - /** - * Sends command to ADK to turn off all LED lights. - * Waits for 4 seconds for the camera to adjust to the new lighting. - */ - private void turnOffLight() { - Log.v(TAG, "Turn off light"); - if (mUsingUsb) { - byte[] buffer = new byte[3]; - - buffer[0] = (byte) 3; - buffer[1] = (byte) 0; - buffer[2] = (byte) 0; - if (mOutputStream != null && buffer[1] != -1) { - try { - mOutputStream.write(buffer); - } catch (IOException e) { - Log.e(TAG, "write failed", e); - } - } - } else { - mActivity.runOnUiThread(new Runnable() { - public void run() { - Toast.makeText(mActivity.getApplicationContext(), "Turn off light!", 4).show(); - - } - }); - } - - try{ - Log.v(TAG, "Waiting, Please Turn off light"); - Thread.sleep(LONG_SLEEP); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - } - - /** - * Sets the Auto Exposure Lock. - * Waits for 2 seonds for the lock to function. - */ - private void setLock() { - Camera.Parameters params = mTestCamera.getParameters(); - - params.setAutoExposureLock(true); - params.setAutoWhiteBalanceLock(true); - mTestCamera.setParameters(params); - try{ - Log.v(TAG, "Waiting to set lock"); - Thread.sleep(2000); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - } - - /** - * Releases the Auto Exposure Lock. - * Waits for 4 seconds afterwards for the Auto Exposure to be adjusted - * to the lighting condition. - */ - private void releaseLock() { - Camera.Parameters params = mTestCamera.getParameters(); - - params.setAutoExposureLock(false); - params.setAutoWhiteBalanceLock(false); - mTestCamera.setParameters(params); - try{ - Log.v(TAG, "Waiting to release lock"); - Thread.sleep(LONG_SLEEP); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - - } - - /** - * Takes a picture and locks thread until the picture callback finishes. - */ - private void takePicture(){ - mTestCamera.takePicture(null, null, null, mTestJpegListener); - - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - // System.gc(); - mProcessingImage.wait(); - } catch (InterruptedException e){ - Log.v(TAG, "Callback wait fails!"); - } - } - } - - /** - * Prepare for the result to be shown in the UI. The result for each single - * test is shown in green if it matches the reference result. It is shown - * in red otherwise. - */ - private void prepareDebugText(boolean[] testCompareResults, int index) { - boolean groupTestPassed = true; - for (int i = 0; i < mTestCount; ++i) { - String testLog; - boolean testPassed = true; - testLog = mReferenceLogs.get(i); - mDebugText += (testLog + "<br/>"); - - if (testCompareResults[i * 2] == mReferenceCompareResults.get(i * 2)) { - mDebugText += String.format( - "Picture 1 brighter than Picture 2 is %b \n", - testCompareResults[i * 2]); - } else { - mDebugText += String.format( - "Picture 1 brighter than Picture 2 is %b \n", - testCompareResults[i * 2]); - testPassed = false; - } - - if (testCompareResults[i * 2 + 1] == mReferenceCompareResults.get(i * 2 + 1)) { - mDebugText += String.format( - "Picture 1 is equivalent to Picture 2 is %b \n", - testCompareResults[i * 2 + 1]); - } else { - mDebugText += String.format( - "Picture 1 is equivalent to Picture 2 is %b \n", - testCompareResults[i * 2 + 1]); - testPassed = false; - } - - if (testPassed) { - mDebugText += "Test passed! \n"; - } else { - mDebugText += "Test failed! \n"; - groupTestPassed = false; - } - } - if (groupTestPassed) { - mTestResults[index] = CameraTests.CAMERA_TEST_SUCCESS; - } else { - mTestResults[index] = CameraTests.CAMERA_TEST_FAILURE; - } - } - - /** - * Clears the debug text so that new test results can be added. - */ - public void clearDebugText() { - mDebugText = ""; - } - - @Override - public String getDebugText() { - return mDebugText; - } - - @Override - public String getResultText() { - return mDebugText; - } - - @Override - public String getTestName() { - return "Auto Exposure Lock test: \n"; - } - - @Override - public String getTestName(int index) { - switch (index) { - case 0: - return "Run all tests"; - case 1: - return "Compulsory tests"; - case 2: - return "Recommended tests (preview behavior)"; - case 3: - return "Optional tests (default lock)"; - default: - return ""; - } - } - - @Override - public int getResult(int index) { - return mTestResults[index]; - } - - @Override - public int getNumTests() { - return mNumTests; - } - - private Camera.PictureCallback mTestJpegListener = new Camera.PictureCallback() { - public void onPictureTaken(byte[] data, Camera mCamera) { - Log.v(TAG, "Shutter pressed down!"); - Bitmap inputImage; - - // Decodes the camera input data into Bitmap. - // Constructs a native image class with the image. - inputImage = BitmapFactory.decodeByteArray(data, 0, data.length); - long bufferAddress = findNative(inputImage); - Log.v(TAG, "findNative method finishes"); - - // Cleans up memory taken by the Bitmap. - data = null; - inputImage.recycle(); - inputImage = null; - System.gc(); - - // Passes data from the native image class to the native - // test handler. - createAutoLockClass(bufferAddress, mTestHandler, - getCheckerCenter(), getCheckerRadius()); - - // Unlocks the thread lock. - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - }; - - private native long createAutoLockTest(); - - private native void createAutoLockClass(long bufferAddress, long handlerAddress, - long checkerCenterAddress, - long checkerRadiusAddress); - - private native void processAutoLockTest(long handlerAddress, boolean[] testCompareResults); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java deleted file mode 100644 index 34e8d2d..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraAnalyzerActivity.java +++ /dev/null
@@ -1,500 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import com.android.cts.verifier.PassFailButtons; -import com.android.cts.verifier.R; - -import android.app.Activity; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.graphics.ImageFormat; -import android.hardware.Camera; -import android.hardware.Camera.CameraInfo; -import android.hardware.Camera.Size; -import android.os.AsyncTask; -import android.os.Bundle; -import android.text.Html; -import android.text.method.ScrollingMovementMethod; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.SurfaceHolder; -import android.view.SurfaceView; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Button; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; -import android.content.Context; - -import java.io.IOException; -import java.lang.Thread; -import java.util.List; - -/** - * Controls the UI activities of the camera quality test app. It is created - * as soon as the app started. Users can launch different quality tests with - * the buttons in the UI. This class will manage the threading for different - * tests. Also it will provide debug output or debug text results for tests. - */ -public class CameraAnalyzerActivity extends PassFailButtons.Activity { - - private static final String TAG = "CameraAnalyzer"; - private SurfaceView mCameraView; - private ImageView mResultView; - private Button mFindCheckerButton; - private Button mExposureCompensationButton; - private Button mWhiteBalanceButton; - private Button mAutoLockButton; - private Button mMeteringButton; - private ListView mTestList; - private TwoColumnAdapter mAdapter; - - private Camera mCamera; - private int mCameraIdx = 0; - private boolean mIsCameraOpen = false; - - private PowerManager mPowerManager; - private PowerManager.WakeLock mWakeLock; - - private boolean mProcessingPicture = false; - private boolean mTestInProgress = false; - private final Object mProcessingTest = new Object(); - private CameraTests mCurrentTest = null; - - private long mCheckerCenterAddress; - private long mCheckerRadiusAddress; - - private String mResultReport = ""; - static final String[] TESTS = new String[] {"Test1", "Test2"}; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.ca_main); - setPassFailButtonClickListeners(); - setInfoResources(R.string.camera_analyzer, R.string.ca_info, -1); - - mFindCheckerButton = (Button) findViewById(R.id.findcheckerboardbutton); - mExposureCompensationButton = (Button) findViewById(R.id.exposurecompensationbutton); - mWhiteBalanceButton = (Button) findViewById(R.id.whitebalancebutton); - mAutoLockButton = (Button) findViewById(R.id.lockbutton); - mMeteringButton = (Button) findViewById(R.id.meteringbutton); - mCameraView = (SurfaceView) findViewById(R.id.cameraview); - mResultView = (ImageView) findViewById(R.id.resultview); - mTestList = (ListView) findViewById(R.id.ca_tests); - mAdapter = new TwoColumnAdapter(this); - - // Initialize the list view. - initializeAdapter(); - mTestList.setAdapter(mAdapter); - mTestList.setOnItemClickListener(mListListener); - - mFindCheckerButton.setOnClickListener(mFindCheckerListener); - mExposureCompensationButton.setOnClickListener(mExposureCompensationListener); - mWhiteBalanceButton.setOnClickListener(mWhiteBalanceListener); - mAutoLockButton.setOnClickListener(mAutoLockListener); - mMeteringButton.setOnClickListener(mMeteringListener); - mCameraView.getHolder().addCallback(mSurfaceChangeListener); - - // Disables all test buttons except the color checker test one. - // They will be enabled after the color checker is located. - mExposureCompensationButton.setEnabled(false); - mWhiteBalanceButton.setEnabled(false); - mAutoLockButton.setEnabled(false); - mMeteringButton.setEnabled(false); - } - - @Override - public void onResume() { - super.onResume(); - - openCamera(mCameraIdx); - Camera.Parameters params = mCamera.getParameters(); - params.setPictureFormat(ImageFormat.JPEG); - params.setPictureSize(640, 480); - mCamera.setParameters(params); - Log.v(TAG, "Set resolution to 640*480"); - } - - @Override - public void onPause() { - super.onPause(); - CameraTests.getCamera().release(); - mIsCameraOpen = false; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.ca_menu, menu); - - Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); - int cameraCount = Camera.getNumberOfCameras(); - for (int camIdx = 0; camIdx < cameraCount; ++camIdx) { - MenuItem cameraMenuItem = menu.add(0, camIdx, Menu.NONE, - String.format("Open Camera %d", camIdx)); - } - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() != mCameraIdx) { - mCameraIdx = item.getItemId(); - new SwitchCameraTask().execute(mCameraIdx); - } - return false; - } - - private class SwitchCameraTask extends AsyncTask<Integer, Void, Void> { - @Override - protected Void doInBackground(Integer... camIdx) { - if (mTestInProgress) { - synchronized (mProcessingTest) { - try{ - Log.v(TAG, "Waiting for test to finish"); - mProcessingTest.wait(); - } catch (InterruptedException e){ - Log.v(TAG, "test wait fails!"); - } - } - } - - openCamera((int)camIdx[0]); - return null; - } - } - - private synchronized void openCamera(int camIdx) { - if (mIsCameraOpen) { - CameraTests.getCamera().release(); - Log.v(TAG, "Releasing the cameratests camera"); - } - try { - mCamera = Camera.open(camIdx); - mIsCameraOpen = true; - } catch (RuntimeException e) { - throw new RuntimeException("Failed to open the camera", e); - } - - try { - mCamera.setPreviewDisplay(mCameraView.getHolder()); - } catch (IOException e) { - throw new RuntimeException("Unable to connect camera to display: " + e); - } - mCamera.startPreview(); - CameraTests.setCamera(mCamera); - - ColorCheckerTest.getSingletonTest().updateCamera(); - WhiteBalanceTest.getSingletonTest().updateCamera(); - ExposureCompensationTest.getSingletonTest().updateCamera(); - MeteringTest.getSingletonTest().updateCamera(); - AutoLockTest.getSingletonTest().updateCamera(); - } - - public Camera getCameraInstance() { - return mCamera; - } - - public void disableAll() { - mExposureCompensationButton.setEnabled(false); - mWhiteBalanceButton.setEnabled(false); - mAutoLockButton.setEnabled(false); - mMeteringButton.setEnabled(false); - mFindCheckerButton.setEnabled(false); - } - - public void enableAll() { - mExposureCompensationButton.setEnabled(true); - mWhiteBalanceButton.setEnabled(true); - mAutoLockButton.setEnabled(true); - mMeteringButton.setEnabled(true); - mFindCheckerButton.setEnabled(true); - } - - /** - * Provides an abstraction for the Camera tests. The camera tests will - * run in the background and the results will be shown in the UI thread - * after the tests are processed. - */ - private class DebugOutputProcessingTask extends AsyncTask<Integer, - Integer, - Integer> { - @Override - protected Integer doInBackground(Integer... cameraTestIndex) { - Log.v(TAG, "Do in Background started!"); - - mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); - mWakeLock = mPowerManager.newWakeLock( - PowerManager.SCREEN_DIM_WAKE_LOCK, "CameraQualityTest"); - mWakeLock.acquire(); - - mTestInProgress = true; - - // Processes the camera tests one by one and publishes their - // debug output or debug text results after each test is done. - mCurrentTest.run((int)cameraTestIndex[0]); - publishProgress(cameraTestIndex); - - Log.v(TAG, "Do in Background thread returns!"); - return cameraTestIndex[0]; - } - - @Override - protected void onProgressUpdate(Integer... cameraTestIndex) { - Log.v(TAG, "Prepare to get debug output!"); - - // Copies the debug output image or text results to the UI. - mResultView.setImageBitmap(mCurrentTest.getDebugOutput()); - mResultReport += (mCurrentTest.getTestName() + mCurrentTest.getDebugText()); - mAdapter.notifyDataSetChanged(); - } - - @Override - protected void onPostExecute(Integer cameraTestIndex) { - - // If the test is to find the color checker, copy the memory - // address of the found color checker centers and radius to the - // CameraTests class' static fields. - if (mCurrentTest.copyCheckerAddress()) { - mCheckerCenterAddress = CameraTests.getCheckerCenter(); - mCheckerRadiusAddress = CameraTests.getCheckerRadius(); - } - - if (mCurrentTest.copyCheckerAddress() || - !mCurrentTest.getTestName().contains("Color Checker")) { - // Enables the button of all other tests after the color checker - // is found. Now the user can start all other available tests. - enableAll(); - } - - mWakeLock.release(); - mTestInProgress = false; - synchronized (mProcessingTest) { - mProcessingTest.notifyAll(); - } - - } - } - - // Creates and runs a new test to find color checker in the captured image. - // It is invoked when users press the Find color checker button in the UI. - private View.OnClickListener mFindCheckerListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - Log.v(TAG, "Running new color checker finding tests!"); - ColorCheckerTest colorCheckerTest = ColorCheckerTest.getSingletonTest(); - - mCurrentTest = colorCheckerTest; - initializeAdapter(); - } - }; - - // Creates and runs a new test to test the exposure compensation function. - // It is invoked when users press the Exposure Compensation Test button - // in the UI. - private View.OnClickListener mExposureCompensationListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - Log.v(TAG, "Running new exposure compensation tests!"); - - ExposureCompensationTest exposureCompensationTest = - ExposureCompensationTest.getSingletonTest(); - - mCurrentTest = exposureCompensationTest; - initializeAdapter(); - - // Loads the memory address of the checker centers and radius - // from the this class and set the two values for the new test. - ExposureCompensationTest.setCheckerAddress(mCheckerCenterAddress, - mCheckerRadiusAddress); - } - }; - - // Creates and runs a new test to test the white balance function. - // It is invoked when users press the White Balance Test button in the UI. - private View.OnClickListener mWhiteBalanceListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - Log.v(TAG, "Running new white balance tests!"); - - WhiteBalanceTest whiteBalanceTest = WhiteBalanceTest.getSingletonTest(); - - mCurrentTest = whiteBalanceTest; - initializeAdapter(); - - // Loads the memory address of the checker centers and radius - // from the this class and set the two values for the new test. - WhiteBalanceTest.setCheckerAddress(mCheckerCenterAddress, mCheckerRadiusAddress); - } - }; - - // Creates and runs a new test to test the camera metering function. - // It is invoked when users press the Metering Test button in the UI. - private View.OnClickListener mMeteringListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - Log.v(TAG, "Running new metering tests!"); - - MeteringTest meteringTest = MeteringTest.getSingletonTest(); - - mCurrentTest = meteringTest; - initializeAdapter(); - - // Loads the memory address of the checker centers and radius - // from the this class and set the two values for the new test. - MeteringTest.setCheckerAddress(mCheckerCenterAddress, mCheckerRadiusAddress); - } - }; - - // Creates and runs new tests to test the camera auto exposure lock. - // It is invoked when users press the AWB and AE Lock Test button - // in the UI. - private View.OnClickListener mAutoLockListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - Log.v(TAG, "Running New auto exposure/wb lock tests!"); - - // Loads the memory address of the checker centers and radius - // from the this class and set the two values for the new test. - AutoLockTest.setCheckerAddress(mCheckerCenterAddress, mCheckerRadiusAddress); - - // Construct all base case test scenearios for the Auto Lock test. - // Detailed documentation on each test can be found in native code. - AutoLockTest autoLockTest = AutoLockTest.getSingletonTest(); - autoLockTest.setActivity(CameraAnalyzerActivity.this); - - mCurrentTest = autoLockTest; - initializeAdapter(); - - } - }; - - // Creates a list listner that launches the experiment with the user's click - private AdapterView.OnItemClickListener mListListener = new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - Log.v(TAG, String.format("Item %d selected!", position)); - if (!mTestInProgress) { - DebugOutputProcessingTask captureTask = new DebugOutputProcessingTask(); - disableAll(); - captureTask.execute(position); - } - } - }; - - private SurfaceHolder.Callback mSurfaceChangeListener = - new SurfaceHolder.Callback() { - - // Sets the aspect ratio of the camera preview to 4:3 - @Override - public void surfaceChanged(SurfaceHolder holder, - int format, - int width, - int height) { - int x = mCameraView.getWidth(); - int y = mCameraView.getHeight(); - Log.v(TAG, String.format("Measures are %d, %d", x, y)); - - if ( x > 4.0 / 3.0 * y) { - android.view.ViewGroup.LayoutParams lp = mCameraView.getLayoutParams(); - lp.height = y; - lp.width = (int)(4.0 / 3.0 * lp.height); - Log.v(TAG, String.format("params are %d, %d", lp.width, lp.height)); - mCameraView.setLayoutParams(lp); - } - - try { - mCamera.setPreviewDisplay(mCameraView.getHolder()); - } catch (IOException e) { - throw new RuntimeException("Unable to connect camera to display: " + e); - } - CameraTests.setCameraView(mCameraView); - mCamera.startPreview(); - } - - @Override - public void surfaceCreated(SurfaceHolder holder) {} - - @Override - public void surfaceDestroyed(SurfaceHolder holder) {} - }; - - @Override - public String getTestDetails() { - return mResultReport; - } - - class TwoColumnAdapter extends ArrayAdapter<String> { - TwoColumnAdapter(Context context) { - super(context, R.layout.ca_row); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - LayoutInflater inflater = getLayoutInflater(); - View row = inflater.inflate(R.layout.ca_row, parent, false); - ImageView iconField = (ImageView) row.findViewById(R.id.caTestIcon); - TextView nameField = (TextView) row.findViewById(R.id.caTestName); - TextView resultField = (TextView) row.findViewById(R.id.caTestResult); - if (mCurrentTest != null) { - nameField.setText(mCurrentTest.getTestName(position)); - int result = mCurrentTest.getResult(position); - switch (result) { - case CameraTests.CAMERA_TEST_SUCCESS: - resultField.setText("Success"); - iconField.setBackgroundColor(Color.rgb(0x99,0xCC,00)); - resultField.setTextColor(Color.rgb(0x99,0xCC,00)); - break; - case CameraTests.CAMERA_TEST_FAILURE: - resultField.setText("Failed!"); - iconField.setBackgroundColor(Color.rgb(0xFF,0x44,0x44)); - resultField.setTextColor(Color.rgb(0xFF,0x44,0x44)); - break; - case CameraTests.CAMERA_TEST_NOT_RUN: - resultField.setText("Tap to run"); - iconField.setBackgroundColor(Color.rgb(0x00,0x99,0xCC)); - resultField.setTextColor(Color.rgb(0x33,0xB5,0xE5)); - break; - } - } - return row; - } - } - - private void initializeAdapter() { - mAdapter.clear(); - if (mCurrentTest != null) { - for (int i = 0; i < mCurrentTest.getNumTests(); ++i) { - mAdapter.add(mCurrentTest.getTestName(i)); - } - } - } - - public int getCameraIdx() { - return mCameraIdx; - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraTests.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraTests.java deleted file mode 100644 index ed99524..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/CameraTests.java +++ /dev/null
@@ -1,201 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.graphics.Bitmap; -import android.hardware.Camera; -import android.os.Environment; -import android.util.Log; -import android.view.SurfaceView; - -import java.io.FileOutputStream; -import java.io.File; -import java.lang.Runnable; - -/** - * Provides an abstraction for all camera tests and allows communication - * between camera test classes with the UI thread. This base class provides - * functions to contruct and access debug output images. It can access and - * set the pointer address of checkerboard centers and radius. It also provides - * native methods to convert an image shot by the camera into a native - * character array. Another native method it provides is to create a native - * test handler with desired debug height and width. - */ -public abstract class CameraTests{ - - public static final int CAMERA_TEST_NOT_RUN = 0; - public static final int CAMERA_TEST_SUCCESS = 1; - public static final int CAMERA_TEST_FAILURE = 2; - - private static final String TAG = "CameraTests"; - - /** Memory address of the color checker centers. */ - private static long sCheckerCenterAddress = 0; - /** Memory address of the color checker radius. */ - private static long sCheckerRadiusAddress = 0; - /** The surface view linked with the camera preview. */ - private static SurfaceView sCameraView; - /** Image debug output. */ - private Bitmap mDebugOutput; - /** Shared camera instance. */ - protected static Camera mTestCamera = null; - - /** - * Constructs the base CameraTests class. - */ - public CameraTests() {} - - /** - * Returns debug Bitmap image. In the test to find the color checker, - * the debug image will be the captured image with a matched color checker - * overlay on top. In the exposure compensation test, the debug image - * will be the response curve of the camera. - * @return A low-resolution Bitmap to be displayed in the UI. - */ - public Bitmap getDebugOutput() { - return mDebugOutput; - } - - public String getDebugText() { - return ""; - } - - public abstract String getTestName(); - - /** - * Gets the detailed report for CTS output. - */ - public String getResultText(){ - return "Details not available \n"; - } - - /** - * Provides a polymorphism to start the run() method for all child classes. - */ - public abstract void run(int index); - - public SurfaceView getCameraView() { - return sCameraView; - } - - public static void setCameraView(SurfaceView cameraView) { - sCameraView = cameraView; - } - - /** - * Refreshes the camera instance when the activity opens a new camera. - */ - public static void setCamera(Camera newCamera) { - mTestCamera = newCamera; - } - - public static Camera getCamera() { - return mTestCamera; - } - - /** - * Sets the memory address of the checker centers and checker radius. - * - * @param inputCenterAddress the new memory address of - * the color checker centers - * @param inputRadiusAddress the new memory address of - * the color checker radius - */ - public static void setCheckerAddress(long inputCenterAddress, long inputRadiusAddress) { - sCheckerCenterAddress = inputCenterAddress; - sCheckerRadiusAddress = inputRadiusAddress; - } - - /** - * Provides polymorphism to indicate whether the checker memory addresses - * should be copied. - * - * @return <code>true</code> if the class invoking the method needs to - * update the memory address of the color checker - * centers and radius; - * <code>false</code> if the class invoking the method does NOT - * update the memory address of the color checker - * centers and radius. - */ - public boolean copyCheckerAddress() { - return false; - } - - public void cleanUp() { - } - - public static long getCheckerCenter() { - return sCheckerCenterAddress; - } - - public static long getCheckerRadius() { - return sCheckerRadiusAddress; - } - - public abstract String getTestName(int index); - - public abstract int getResult(int index); - - public abstract int getNumTests(); - - /** - * Provides a native method to convert the input Bitmap of the captured - * image into a native character array and constructs a native image class - * with this character array. This method currently supports conversion - * of Bitmaps in the formats of RGB_565 and RGB_8888. - * - * @param input the input Bitmap, which is decoded from the camrea data. - * - * @return the memory address of the native image class which contains - * the character array. - */ - public native long findNative(Bitmap input); - - /** - * Provides a native method to create a native image handler class. The - * native image handler class is the base class for all test classes and - * contains the debug output as a character array. - * - * @param outputHeight the desired height for the debug output - * @param outputWidth the desired width for the debug output - * - * @return the memory address of the native test handler class. - */ - public native long createImageTestHandler(int outputHeight, int outputWidth); - - /** - * Provides a native method to clean up the memory taken by the handler. - * - * @param handlerAddress the memory address of the native test handler, - * which contains the debug output. - */ - public native void cleanUpHandler(long handlerAddress); - - /** - * Provides a native method to convert the native debug output from - * character array back to Bitmap and copy it to the debug output of this - * class. - * - * @param handlerAddress the memory address of the native test handler, - * which contains the debug output. - */ - public native void displayHandlerDebugOutput(long handlerAddress); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorCheckerTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorCheckerTest.java deleted file mode 100644 index ad171b4..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ColorCheckerTest.java +++ /dev/null
@@ -1,299 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.hardware.Camera; -import android.util.Log; -import android.widget.ImageView; - -import java.util.List; - -/** Locates a Xrite Classic Color Checker grid pattern in an image, stores the - * center positions and the color checker radius, and provides a function to - * get the memory address of these two properties. - * - * The pattern is a 6x4 grid of square color patches. The detection routine - * assumes the pattern is placed roughly facing the camera, with the long size - * roughly horizontal. It also assumes that the grey squares are in the bottom - * row. - */ -public class ColorCheckerTest extends CameraTests { - - private static final String TAG = "ColorCheckerTest"; - - /** Memory address of the image class instance that contains the image. */ - private long mClassAddress; - /** Memory address of the image test class instance. */ - private long mTestHandler; - /** Thread lock. */ - private final Object mProcessingImage = new Object(); - /** Boolean to tell whether auto focus has succeded.*/ - private boolean mAutoFocusSuccess; - /** Boolean to tell whether auto focus is supported.*/ - private boolean mAutoFocusEnabled = false; - /** Singleton instance of the class.*/ - private static ColorCheckerTest singletonTest = null; - - private boolean mFindCheckerSuccess = false; - private boolean mHasRunOnce = false; - - /** - * Constructs a <code>ColorCheckerTest</code> instance with a given - * Camera pointer. - */ - private ColorCheckerTest() { - super(); - } - - /** - * Updates the camera and parameter when the activity switches camera. - */ - public void updateCamera() { - Camera.Parameters params = mTestCamera.getParameters(); - List<String> supportedFocusModes = params.getSupportedFocusModes(); - - // Sets camera focus mode to Auto focus if it is supported. - if (supportedFocusModes.contains(params.FOCUS_MODE_AUTO)) { - Log.v(TAG, "Auto focus possible"); - params.setFocusMode(params.FOCUS_MODE_AUTO); - mTestCamera.setParameters(params); - mAutoFocusEnabled = true; - } else { - mAutoFocusEnabled = false; - } - } - - public static synchronized ColorCheckerTest getSingletonTest() { - if (singletonTest == null) { - Log.v(TAG, "Creating a new ColorCheckerTest instance"); - singletonTest = new ColorCheckerTest(); - singletonTest.initializeTest(); - } - return singletonTest; - } - - private void initializeTest() { - // Creates a native test handler with a 120x160 pixel debug output - mTestHandler = createColorCheckerTest(120, 160); - } - - @Override - public synchronized void run(int index) { - Log.v(TAG, "ColorCheckerTest thread started!"); - mAutoFocusSuccess = false; - mFindCheckerSuccess = false; - mHasRunOnce = true; - // Sets camera focus mode to Auto focus if it is supported. - if (mAutoFocusEnabled) { - while (!mAutoFocusSuccess) { - // Starts the auto focus process of the camera. - mTestCamera.autoFocus(mAutoFocusListener); - - // Locks thread until the camera finishes taking picture. - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - mProcessingImage.wait(); - } catch (InterruptedException e) { - Log.v(TAG, "Callback wait fails!"); - } - } - } - } else { - mTestCamera.takePicture(null, null, null, mTestJpegListener); - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - mProcessingImage.wait(); - } catch (InterruptedException e) { - Log.v(TAG, "Callback wait fails!"); - } - } - } - - // Launches the native method to find the color checker in the image. - mFindCheckerSuccess = processColorCheckerTest(mTestHandler); - // Displays the debug output from the native test handler instance. - displayHandlerDebugOutput(mTestHandler); - - Log.v(TAG, "Callback has returned!"); - } - - private Camera.AutoFocusCallback mAutoFocusListener = new Camera.AutoFocusCallback() { - public void onAutoFocus(boolean mSuccess, Camera mCamera) { - if (mSuccess) { - mAutoFocusSuccess = true; - Log.v(TAG, "Autofocus success!"); - mCamera.takePicture(null, null, null, mTestJpegListener); - } else { - try{ - Log.v(TAG, "Autofocus failed. Please adjust!"); - Thread.sleep(4000); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){} - - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - } - }; - - private Camera.PictureCallback mTestJpegListener = new Camera.PictureCallback() { - public void onPictureTaken(byte[] data, Camera mCamera) { - Log.v(TAG, "Shutter pressed down!"); - - // Changes the focus mode to fixed to avoid focus shift after - // auto focus is successful. - //Camera.Parameters params = mCamera.getParameters(); - //params.setFocusMode(params.FOCUS_MODE_FIXED); - //mCamera.setParameters(params); - - // Decodes the camera data to Bitmap and creates a native image - // class with the Bitmap. - Bitmap inputImage; - inputImage = BitmapFactory.decodeByteArray(data, 0, data.length); - long bufferAddress = findNative(inputImage); - Log.v(TAG, "findNative method finishes"); - - // Cleans up the Bitmap memory space. - inputImage.recycle(); - data = null; - inputImage = null; - System.gc(); - - // Constructs a test handler class to handle the image. - createColorCheckerClass(bufferAddress, mTestHandler); - - mCamera.startPreview(); - - // Notifies the thread lock the image capture is done. - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - }; - - /** - * Overrides the base class method and use the memory addresses of the - * checker centers and radius computed by the native test handler class - * to update the values stored in the base class. - * - * @return <code>true</code> indicating a memory address upload is needed. - */ - @Override - public boolean copyCheckerAddress() { - if (mFindCheckerSuccess) { - setCheckerAddress(getColorCheckerCenterAdd(mTestHandler), - getColorCheckerRadiusAdd(mTestHandler)); - return true; - } else { - return false; - } - } - - @Override - public void cleanUp() { - cleanUpHandler(mTestHandler); - } - - @Override - public String getTestName() { - return "Color Checker test: \n"; - } - - @Override - public String getTestName(int index) { - return "Find color checker"; - } - - @Override - public int getResult(int index) { - if (mFindCheckerSuccess) { - return CameraTests.CAMERA_TEST_SUCCESS; - } else { - if (mHasRunOnce) { - return CameraTests.CAMERA_TEST_FAILURE; - } else { - return CameraTests.CAMERA_TEST_NOT_RUN; - } - } - } - - @Override - public int getNumTests() { - return 1; - } - - /** - * Gets the memory address of the vector storing the color checker centers - * from the native test handler instance. - * - * @param handlerAddress the memory address of the native test handler - * instance - * - * @return memory address of the native vector storing the color checker - * centers' coordinates - */ - private native long getColorCheckerRadiusAdd(long handlerAddress); - - /** - * Gets the memory address of the vector storing the color checker radius - * from the native test handler instance. - * - * @param handlerAddress the memory address of the native test handler - * instance. - * - * @return memory address of the native vector storing the color checker - * centers' coordinates - */ - private native long getColorCheckerCenterAdd(long handlerAddress); - - /** - * Creates a native color checker test handler instance. - * - * @param outputWidth the desired width for the debug output - * @param outputHeight the desired height of the debug output - * - * @return memory address of the native test handler instance - */ - private native long createColorCheckerTest(int outputWidth, int outputHeight); - - /** - * Loads a native image class instances and extracts data from it to add - * to the test handler. - * - * @param bufferAddress the memory address of the image class instance - * @param handlerAddress the memory address of the test handler instance - */ - private native void createColorCheckerClass(long bufferAddress, long handlerAddress); - - /** - * Processes the data in the native test handler instance. Computes test - * results with all the data and construct a debug image or debug text - * outputs. - * - * @param handlerAddress the memory address of the test handler instance - */ - private native boolean processColorCheckerTest(long handlerAddress); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ExposureCompensationTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ExposureCompensationTest.java deleted file mode 100644 index 9a8d9f0..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/ExposureCompensationTest.java +++ /dev/null
@@ -1,215 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.ImageFormat; -import android.hardware.Camera; -import android.util.Log; -import android.widget.ImageView; - -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Random; - -public class ExposureCompensationTest extends CameraTests { - - private static final String TAG = "ExposureCompensationTest"; - - /** Records the current exposure level. */ - private float mExposureLevel; - /** Lock for the camera object.*/ - private final Object mProcessingImage = new Object(); - /** Lock for the camera's auto focusing task.*/ - private final Object mAutoFocusing = new Object(); - /** Memory address of the native test handler.*/ - private long mTestHandler; - /** Test results. */ - private int[] mTestResults; - /** Number of sub-tests. */ - private int mNumTests; - /** Camera Parameters. */ - private Camera.Parameters mParams; - /** Debug results in text. */ - private String mDebugText; - - private static ExposureCompensationTest singletonTest = null; - - private ExposureCompensationTest(){ - super(); - } - - /** Prepares the camera and the related parameters for the test.*/ - public void updateCamera() { - mParams = mTestCamera.getParameters(); - Log.v(TAG, String.format("Exposure level is from %d to %d", - mParams.getMinExposureCompensation(), - mParams.getMaxExposureCompensation())); - mNumTests = (int) ((float) (mParams.getMaxExposureCompensation() - - mParams.getMinExposureCompensation()) - * mParams.getExposureCompensationStep()); - mTestResults = new int[mNumTests + 1]; - for (int i = 0; i < mNumTests + 1; ++i) { - mTestResults[i] = CameraTests.CAMERA_TEST_NOT_RUN; - } - } - - public static synchronized ExposureCompensationTest getSingletonTest() { - if (singletonTest == null) { - Log.v(TAG, "Creating a new ExposureCompensationTest instance"); - singletonTest = new ExposureCompensationTest(); - singletonTest.initializeTest(); - } - return singletonTest; - } - - private void initializeTest() { - mDebugText = new String(); - // Creates a native test handler with a 120x160 pixel debug output - mTestHandler = createExposureCompensationTest(200, 280); - } - - @Override - public synchronized void run(int index){ - Log.v(TAG, "ExposureCompensationTest thread started!"); - - int testRangeMin, testRangeMax; - if (index == 0) { - testRangeMin = mParams.getMinExposureCompensation(); - testRangeMax = mParams.getMaxExposureCompensation(); - } else { - testRangeMin = (int) ((float)(index - 1) / mParams.getExposureCompensationStep()) - + mParams.getMinExposureCompensation(); - testRangeMax = (int) ((float)(index) / mParams.getExposureCompensationStep()) - + mParams.getMinExposureCompensation(); - } - - /** Checks for each exposure compensation setting within the test range.*/ - for (int i = testRangeMin; - i <= testRangeMax; i += 1){ - mExposureLevel = i * mParams.getExposureCompensationStep(); - Log.v(TAG, String.format("Current exposure level is %d", i)); - int mCameraExposure; - - do{ - mParams.setExposureCompensation(i); - mTestCamera.setParameters(mParams); - - try{ - Log.v(TAG, "Waiting"); - Thread.sleep(4000); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e){ - //TODO: error handling. - } - - mParams = mTestCamera.getParameters(); - mCameraExposure = mParams.getExposureCompensation(); - Log.v(TAG, String.format("Camera exposure level is %d", mCameraExposure)); - } while (mCameraExposure != i); - - mTestCamera.takePicture(null, null, null, mTestJpegListener); - - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - mProcessingImage.wait(); - } catch (InterruptedException e){ - Log.v(TAG, "Callback wait fails!"); - } - } - } - - mDebugText = processExposureCompensationTest(mTestHandler); - displayHandlerDebugOutput(mTestHandler); - - Log.v(TAG, "Callback has returned!"); - mParams.setExposureCompensation(0); - mTestCamera.setParameters(mParams); - } - - private Camera.PictureCallback mTestJpegListener = new Camera.PictureCallback() { - public void onPictureTaken(byte[] data, Camera mCamera) { - Log.v(TAG, "Shutter pressed down!"); - Log.v(TAG, String.format("Current exposure is %f", mExposureLevel)); - - Bitmap inputImage; - - inputImage = BitmapFactory.decodeByteArray(data, 0, data.length); - long bufferAddress = findNative(inputImage); - Log.v(TAG, "findNative method finishes"); - - inputImage.recycle(); - data = null; - inputImage = null; - System.gc(); - - createExposureCompensationClass(bufferAddress, mTestHandler, - getCheckerCenter(), getCheckerRadius(), - mExposureLevel); - mCamera.startPreview(); - - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - }; - - @Override - public String getTestName(int index) { - switch (index) { - case 0: - return "EC All Range"; - default: - return String.format("EC %d -> %d", (index - mNumTests / 2 - 1) * 10, - (index - mNumTests / 2) * 10); - } - } - - @Override - public int getResult(int index) { - return mTestResults[index]; - } - - @Override - public int getNumTests() { - return mNumTests + 1; - } - - @Override - public String getTestName() { - return "Exposure Compensation Test: \n"; - } - - @Override - public String getDebugText() { - return mDebugText; - } - - private native long createExposureCompensationTest(int outputHeight, int outputWidth); - - private native void createExposureCompensationClass(long bufferAddress, long handlerAddress, - long checkerCenterAddress, long checkerAadiusAddress, float mExposureLevel); - - private native String processExposureCompensationTest(long handlerAddress); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/MeteringTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/MeteringTest.java deleted file mode 100644 index 9ff559f..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/MeteringTest.java +++ /dev/null
@@ -1,685 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.ImageFormat; -import android.graphics.Rect; -import android.hardware.Camera; -import android.hardware.Camera.Area; -import android.util.Log; -import android.widget.ImageView; - -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Implements a test to verify whether the camera metering system works as - * described in the API. - * - * The test consists two sub-categories. The first one has tests with only - * one metering area defined. The second one has tests with two metering areas - * defined. For each single sub-test, we use a random number generator to - * decide where to put some of the metering areas to and how much weight should - * be assigned to each area. For different tests, we use different ways to - * define other metering areas and their weight, in order to cover all possible - * fail cases. The metering areas are contrained to the grey squares in the - * bottom of the color checker. - */ -public class MeteringTest extends CameraTests { - - private static final String TAG = "MeteringTest"; - - /** A long wait.*/ - private static final int LONG_SLEEP = 4000; - /** Debug result in text. */ - private String mDebugText; - /** Thread lock. */ - private final Object mProcessingImage = new Object(); - /** Memory address of the native test handler. */ - private long mTestHandler; - /** The maximum number of metering area the device supports. */ - private int mMaxNumMeteringArea; - /** The metering areas. */ - private List<Camera.Area> mGreyAreas; - /** The coordinates of the grey squares on the color checker. */ - private int[] mGreyCoordinates = new int[24]; - /** Random number generator. */ - private final Random mRandomGenerator = new Random(); - /** Reference comparison result for tests. */ - private ArrayList<Boolean> mReferenceCompareResults; - /** Number of tests in the same instance. */ - private int mTestCount; - /** Reference test logs. */ - private ArrayList<String> mReferenceLogs; - /** Test result to show. */ - private int[] mTestResults; - /** Number of tests. */ - private int mNumTests; - /** Camera Parameters. */ - private Camera.Parameters mParams; - /** Singleton test instance. */ - private static MeteringTest singletonTest = null; - - /** Constructs a <code>MeteringTest</code> instance with the given - * camera pointer. - */ - private MeteringTest() { - super(); - } - - public void updateCamera() { - // Looks up how many metering area the device supports. - mParams = mTestCamera.getParameters(); - mMaxNumMeteringArea = mParams.getMaxNumMeteringAreas(); - Log.v(TAG, String.format("Maximum number if metering area is %d", mMaxNumMeteringArea)); - if (mMaxNumMeteringArea == 0) { - mDebugText = "Custom Metering not supported!"; - Log.v(TAG, "Custom Metering not supported"); - } - } - - public static synchronized MeteringTest getSingletonTest() { - if (singletonTest == null) { - Log.v(TAG, "Creating a new MeteringTest instance"); - singletonTest = new MeteringTest(); - singletonTest.initializeTest(); - } - return singletonTest; - } - - private void initializeTest() { - // Creates a native metering test handler. - mTestHandler = createMeteringTest(); - mDebugText = new String(); - mReferenceCompareResults = new ArrayList<Boolean>(); - mReferenceLogs = new ArrayList<String>(); - mNumTests = 3; - mTestResults = new int[mNumTests]; - for (int i = 0; i < mNumTests; ++i) { - mTestResults[i] = CameraTests.CAMERA_TEST_NOT_RUN; - } - } - - /** - * Runs the metering test instance. - */ - @Override - public synchronized void run(int index) { - if (index == 0) { - run(1); - run(2); - return; - } - Log.v(TAG, "MeteringTest thread started!"); - - // Finds the coordinates of the grey squares on the color checker. - // The coordinate system has (-1000, -1000) on the upper left corner. - // And (1000, 1000) on the bottom right corner. - findGreyCoordinates(mGreyCoordinates, getCheckerCenter(), getCheckerRadius()); - - if (mMaxNumMeteringArea > 0) { - mTestCount = 0; - // Runs the metering tests category by category. - switch (index) { - case 1: - runOneAreaTest(); - break; - case 2: - if (mMaxNumMeteringArea > 1) { - runTwoAreasTest(); - } - break; - default: - break; - } - } - - mParams = mTestCamera.getParameters(); - mParams.setMeteringAreas(null); - mTestCamera.setParameters(mParams); - - boolean[] testCompareResults = new boolean[2 * mTestCount]; - - // Processes the image data taken so far and stores the test results. - processMeteringTest(mTestHandler, testCompareResults); - // Prepares debug output based on the test results. - prepareDebugText(testCompareResults, index); - - mReferenceCompareResults.clear(); - mReferenceLogs.clear(); - } - - /** - * Prepares the test results in HTML text string to show in the UI. - * - * If the test result is the same as the reference result, the text will be - * shown in green. Otherwise it would be shown as red. - * - * @param testCompareResults the array storing the comparison results from - * the data taken by the camera so far. - */ - private void prepareDebugText(boolean[] testCompareResults, int index) { - mDebugText = ""; - boolean groupTestPassed = true; - for (int i = 0; i < mTestCount; ++i) { - String testLog; - boolean testPassed = true; - testLog = mReferenceLogs.get(i); - mDebugText += (testLog + "<br/>"); - - if (testCompareResults[i * 2] == mReferenceCompareResults.get(i * 2)) { - mDebugText += String.format( - "Picture 1 equivalent to Picture 2 is %b \n", - testCompareResults[i * 2]); - } else { - mDebugText += String.format( - "Picture 1 equivalent to Picture 2 is %b \n", - testCompareResults[i * 2]); - testPassed = false; - } - - if (testCompareResults[i * 2 + 1] == mReferenceCompareResults.get(i * 2 + 1)) { - mDebugText += String.format( - "Picture 1 darker than Picture 2 is %b \n", - testCompareResults[i * 2 + 1]); - } else { - mDebugText += String.format( - "Picture 1 darker than Picture 2 is %b \n", - testCompareResults[i * 2 + 1]); - testPassed = false; - } - - if (testPassed) { - mDebugText += "Test passed! \n"; - } else { - mDebugText += "Test failed! \n"; - groupTestPassed = false; - } - Log.v(TAG, String.format("%s", mDebugText)); - } - - if (groupTestPassed) { - mTestResults[index] = CameraTests.CAMERA_TEST_SUCCESS; - } else { - mTestResults[index] = CameraTests.CAMERA_TEST_FAILURE; - } - - } - - /** - * Runs tests to check whether the metering functionalities work properly - * when one metering area is added. - */ - private void runOneAreaTest() { - int weight1; - int weight2; - int square1; - int square2; - - Log.v(TAG, "Running one area Test"); - - // Test case 1: Two images have the same metering area. Image 1 has - // a diffent weight than Image 2. The result images should be - // identical. - // Tests whether weight normalization works. - square1 = mRandomGenerator.nextInt(6); - weight1 = mRandomGenerator.nextInt(100) + 1; - runSingleTest(square1, square1, weight1); - - square2 = square1; - weight2 = mRandomGenerator.nextInt(100) + 901; - runSingleTest(square2, square2, weight2); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - Log.v(TAG, String.format("Running test for %d square with weights %d, %d", - square1, weight1, weight2)); - mReferenceLogs.add(String.format( - "Running test for %d 1x1 square with weights %d, %d", square1, weight1, weight2)); - ++mTestCount; - - // Test case 2: Two images have different metering areas. Image 1 has - // one of the grey squares as its metering area. Image 2 has a darker - // grey square as its metering area. The weights for both images are - // the same. Image 1 is expected to be darker than Image 2. - // Tests whether metering on uni-brightness patches work. - square1 = mRandomGenerator.nextInt(5); - weight1 = mRandomGenerator.nextInt(1000) + 1; - runSingleTest(square1, square1, weight1); - - square2 = mRandomGenerator.nextInt(6 - square1 - 1) + square1 + 1; - weight2 = weight1; - runSingleTest(square2, square2, weight2); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add(String.format( - "Running test for %d, %d 1x1 square with weight %d", square1, square2, weight1)); - ++mTestCount; - - // Test case 3: Two images have different metering areas. Image one has - // one of the grey squares as its metering area. Image 2 has a - // rectangle which contains Image 1's metering area and the neighboring - // darker grey square. The weights for both tests are the same. Image 1 - // is expected to be darker than Image 2. - // Tests whether metering on patches with different brightness works. - square1 = mRandomGenerator.nextInt(5); - weight1 = mRandomGenerator.nextInt(1000) + 1; - runSingleTest(square1, square1, weight1); - - square2 = square1; - weight2 = weight1; - runSingleTest(square2, square2 + 1, weight2); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add(String.format( - "Running test for %d 1x1, 1x2 square with weight %d", square1, weight1)); - ++mTestCount; - - // Test case 4: Two images have different metering areas. Image one has - // two neighboring grey squares as its metering area. Image 2 has two - // darker neighboring grey squares as its metering area. Weights are - // the same for both images. Image 1 is expected to be darker than - // Image 2. - // Tests whether metering on two mixed-brightness patches work. - square1 = mRandomGenerator.nextInt(4); - weight1 = mRandomGenerator.nextInt(1000) + 1; - runSingleTest(square1, square1 + 1, weight1); - - square2 = mRandomGenerator.nextInt(5 - square1 - 1) + square1 + 1; - weight2 = weight1; - runSingleTest(square2, square2 + 1, weight2); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add(String.format( - "Running test for %d, %d 1x2 square with weight %d", square1, square2, weight1)); - ++mTestCount; - - // Test case 5: Two images have different metering areas. Image one has - // three neighboring grey squares as its metering area. Image 2 has - // three darker neighboring grey squares as its metering area. Weights - // are the same. Image 1 is expected to be darker than Image 2. - // Tests whether metering on three mixed-brightness patches work. - square1 = mRandomGenerator.nextInt(3); - weight1 = mRandomGenerator.nextInt(1000) + 1; - runSingleTest(square1, square1 + 2, weight1); - - square2 = mRandomGenerator.nextInt(4 - square1 - 1) + square1 + 1; - weight2 = weight1; - runSingleTest(square2, square2 + 2, weight2); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add(String.format( - "Running test for %d, %d 1x3 square with weight %d", square1, square2, weight1)); - ++mTestCount; - } - - /** - * Runs metering tests to verify the functionalities when there are two - * areas set as the metering area. - */ - private void runTwoAreasTest() { - int[] weight1 = new int[2]; - int[] weight2 = new int[2]; - int[] square1Start = new int[2]; - int[] square2Start = new int[2]; - int[] square1End = new int[2]; - int[] square2End = new int[2]; - - Log.v(TAG, "Running two-area Test"); - - // Test case 1: Image 1 has two metering areas. They are two adjacent - // grey squares (each set as a metering area). The two areas have the - // same weight. Image 2 has one metering area, which is the combination - // of Image 1's two metering areas as a rectangle. The weight is the - // same as that of Image 1's individual area. Image 1 is expected to - // be equivalent to Image 2. - // Tests whether having seperating a metering area into two will yield - // the same result. - square1Start[0] = mRandomGenerator.nextInt(5); - square1End[0] = square1Start[0]; - weight1[0] = mRandomGenerator.nextInt(1000) + 1; - square1Start[1] = square1Start[0] + 1; - square1End[1] = square1Start[1]; - weight1[1] = weight1[0]; - runMultipleAreaTest(square1Start, square1End, weight1); - - square2Start[0] = square1Start[0]; - weight2[0] = weight1[0]; - runSingleTest(square2Start[0], square2Start[0] + 1, weight2[0]); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add(String.format( - "Running test for %d, %d 1x1 square with weight %d", - square1Start[0], square1Start[1], weight1[0])); - ++mTestCount; - - // Test case 2: Image 1 has two metering areas. They are two random - // grey squareson the color checker. The brighter square has a larger - // weight than the darker square. Image 2 has the same two metering - // areas as Image 1. The weights for both are equal to the weight of - // the darker square in Image 1, which is smaller than the weight of - // the brighter square in Image 1. Image 1 is expected to be darker - // than Image 2. - // Tests whether giving one of the two metering areas a different - // weight would change the image in the correct way. - square1Start[0] = mRandomGenerator.nextInt(4); - square1End[0] = square1Start[0]; - weight1[0] = mRandomGenerator.nextInt(100) + 901; - square1Start[1] = mRandomGenerator.nextInt(5 - square1Start[0] - 1) + square1Start[0] + 1; - square1End[1] = square1Start[1]; - weight1[1] = mRandomGenerator.nextInt(100) + 1; - runMultipleAreaTest(square1Start, square1End, weight1); - - square2Start[0] = square1Start[0]; - square2End[0] = square2Start[0]; - weight2[0] = weight1[1]; - square2Start[1] = square1Start[1]; - square2End[1] = square1End[1]; - weight2[1] = weight2[0]; - runMultipleAreaTest(square2Start, square2End, weight2); - mReferenceCompareResults.add(false); - mReferenceCompareResults.add(true); - mReferenceLogs.add(String.format( - "Running test for %d, %d 1x1 square with weight %d, %d", - square1Start[0], square1Start[1], weight1[0], weight2[1])); - ++mTestCount; - - // Test case 3: Image 1 has two metering areas. Both are set to the - // same random grey square on the color checker. The weight for both - // are the same. Image 2 has one meterig area, which is the same as - // Image 1's chosen grey square. The weight for it is the same as - // Image 1's weight for one metering area. Image 1 is expected to be - // equivalent to Image 2. - // Tests whether defining overlapping metering area works. - square1Start[0] = mRandomGenerator.nextInt(6); - square1End[0] = square1Start[0]; - weight1[0] = mRandomGenerator.nextInt(1000) + 1; - square1Start[1] = square1Start[0]; - square1End[1] = square1Start[1]; - weight1[1] = weight1[0]; - runMultipleAreaTest(square1Start, square1End, weight1); - - square2Start[0] = square1Start[0]; - square2End[0] = square2Start[0]; - weight2[0] = weight1[0]; - runSingleTest(square2Start[0], square2End[0], weight2[0]); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add(String.format( - "Running test for %d 1x1 square with weight %d,", square1Start[0], weight1[0])); - ++mTestCount; - - // Test case 4: Image 1 has two metering areas. The first one is a - // grey square on the color checker. The second one is a rectangle - // containing the first metering area's grey square and its neighboring - // darker square. The weights for both metering area are the same. - // Image 2 has two metering areas. The first one is the same grey - // square as Image 1's first metering area. The second one is the - // neighboring darker grey square. The weight for the brighter square - // is double the weight of Image 1's weights for each metering area. - // The weight for the Image 2's darker grey square is the same as - // Image 1's weight for each of its metering areas. Image 1 is expected - // to be equivalent to Image 2. - // Tests whether the weights for overlapping metering area add up. - square1Start[0] = mRandomGenerator.nextInt(2); - square1End[0] = square1Start[0]; - weight1[0] = mRandomGenerator.nextInt(500) + 1; - square1Start[1] = square1Start[0]; - square1End[1] = square1Start[1] + 1; - weight1[1] = weight1[0]; - runMultipleAreaTest(square1Start, square1End, weight1); - - square2Start[0] = square1Start[0]; - square2End[0] = square1End[0]; - weight2[0] = weight1[0] * 2; - square2Start[1] = square2Start[0] + 1; - square2End[1] = square2Start[1]; - weight2[1] = weight1[1]; - runMultipleAreaTest(square2Start, square2End, weight2); - mReferenceCompareResults.add(true); - mReferenceCompareResults.add(false); - mReferenceLogs.add(String.format( - "Running test for %d 1x2 1x1 and 1x2 square with weight %d,", - square1Start[0], weight1[0])); - ++mTestCount; - } - - /** - * Runs the metering test when multiple metering areas are defined. - * - * @param startIndex the array storing the index of the grey square where - * one metering area starts - * @param endIndex the array storing the index of the grey square where one - * metering area ends. - * @param weight the array storing the weight for each metering area. - */ - private void runMultipleAreaTest(int[] startIndex, int[] endIndex, int[] weight) { - int numAreas = startIndex.length; - mParams = mTestCamera.getParameters(); - List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>(); - - for (int i = 0; i < numAreas; ++i) { - meteringAreas.add(makeArea(startIndex[i], endIndex[i], weight[i])); - Log.v(TAG, String.format("Add metering area for %d, %d, %d", - startIndex[i], endIndex[i], weight[i])); - } - mParams.setMeteringAreas(meteringAreas); - mTestCamera.setParameters(mParams); - takePicture(); - } - - /** - * Runs the metering test when one metering area is defined. - * - * @param startIndex the index of the grey square where the metering area - * starts - * @param endIndex the index of the grey square where the metering area - * ends. - * @param weight the weight for the metering area. - */ - private void runSingleTest(int startIndex, int endIndex, int weight) { - mParams = mTestCamera.getParameters(); - List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>(); - - Log.v(TAG, String.format("Single test for %d, %d, %d", startIndex, endIndex, weight)); - meteringAreas.add(makeArea(startIndex, endIndex, weight)); - mParams.setMeteringAreas(meteringAreas); - mTestCamera.setParameters(mParams); - takePicture(); - } - - /** - * Takes picture with the camera instance linked to this test class. - */ - private void takePicture() { - // Waits for the metering to be stable - try{ - Log.v(TAG, "Waiting for metering"); - Thread.sleep(LONG_SLEEP); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e) {} - - mTestCamera.takePicture(null, null, null, mTestJpegListener); - - // Locks thread until picture is taken and ready for processing. - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - - mProcessingImage.wait(); - } catch (InterruptedException e) { - Log.v(TAG, "Callback wait fails!"); - } - } - } - - /** - * Constructs a <code>Camera.Area</code> object of the metering area. - * Given the start and end index of one metering area, it takes the upper - * left corner of the starting square and the bottom right corner of the - * end square to construct an Area. - * - * @param startIndex the index of the grey square where the metering area - * starts - * @param endIndex the index of the grey square where the metering area - * ends - * @param weight the weight of this metering area. - * - * @return a <code>Camera.Area</code> object which represents this metering - * area - */ - private Camera.Area makeArea(int startIndex, int endIndex, int weight) { - Rect areaRect = new Rect(mGreyCoordinates[startIndex * 4], - mGreyCoordinates[startIndex * 4 + 1], - mGreyCoordinates[endIndex * 4 + 2], - mGreyCoordinates[endIndex * 4 + 3]); - Camera.Area area = new Camera.Area(areaRect, weight); - - return area; - } - - @Override - public String getDebugText() { - return mDebugText; - } - - @Override - public String getResultText() { - return mDebugText; - } - - @Override - public String getTestName() { - return "Metering Test: \n"; - } - - @Override - public String getTestName(int index) { - switch (index) { - case 0: - return "Run all tests"; - case 1: - return "One metering area tests"; - case 2: - return "Multiple metering areas tests"; - default: - return ""; - } - } - - @Override - public int getResult(int index) { - return mTestResults[index]; - } - - @Override - public int getNumTests() { - return mNumTests; - } - - private Camera.PictureCallback mTestJpegListener = new Camera.PictureCallback() { - public void onPictureTaken(byte[] data, Camera mCamera) { - Log.v(TAG, "Shutter pressed down!"); - Bitmap inputImage; - try { - FileOutputStream outStream = new FileOutputStream( - String.format("/sdcard/metering%d.jpg", System.currentTimeMillis())); - outStream.write(data); - outStream.close(); - } catch (FileNotFoundException e) { - } catch (IOException e) {} - - // Decodes the input data of the camera. - inputImage = BitmapFactory.decodeByteArray(data, 0, data.length); - - // Records the memory address of the native image class instance. - long bufferAddress = findNative(inputImage); - Log.v(TAG, "findNative method finishes"); - - // Cleans up the memory taken by the bitmap. - inputImage.recycle(); - data = null; - inputImage = null; - System.gc(); - - // Add the image data to the native test handler. - createMeteringClass(bufferAddress, mTestHandler, - getCheckerCenter(), getCheckerRadius()); - mCamera.startPreview(); - - // Releases thread lock after the image is processed. - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - }; - - /** - * Finds the coordinates of the grey squares on the color checker. - * The coordinates are computed by using the checker center and radius. - * The coordinates are converted to a system with (-1000, -1000) in the - * upper left corner and (1000, 1000) in the bottom right corner. - * - * @param greyCoordinates the array to store the coordinates of the grey - * squares - * @param checkerCenterAddress the memory address pointing to the vector - * storing the color checker's centers. - * @param checkerRadiusAddress the memory address pointing to the vetor - * storing the color checker's radius. - */ - private native void findGreyCoordinates(int[] greyCoordinates, - long checkerCenterAddress, long checkerRadiusAddress); - - /** - * Creates the native metering test handler with no debug image. - * - * @return the memory address pointing to the native test handler instance - */ - private native long createMeteringTest(); - - /** - * Adds the data from the native image class instance to the native test - * handler. - * - * @param bufferAddress the meory address of the native image class - * @param handlerAddress the memory address of the native test handler - * @param checkerCenterAddress the memory address of the checker cneters - * @param checkerRadiusAddress the meory address of the checker radius - */ - private native void createMeteringClass(long bufferAddress, long handlerAddress, - long checkerCenterAddress, - long checkerRadiusAddress); - - /** - * Process the data stored in the native test handler and stores the - * comparison results. - * - * @param handlerAddress the memory address of the native test handler - * @param testCompareResults the boolean array to store the test comparison - * results - */ - private native void processMeteringTest(long handlerAddress, boolean[] testCompareResults); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/WhiteBalanceTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/WhiteBalanceTest.java deleted file mode 100644 index a4111eb..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/analyzer/WhiteBalanceTest.java +++ /dev/null
@@ -1,398 +0,0 @@ -/* - * Copyright (C) 2011 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.camera.analyzer; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.ImageFormat; -import android.hardware.Camera; -import android.util.Log; -import android.widget.ImageView; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import java.util.List; - -/** - * Implements a test to verify whether the correlated color temperatures (CTT) - * of the supported white balance modes are inside the range camera - * manufacturers generally agree on. - * - * The test assumes that the Daylight white balance mode has a CCT of 5200K, - * which is widely agreed in industry and academics. It then use this as a - * benchmark and compare images taken with other white balance settings. - * Using the pixel values of the grey squares on the color checker, the CCT - * of other white balance modes can be computed. The reference ranges were - * summarized with the help of online resources. For the Auto mode, the - * reference CCT is computed as the CCT that will keep the grey squares appear - * grey in the result image. - */ -public class WhiteBalanceTest extends CameraTests { - - private static final String TAG = "WhiteBalanceTest"; - - /** Current white balance mode. */ - private String mWhiteBalance; - /** Array to store the reference CCT's of each mode. */ - private int[][] mReferenceTemperature; - /** List of supported white balance mode on a device. */ - private List<String> mWhiteBalanceList; - /** The index of the white balance mode "Auto". */ - private int mAutoId; - - /** Debug results in text. */ - private String mDebugText; - /** Memory address of the native test handler instance. */ - private long mTestHandler; - /** Thread lock. */ - private final Object mProcessingImage = new Object(); - /** Test result to show. */ - private int[] mTestResults; - /** Number of test. */ - private int mNumTests; - /** Camera Parameters. */ - private Camera.Parameters mParams; - /** Singleton test instance. */ - private static WhiteBalanceTest singletonTest = null; - /** Boolean to check whehter daylight wb has been recorded. */ - private boolean mHasDaylight = false; - - /** - * Constructs a <code>WhiteBalanceTest</code> instance with a given - * Camera pointer. - */ - private WhiteBalanceTest() { - super(); - } - - public void updateCamera() { - mAutoId = 0; - mHasDaylight = false; - mParams = mTestCamera.getParameters(); - mWhiteBalanceList = mParams.getSupportedWhiteBalance(); - mNumTests = mWhiteBalanceList.size() + 1; - mTestResults = new int[mNumTests]; - for (int i = 0; i < mNumTests; ++i) { - mTestResults[i] = CameraTests.CAMERA_TEST_NOT_RUN; - } - - if (mWhiteBalanceList != null) { - mReferenceTemperature = new int[mWhiteBalanceList.size()][2]; - - // Sets the reference CCT of the supported white balance modes - for (int i = 0; i < mWhiteBalanceList.size(); i++) { - setReferenceTemperature(i, mWhiteBalanceList.get(i)); - if (mWhiteBalanceList.get(i).equals("auto")) { - mAutoId = i; - } - } - } - } - - public static synchronized WhiteBalanceTest getSingletonTest() { - if (singletonTest == null) { - Log.v(TAG, "Creating a new WhiteBalanceTest instance"); - singletonTest = new WhiteBalanceTest(); - singletonTest.initializeTest(); - } - return singletonTest; - } - - private void initializeTest() { - mDebugText = new String(); - // Creates a native white balance test handler. - // mTestHandler stores the memory address of this instance. - mTestHandler = createWhiteBalanceTest(); - } - - private void initializeWhiteBalanceTest() { - mWhiteBalance = "daylight"; - takePicture(mWhiteBalance); - int colorTemperature = processWhiteBalanceTest(mTestHandler); - - setReferenceTemperature(mAutoId, colorTemperature); - mHasDaylight = true; - } - - private void takePicture(String whiteBalance) { - mParams.setWhiteBalance(whiteBalance); - mTestCamera.setParameters(mParams); - - try{ - Log.v(TAG, "Waiting for white balance to adjust"); - Thread.sleep(4000); - Log.v(TAG, "END Waiting"); - } catch (InterruptedException e) {} - - mTestCamera.takePicture(null, null, null, mTestJpegListener); - - // Thread locks until image capture is done - synchronized (mProcessingImage) { - try{ - Log.v(TAG, "Start waiting for Image"); - mProcessingImage.wait(); - } catch (InterruptedException e) { - Log.v(TAG, "Callback wait fails!"); - } - } - } - - /** - * Runs the white balance camera test instance. - */ - @Override - public synchronized void run(int index) { - Log.v(TAG, "WhiteBalanceTest thread started!"); - - if (!mHasDaylight) { - initializeWhiteBalanceTest(); - } - - if (index != 0) { - // Retrieves the list of supported white balance mode. - mParams = mTestCamera.getParameters(); - - int i = index - 1; - mWhiteBalance = mWhiteBalanceList.get(i); - - Log.v(TAG, "Current white balance is " + mWhiteBalance); - - takePicture(mWhiteBalance); - - // Processes the white balance test data in the native code. - // Returns an array of CCT of each white balance modes, given the CCT - // of the "Daylight" mode is 5200K. - int colorTemperature = 0; - - Log.v(TAG, "Finished taking picture, ready to process"); - colorTemperature = processWhiteBalanceTest(mTestHandler); - - // Records the index of the "Auto" white balance mode - if (mWhiteBalance.equals("daylight")) { - setReferenceTemperature(mAutoId, colorTemperature); - prepareDebugText(5200, index); - // Computes the reference CCT range of the "Auto" mode. Assuming that - // all grey squares on the color checker should be imaged as grey under - // a CCT, this CCT is used as a middle point to provide a range. - //setReferenceTemperature(mAutoId, colorTemperature[mWhiteBalanceList.size()]); - } else { - // Prepares the debug output. - prepareDebugText(colorTemperature, index); - } - } else { - for (int i = 0; i < mWhiteBalanceList.size(); i++) { - run(i + 1); - } - } - - mParams.setWhiteBalance("auto"); - mTestCamera.setParameters(mParams); - } - - /** - * Prepares the debug results in HTML text. For each white balance mode, - * the CCT will be printed in green if it is in the reference range and - * red otherwise. The reference CCT range is also printed below, with - * green meaning the CCT range is satisfied and red otherwise. - * - * @param colorTemperature the CCT of the supported white balance modes - */ - private void prepareDebugText(int colorTemperature, int index) { - mDebugText += String.format("CCT Ref is %d, %d, and CCT is %d", - mReferenceTemperature[index - 1][0], - mReferenceTemperature[index - 1][1], - colorTemperature); - Log.v(TAG, String.format("CCT Ref is %d, %d, and CCT is %d", - mReferenceTemperature[index - 1][0], - mReferenceTemperature[index - 1][1], - colorTemperature)); - if ((colorTemperature >= mReferenceTemperature[index - 1][0]) && - (colorTemperature <= mReferenceTemperature[index - 1][1])) { - mTestResults[index] = CameraTests.CAMERA_TEST_SUCCESS; - } else { - mTestResults[index] = CameraTests.CAMERA_TEST_FAILURE; - } - - } - - @Override - public String getDebugText() { - return mDebugText; - } - - @Override - public String getResultText() { - return mDebugText; - } - - @Override - public String getTestName() { - return "White Balance Test: \n"; - } - - @Override - public String getTestName(int index) { - if (index != 0){ - return String.format("%s mode test", mWhiteBalanceList.get(index - 1)); - } else { - return "Run all tests"; - } - } - - @Override - public int getResult(int index) { - return mTestResults[index]; - } - - @Override - public int getNumTests() { - return mNumTests; - } - - /** - * Sets the reference temperatures for the white balance modes of - * incandescent, fluorescent, warm-fluorescent, daylight, cloudy, shade - * and twilight. These are the currently supported White balance mode - * listed on the Android camera API. - * - * The reference range are summarized based on the published settings of - * Canon, Nikon and the references from Wikipedia on color temperature. - * - * @param i the index of the current white balance mode - * @param referenceWhiteBalance the name of the white balance mode. - */ - private void setReferenceTemperature(int i, String referenceWhiteBalance) { - if (referenceWhiteBalance.equals("incandescent")) { - mReferenceTemperature[i][0] = 2500; - mReferenceTemperature[i][1] = 3500; - } else if (referenceWhiteBalance.equals("fluorescent")) { - mReferenceTemperature[i][0] = 3000; - mReferenceTemperature[i][1] = 6500; - } else if (referenceWhiteBalance.equals("warm-fluorescent")) { - mReferenceTemperature[i][0] = 2500; - mReferenceTemperature[i][1] = 3000; - } else if (referenceWhiteBalance.equals("daylight")) { - mReferenceTemperature[i][0] = 5000; - mReferenceTemperature[i][1] = 5400; - } else if (referenceWhiteBalance.equals("cloudy-daylight")) { - mReferenceTemperature[i][0] = 5500; - mReferenceTemperature[i][1] = 7500; - } else if (referenceWhiteBalance.equals("shade")) { - mReferenceTemperature[i][0] = 6800; - mReferenceTemperature[i][1] = 8000; - } else if (referenceWhiteBalance.equals("twilight")) { - mReferenceTemperature[i][0] = 10000; - mReferenceTemperature[i][1] = 14000; - } - } - - /** Sets a reference range of CCT based on a given middle point CCT. - * The rerence range is from -10% of the CCT value to +10%. - * - * @param i the index of the current white balance mode - * @param t the middle point CCT. - */ - private void setReferenceTemperature(int i, int t) { - mReferenceTemperature[i][0] = (int)((double)t * 0.9); - mReferenceTemperature[i][1] = (int)((double)t * 1.1); - } - - private Camera.PictureCallback mTestJpegListener = new Camera.PictureCallback() { - public void onPictureTaken(byte[] data, Camera mCamera) { - Log.v(TAG, "Shutter pressed down!"); - Bitmap inputImage; - try { - FileOutputStream outStream = new FileOutputStream( - String.format("/sdcard/wb%d.jpg", System.currentTimeMillis())); - outStream.write(data); - outStream.close(); - } catch (FileNotFoundException e) { - } catch (IOException e) {} - // Decodes the camera data to Bitmap and creates a native image - // class with the Bitmap. - inputImage = BitmapFactory.decodeByteArray(data, 0, data.length); - long bufferAddress = findNative(inputImage); - Log.v(TAG, "findNative method finishes"); - - // Cleans up the Bitmap memory space. - inputImage.recycle(); - data = null; - inputImage = null; - System.gc(); - - // Adds the data from the current image base class to the native - // white balance test handler. - createWhiteBalanceClass(bufferAddress, mTestHandler, - getCheckerCenter(), getCheckerRadius(), mWhiteBalance); - - mCamera.startPreview(); - - // Notifies the thread lock that the image capture is finished - synchronized (mProcessingImage) { - mProcessingImage.notifyAll(); - } - } - }; - - /** - * Creates a native white balance test handler. - * - * @return the memory address of the test handler - */ - private native long createWhiteBalanceTest(); - - /** - * Adds the data of interest from the image class pointed by - * <code>bufferAddress</code> to the handler class pointed by - * <code>handlerAddress</code> by using the color checker coordinates. - * Also sets the white balance of this test. - * - * @param bufferAddress the memory address of the native image class - * containing the current camera captured image - * @param handlerAddress the memory address of the native white balance - * test handler instance - * @param checkerCenterAddress the memory address of the color checker - * center coordinates - * @param checkerRadiusAddress the memory address of the color checker - * radius - * @param whiteBalance the white balance mode used for shooting the image - */ - private native void createWhiteBalanceClass(long bufferAddress, long handlerAddress, - long checkerCenterAddress, - long checkerRadiusAddress, - String whiteBalance); - - /** - * Processes the white balance test in the native code. This is executed - * after the images are taken with all possible white balance modes. It - * uses the "Daylight" white balance mode as reference and computes the - * CCT of other white balance modes. - * - * @param handlerAddress the memory address of the native white balance - * test handler instance. - * @param colorTemperature the array to store the computed CCT of all white - * balance modes. - */ - private native int processWhiteBalanceTest(long handlerAddress); - - private native int getAutoTemperature(long handlerAddress); - - static { - System.loadLibrary("cameraanalyzer"); - } -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/flashlight/CameraFlashlightActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/flashlight/CameraFlashlightActivity.java new file mode 100644 index 0000000..4d37b3ee --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/flashlight/CameraFlashlightActivity.java
@@ -0,0 +1,275 @@ +/* + * Copyright 2015 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.camera.flashlight; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.content.Context; +import android.hardware.camera2.CameraManager; +import android.hardware.camera2.CameraCharacteristics; +import android.os.Bundle; +import android.os.Handler; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import java.util.HashSet; +import java.util.HashMap; + +/** + * This test checks the flashlight functionality by turning on and off the flashlight. After it + * turns on or off the flashlight, it asks for user input to verify the flashlight status. The + * test will pass when the user input is correct for all camera devices with a flash unit. + */ +public class CameraFlashlightActivity extends PassFailButtons.Activity { + + private static final String TAG = "CameraFlashlight"; + + private CameraManager mCameraManager; + private TestState mTestState; + private final HashSet<String> mPendingCameraIds = new HashSet<>(); + private String mCurrentCameraId; + + private Button mInstructionButton; + private Button mOnButton; + private Button mOffButton; + private TextView mInstructionTextView; + private final HashSet<View> mAllButtons = new HashSet<>(); + // TestState -> enabled buttons + private final HashMap<TestState, HashSet<View>> mStateButtonsMap = new HashMap<>(); + + private enum TestState { + NOT_STARTED, + TESTING_ON, + WAITING_ON_CALLBACK_ON, + RESPONDED_ON_CORRECTLY, + WAITING_ON_CALLBACK_OFF, + TESTING_OFF, + RESPONDED_OFF_CORRECTLY, + ALL_PASSED, + FAILED + } + + private final View.OnClickListener mInstructionButtonListener = new View.OnClickListener() { + @Override + public void onClick(View v) { + switch (mTestState) { + case NOT_STARTED: + // Start testing turning on the first camera's flashlight. + // Fall through. + case RESPONDED_OFF_CORRECTLY: + // Current camera passed. Start testing turning on next camera's flashlight. + if (mPendingCameraIds.size() == 0) { + // Passed + mTestState = TestState.ALL_PASSED; + updateButtonsAndInstructionLocked(); + return; + } + + mCurrentCameraId = (String)mPendingCameraIds.toArray()[0]; + mPendingCameraIds.remove(mCurrentCameraId); + + try { + mCameraManager.setTorchMode(mCurrentCameraId, true); + mTestState = TestState.WAITING_ON_CALLBACK_ON; + } catch (Exception e) { + e.printStackTrace(); + mTestState = TestState.FAILED; + } + break; + + case RESPONDED_ON_CORRECTLY: + // Flashlight is on and user responded correctly. + // Turning off the flashlight. + try { + mCameraManager.setTorchMode(mCurrentCameraId, false); + mTestState = TestState.WAITING_ON_CALLBACK_OFF; + } catch (Exception e) { + e.printStackTrace(); + mTestState = TestState.FAILED; + } + break; + + case FAILED: + // The test failed, report failure. + if (mCurrentCameraId != null) { + try { + mCameraManager.setTorchMode(mCurrentCameraId, false); + } catch (Exception e) { + e.printStackTrace(); + Log.e(TAG, "Test failed but cannot turn off the torch"); + } + } + setTestResultAndFinish(false); + break; + + case ALL_PASSED: + // The test passed, report pass. + setTestResultAndFinish(true); + break; + } + + updateButtonsAndInstructionLocked(); + } + }; + + private final View.OnClickListener mOnButtonListener = new View.OnClickListener() { + @Override + public void onClick(View v) { + // Check if user responded correctly. + if (mTestState == TestState.TESTING_ON) { + mTestState = TestState.RESPONDED_ON_CORRECTLY; + } else { + mTestState = TestState.FAILED; + } + updateButtonsAndInstructionLocked(); + } + }; + + private final View.OnClickListener mOffButtonListener = new View.OnClickListener() { + @Override + public void onClick(View v) { + // Check if user responded correctly. + if (mTestState == TestState.TESTING_OFF) { + mTestState = TestState.RESPONDED_OFF_CORRECTLY; + } else { + mTestState = TestState.FAILED; + } + updateButtonsAndInstructionLocked(); + } + }; + + private final CameraManager.TorchCallback mTorchCallback = new CameraManager.TorchCallback() { + @Override + public void onTorchModeChanged(String cameraId, boolean enabled) { + if (!cameraId.equals(mCurrentCameraId)) { + return; + } + + // Move to next state after receiving the expected callback. + if (mTestState == TestState.WAITING_ON_CALLBACK_ON && enabled) { + mTestState = TestState.TESTING_ON; + } else if (mTestState == TestState.WAITING_ON_CALLBACK_OFF && !enabled) { + mTestState = TestState.TESTING_OFF; + } + updateButtonsAndInstructionLocked(); + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // initialize state -> buttons map + for (TestState state : TestState.values()) { + mStateButtonsMap.put(state, new HashSet<View>()); + } + + mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); + + try { + String[] cameraIds = mCameraManager.getCameraIdList(); + for (String id : cameraIds) { + CameraCharacteristics info = mCameraManager.getCameraCharacteristics(id); + if (info.get(CameraCharacteristics.FLASH_INFO_AVAILABLE).booleanValue() == + true) { + mPendingCameraIds.add(id); + } + } + mCameraManager.registerTorchCallback(mTorchCallback, new Handler()); + } catch (Exception e) { + e.printStackTrace(); + mTestState = TestState.FAILED; + updateButtonsAndInstructionLocked(); + return; + } + + // Setup the UI. + setContentView(R.layout.camera_flashlight); + setPassFailButtonClickListeners(); + setInfoResources(R.string.camera_flashlight_test, R.string.camera_flashlight_info, -1); + + mInstructionTextView = (TextView) findViewById(R.id.flash_instruction_text); + + // Get the buttons and attach the listener. + mInstructionButton = (Button) findViewById(R.id.flash_instruction_button); + mInstructionButton.setOnClickListener(mInstructionButtonListener); + mStateButtonsMap.get(TestState.NOT_STARTED).add(mInstructionButton); + mStateButtonsMap.get(TestState.RESPONDED_ON_CORRECTLY).add(mInstructionButton); + mStateButtonsMap.get(TestState.RESPONDED_OFF_CORRECTLY).add(mInstructionButton); + mStateButtonsMap.get(TestState.ALL_PASSED).add(mInstructionButton); + mStateButtonsMap.get(TestState.FAILED).add(mInstructionButton); + mAllButtons.add(mInstructionButton); + + mOnButton = (Button) findViewById(R.id.flash_on_button); + mOnButton.setOnClickListener(mOnButtonListener); + mStateButtonsMap.get(TestState.TESTING_ON).add(mOnButton); + mStateButtonsMap.get(TestState.TESTING_OFF).add(mOnButton); + mAllButtons.add(mOnButton); + + mOffButton = (Button) findViewById(R.id.flash_off_button); + mOffButton.setOnClickListener(mOffButtonListener); + mStateButtonsMap.get(TestState.TESTING_ON).add(mOffButton); + mStateButtonsMap.get(TestState.TESTING_OFF).add(mOffButton); + mAllButtons.add(mOffButton); + + View passButton = getPassButton(); + mStateButtonsMap.get(TestState.ALL_PASSED).add(passButton); + mAllButtons.add(passButton); + + mTestState = TestState.NOT_STARTED; + updateButtonsAndInstructionLocked(); + } + + + private void updateButtonsAndInstructionLocked() { + for (View v : mAllButtons) { + v.setEnabled(false); + } + + // Only enable the buttons for this state. + HashSet<View> views = mStateButtonsMap.get(mTestState); + for (View v : views) { + v.setEnabled(true); + } + + switch (mTestState) { + case TESTING_ON: + case TESTING_OFF: + mInstructionTextView.setText(String.format( + getString(R.string.camera_flashlight_question_text), mCurrentCameraId)); + break; + case RESPONDED_ON_CORRECTLY: + case RESPONDED_OFF_CORRECTLY: + mInstructionTextView.setText(R.string.camera_flashlight_next_text); + mInstructionButton.setText(R.string.camera_flashlight_next_button); + break; + case FAILED: + mInstructionTextView.setText(R.string.camera_flashlight_failed_text); + mInstructionButton.setText(R.string.camera_flashlight_done_button); + break; + case ALL_PASSED: + mInstructionTextView.setText(R.string.camera_flashlight_passed_text); + mInstructionButton.setText(R.string.camera_flashlight_done_button); + break; + default: + break; + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsSerializer.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsSerializer.java index cf8365a..9abfa9a 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsSerializer.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsSerializer.java
@@ -116,9 +116,15 @@ faceObj.put("bounds", serializeRect(face.getBounds())); faceObj.put("score", face.getScore()); faceObj.put("id", face.getId()); - faceObj.put("leftEye", serializePoint(face.getLeftEyePosition())); - faceObj.put("rightEye", serializePoint(face.getRightEyePosition())); - faceObj.put("mouth", serializePoint(face.getMouthPosition())); + if (face.getLeftEyePosition() != null) { + faceObj.put("leftEye", serializePoint(face.getLeftEyePosition())); + } + if (face.getRightEyePosition() != null) { + faceObj.put("rightEye", serializePoint(face.getRightEyePosition())); + } + if (face.getMouthPosition() != null) { + faceObj.put("mouth", serializePoint(face.getMouthPosition())); + } return faceObj; } @@ -145,6 +151,19 @@ cfgArray.put(obj); } } + sizes = map.getHighResolutionOutputSizes(fmts[fi]); + if (sizes != null) { + for (int si = 0; si < Array.getLength(sizes); si++) { + JSONObject obj = new JSONObject(); + obj.put("format", fmts[fi]); + obj.put("width",sizes[si].getWidth()); + obj.put("height", sizes[si].getHeight()); + obj.put("input", false); + obj.put("minFrameDuration", + map.getOutputMinFrameDuration(fmts[fi],sizes[si])); + cfgArray.put(obj); + } + } } } mapObj.put("availableStreamConfigurations", cfgArray);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java index ce10535..e3ff74b 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
@@ -30,6 +30,7 @@ import android.hardware.camera2.CaptureResult; import android.hardware.camera2.DngCreator; import android.hardware.camera2.TotalCaptureResult; +import android.hardware.camera2.params.InputConfiguration; import android.hardware.camera2.params.MeteringRectangle; import android.hardware.Sensor; import android.hardware.SensorEvent; @@ -37,12 +38,15 @@ import android.hardware.SensorManager; import android.media.Image; import android.media.ImageReader; +import android.media.ImageWriter; +import android.media.Image.Plane; import android.net.Uri; import android.os.ConditionVariable; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Message; +import android.os.SystemClock; import android.os.Vibrator; import android.util.Log; import android.util.Rational; @@ -54,6 +58,8 @@ import com.android.ex.camera2.blocking.BlockingStateCallback; import com.android.ex.camera2.blocking.BlockingSessionCallback; +import com.android.cts.verifier.camera.its.StatsImage; + import org.json.JSONArray; import org.json.JSONObject; @@ -67,8 +73,9 @@ import java.math.BigInteger; import java.net.ServerSocket; import java.net.Socket; -import java.net.SocketTimeoutException; import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.ArrayList; @@ -78,6 +85,7 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -121,7 +129,8 @@ private BlockingStateCallback mCameraListener = null; private CameraDevice mCamera = null; private CameraCaptureSession mSession = null; - private ImageReader[] mCaptureReaders = null; + private ImageReader[] mOutputImageReaders = null; + private ImageReader mInputImageReader = null; private CameraCharacteristics mCameraCharacteristics = null; private Vibrator mVibrator = null; @@ -146,10 +155,14 @@ private AtomicInteger mCountCallbacksRemaining = new AtomicInteger(); private AtomicInteger mCountRawOrDng = new AtomicInteger(); private AtomicInteger mCountRaw10 = new AtomicInteger(); + private AtomicInteger mCountRaw12 = new AtomicInteger(); private AtomicInteger mCountJpg = new AtomicInteger(); private AtomicInteger mCountYuv = new AtomicInteger(); private AtomicInteger mCountCapRes = new AtomicInteger(); private boolean mCaptureRawIsDng; + private boolean mCaptureRawIsStats; + private int mCaptureStatsGridWidth; + private int mCaptureStatsGridHeight; private CaptureResult mCaptureResults[] = null; private volatile ConditionVariable mInterlock3A = new ConditionVariable(true); @@ -400,7 +413,7 @@ continue; } if (b.hasArray()) { - mOpenSocket.getOutputStream().write(b.array()); + mOpenSocket.getOutputStream().write(b.array(), 0, b.capacity()); } else { byte[] barray = new byte[b.capacity()]; b.get(barray); @@ -493,6 +506,7 @@ mSocketWriteQueue.clear(); mOpenSocket.close(); mOpenSocket = null; + mSocketWriteRunnable.setOpenSocket(null); Logt.i(TAG, "Socket disconnected"); } } catch (java.io.IOException e) { @@ -505,9 +519,12 @@ Logt.i(TAG, "Socket server loop exited"); mThreadExitFlag = true; try { - if (mOpenSocket != null) { - mOpenSocket.close(); - mOpenSocket = null; + synchronized(mSocketWriteDrainLock) { + if (mOpenSocket != null) { + mOpenSocket.close(); + mOpenSocket = null; + mSocketWriteRunnable.setOpenSocket(null); + } } } catch (java.io.IOException e) { Logt.w(TAG, "Exception closing socket"); @@ -546,6 +563,8 @@ doVibrate(cmdObj); } else if ("getCameraIds".equals(cmdObj.getString("cmdName"))) { doGetCameraIds(); + } else if ("doReprocessCapture".equals(cmdObj.getString("cmdName"))) { + doReprocessCapture(cmdObj); } else { throw new ItsException("Unknown command: " + cmd); } @@ -655,9 +674,20 @@ jsonSurface.put("height", readers[i].getHeight()); int format = readers[i].getImageFormat(); if (format == ImageFormat.RAW_SENSOR) { - jsonSurface.put("format", "raw"); + if (mCaptureRawIsStats) { + jsonSurface.put("format", "rawStats"); + jsonSurface.put("width", readers[i].getWidth()/mCaptureStatsGridWidth); + jsonSurface.put("height", + readers[i].getHeight()/mCaptureStatsGridHeight); + } else if (mCaptureRawIsDng) { + jsonSurface.put("format", "dng"); + } else { + jsonSurface.put("format", "raw"); + } } else if (format == ImageFormat.RAW10) { jsonSurface.put("format", "raw10"); + } else if (format == ImageFormat.RAW12) { + jsonSurface.put("format", "raw12"); } else if (format == ImageFormat.JPEG) { jsonSurface.put("format", "jpeg"); } else if (format == ImageFormat.YUV_420_888) { @@ -763,18 +793,42 @@ } } - private void prepareCaptureReader(int[] widths, int[] heights, int formats[], int numSurfaces) { - if (mCaptureReaders != null) { - for (int i = 0; i < mCaptureReaders.length; i++) { - if (mCaptureReaders[i] != null) { - mCaptureReaders[i].close(); + private void prepareImageReaders(Size[] outputSizes, int[] outputFormats, Size inputSize, + int inputFormat, int maxInputBuffers) { + closeImageReaders(); + mOutputImageReaders = new ImageReader[outputSizes.length]; + for (int i = 0; i < outputSizes.length; i++) { + // Check if the output image reader can be shared with the input image reader. + if (outputSizes[i].equals(inputSize) && outputFormats[i] == inputFormat) { + mOutputImageReaders[i] = ImageReader.newInstance(outputSizes[i].getWidth(), + outputSizes[i].getHeight(), outputFormats[i], + MAX_CONCURRENT_READER_BUFFERS + maxInputBuffers); + mInputImageReader = mOutputImageReaders[i]; + } else { + mOutputImageReaders[i] = ImageReader.newInstance(outputSizes[i].getWidth(), + outputSizes[i].getHeight(), outputFormats[i], + MAX_CONCURRENT_READER_BUFFERS); + } + } + + if (inputSize != null && mInputImageReader == null) { + mInputImageReader = ImageReader.newInstance(inputSize.getWidth(), inputSize.getHeight(), + inputFormat, maxInputBuffers); + } + } + + private void closeImageReaders() { + if (mOutputImageReaders != null) { + for (int i = 0; i < mOutputImageReaders.length; i++) { + if (mOutputImageReaders[i] != null) { + mOutputImageReaders[i].close(); + mOutputImageReaders[i] = null; } } } - mCaptureReaders = new ImageReader[numSurfaces]; - for (int i = 0; i < numSurfaces; i++) { - mCaptureReaders[i] = ImageReader.newInstance(widths[i], heights[i], formats[i], - MAX_CONCURRENT_READER_BUFFERS); + if (mInputImageReader != null) { + mInputImageReader.close(); + mInputImageReader = null; } } @@ -785,18 +839,17 @@ // 3A happens on full-res frames. Size sizes[] = ItsUtils.getYuvOutputSizes(mCameraCharacteristics); - int widths[] = new int[1]; - int heights[] = new int[1]; - int formats[] = new int[1]; - widths[0] = sizes[0].getWidth(); - heights[0] = sizes[0].getHeight(); - formats[0] = ImageFormat.YUV_420_888; - int width = widths[0]; - int height = heights[0]; + int outputFormats[] = new int[1]; + outputFormats[0] = ImageFormat.YUV_420_888; + Size[] outputSizes = new Size[1]; + outputSizes[0] = sizes[0]; + int width = outputSizes[0].getWidth(); + int height = outputSizes[0].getHeight(); - prepareCaptureReader(widths, heights, formats, 1); + prepareImageReaders(outputSizes, outputFormats, /*inputSize*/null, /*inputFormat*/0, + /*maxInputBuffers*/0); List<Surface> outputSurfaces = new ArrayList<Surface>(1); - outputSurfaces.add(mCaptureReaders[0].getSurface()); + outputSurfaces.add(mOutputImageReaders[0].getSurface()); BlockingSessionCallback sessionListener = new BlockingSessionCallback(); mCamera.createCaptureSession(outputSurfaces, sessionListener, mCameraHandler); mSession = sessionListener.waitAndGetSession(TIMEOUT_IDLE_MS); @@ -804,7 +857,7 @@ // Add a listener that just recycles buffers; they aren't saved anywhere. ImageReader.OnImageAvailableListener readerListener = createAvailableListenerDropper(mCaptureCallback); - mCaptureReaders[0].setOnImageAvailableListener(readerListener, mSaveHandlers[0]); + mOutputImageReaders[0].setOnImageAvailableListener(readerListener, mSaveHandlers[0]); // Get the user-specified regions for AE, AWB, AF. // Note that the user specifies normalized [x,y,w,h], which is converted below @@ -950,7 +1003,7 @@ triggeredAF = true; } - req.addTarget(mCaptureReaders[0].getSurface()); + req.addTarget(mOutputImageReaders[0].getSurface()); mIssuedRequest3A = true; mSession.capture(req.build(), mCaptureResultListener, mResultHandler); @@ -988,88 +1041,131 @@ } } + /** + * Parse jsonOutputSpecs to get output surface sizes and formats. Create input and output + * image readers for the parsed output surface sizes, output formats, and the given input + * size and format. + */ + private void prepareImageReadersWithOutputSpecs(JSONArray jsonOutputSpecs, Size inputSize, + int inputFormat, int maxInputBuffers) throws ItsException { + Size outputSizes[]; + int outputFormats[]; + int numSurfaces = 0; + + if (jsonOutputSpecs != null) { + try { + numSurfaces = jsonOutputSpecs.length(); + if (numSurfaces > MAX_NUM_OUTPUT_SURFACES) { + throw new ItsException("Too many output surfaces"); + } + + outputSizes = new Size[numSurfaces]; + outputFormats = new int[numSurfaces]; + for (int i = 0; i < numSurfaces; i++) { + // Get the specified surface. + JSONObject surfaceObj = jsonOutputSpecs.getJSONObject(i); + String sformat = surfaceObj.optString("format"); + Size sizes[]; + if ("yuv".equals(sformat) || "".equals(sformat)) { + // Default to YUV if no format is specified. + outputFormats[i] = ImageFormat.YUV_420_888; + sizes = ItsUtils.getYuvOutputSizes(mCameraCharacteristics); + } else if ("jpg".equals(sformat) || "jpeg".equals(sformat)) { + outputFormats[i] = ImageFormat.JPEG; + sizes = ItsUtils.getJpegOutputSizes(mCameraCharacteristics); + } else if ("raw".equals(sformat)) { + outputFormats[i] = ImageFormat.RAW_SENSOR; + sizes = ItsUtils.getRaw16OutputSizes(mCameraCharacteristics); + } else if ("raw10".equals(sformat)) { + outputFormats[i] = ImageFormat.RAW10; + sizes = ItsUtils.getRaw10OutputSizes(mCameraCharacteristics); + } else if ("raw12".equals(sformat)) { + outputFormats[i] = ImageFormat.RAW12; + sizes = ItsUtils.getRaw12OutputSizes(mCameraCharacteristics); + } else if ("dng".equals(sformat)) { + outputFormats[i] = ImageFormat.RAW_SENSOR; + sizes = ItsUtils.getRaw16OutputSizes(mCameraCharacteristics); + mCaptureRawIsDng = true; + } else if ("rawStats".equals(sformat)) { + outputFormats[i] = ImageFormat.RAW_SENSOR; + sizes = ItsUtils.getRaw16OutputSizes(mCameraCharacteristics); + mCaptureRawIsStats = true; + mCaptureStatsGridWidth = surfaceObj.optInt("gridWidth"); + mCaptureStatsGridHeight = surfaceObj.optInt("gridHeight"); + } else { + throw new ItsException("Unsupported format: " + sformat); + } + // If the size is omitted, then default to the largest allowed size for the + // format. + int width = surfaceObj.optInt("width"); + int height = surfaceObj.optInt("height"); + if (width <= 0) { + if (sizes == null || sizes.length == 0) { + throw new ItsException(String.format( + "Zero stream configs available for requested format: %s", + sformat)); + } + width = ItsUtils.getMaxSize(sizes).getWidth(); + } + if (height <= 0) { + height = ItsUtils.getMaxSize(sizes).getHeight(); + } + if (mCaptureStatsGridWidth <= 0) { + mCaptureStatsGridWidth = width; + } + if (mCaptureStatsGridHeight <= 0) { + mCaptureStatsGridHeight = height; + } + + // TODO: Crop to the active array in the stats image analysis. + + outputSizes[i] = new Size(width, height); + } + } catch (org.json.JSONException e) { + throw new ItsException("JSON error", e); + } + } else { + // No surface(s) specified at all. + // Default: a single output surface which is full-res YUV. + Size sizes[] = ItsUtils.getYuvOutputSizes(mCameraCharacteristics); + numSurfaces = 1; + + outputSizes = new Size[1]; + outputFormats = new int[1]; + outputSizes[0] = sizes[0]; + outputFormats[0] = ImageFormat.YUV_420_888; + } + + prepareImageReaders(outputSizes, outputFormats, inputSize, inputFormat, maxInputBuffers); + } + private void doCapture(JSONObject params) throws ItsException { try { // Parse the JSON to get the list of capture requests. List<CaptureRequest.Builder> requests = ItsSerializer.deserializeRequestList( mCamera, params); - // Set the output surface(s) and listeners. - int widths[] = new int[MAX_NUM_OUTPUT_SURFACES]; - int heights[] = new int[MAX_NUM_OUTPUT_SURFACES]; - int formats[] = new int[MAX_NUM_OUTPUT_SURFACES]; int numSurfaces = 0; try { mCountRawOrDng.set(0); mCountJpg.set(0); mCountYuv.set(0); mCountRaw10.set(0); + mCountRaw12.set(0); mCountCapRes.set(0); mCaptureRawIsDng = false; + mCaptureRawIsStats = false; mCaptureResults = new CaptureResult[requests.size()]; JSONArray jsonOutputSpecs = ItsUtils.getOutputSpecs(params); - if (jsonOutputSpecs != null) { - numSurfaces = jsonOutputSpecs.length(); - if (numSurfaces > MAX_NUM_OUTPUT_SURFACES) { - throw new ItsException("Too many output surfaces"); - } - for (int i = 0; i < numSurfaces; i++) { - // Get the specified surface. - JSONObject surfaceObj = jsonOutputSpecs.getJSONObject(i); - String sformat = surfaceObj.optString("format"); - Size sizes[]; - if ("yuv".equals(sformat) || "".equals(sformat)) { - // Default to YUV if no format is specified. - formats[i] = ImageFormat.YUV_420_888; - sizes = ItsUtils.getYuvOutputSizes(mCameraCharacteristics); - } else if ("jpg".equals(sformat) || "jpeg".equals(sformat)) { - formats[i] = ImageFormat.JPEG; - sizes = ItsUtils.getJpegOutputSizes(mCameraCharacteristics); - } else if ("raw".equals(sformat)) { - formats[i] = ImageFormat.RAW_SENSOR; - sizes = ItsUtils.getRawOutputSizes(mCameraCharacteristics); - } else if ("raw10".equals(sformat)) { - formats[i] = ImageFormat.RAW10; - sizes = ItsUtils.getRawOutputSizes(mCameraCharacteristics); - } else if ("dng".equals(sformat)) { - formats[i] = ImageFormat.RAW_SENSOR; - sizes = ItsUtils.getRawOutputSizes(mCameraCharacteristics); - mCaptureRawIsDng = true; - } else { - throw new ItsException("Unsupported format: " + sformat); - } - // If the size is omitted, then default to the largest allowed size for the - // format. - widths[i] = surfaceObj.optInt("width"); - heights[i] = surfaceObj.optInt("height"); - if (widths[i] <= 0) { - if (sizes == null || sizes.length == 0) { - throw new ItsException(String.format( - "Zero stream configs available for requested format: %s", - sformat)); - } - widths[i] = sizes[0].getWidth(); - } - if (heights[i] <= 0) { - heights[i] = sizes[0].getHeight(); - } - } - } else { - // No surface(s) specified at all. - // Default: a single output surface which is full-res YUV. - Size sizes[] = - ItsUtils.getYuvOutputSizes(mCameraCharacteristics); - numSurfaces = 1; - widths[0] = sizes[0].getWidth(); - heights[0] = sizes[0].getHeight(); - formats[0] = ImageFormat.YUV_420_888; - } - prepareCaptureReader(widths, heights, formats, numSurfaces); + prepareImageReadersWithOutputSpecs(jsonOutputSpecs, /*inputSize*/null, + /*inputFormat*/0, /*maxInputBuffers*/0); + numSurfaces = mOutputImageReaders.length; + List<Surface> outputSurfaces = new ArrayList<Surface>(numSurfaces); for (int i = 0; i < numSurfaces; i++) { - outputSurfaces.add(mCaptureReaders[i].getSurface()); + outputSurfaces.add(mOutputImageReaders[i].getSurface()); } BlockingSessionCallback sessionListener = new BlockingSessionCallback(); mCamera.createCaptureSession(outputSurfaces, sessionListener, mCameraHandler); @@ -1078,7 +1174,8 @@ for (int i = 0; i < numSurfaces; i++) { ImageReader.OnImageAvailableListener readerListener = createAvailableListener(mCaptureCallback); - mCaptureReaders[i].setOnImageAvailableListener(readerListener,mSaveHandlers[i]); + mOutputImageReaders[i].setOnImageAvailableListener(readerListener, + mSaveHandlers[i]); } // Plan for how many callbacks need to be received throughout the duration of this @@ -1089,8 +1186,6 @@ } catch (CameraAccessException e) { throw new ItsException("Error configuring outputs", e); - } catch (org.json.JSONException e) { - throw new ItsException("JSON error", e); } // Initiate the captures. @@ -1107,7 +1202,7 @@ } for (int j = 0; j < numSurfaces; j++) { - req.addTarget(mCaptureReaders[j].getSurface()); + req.addTarget(mOutputImageReaders[j].getSurface()); } mSession.capture(req.build(), mCaptureResultListener, mResultHandler); } @@ -1137,6 +1232,182 @@ } } + /** + * Perform reprocess captures. + * + * It takes captureRequests in a JSON object and perform capture requests in two steps: + * regular capture request to get reprocess input and reprocess capture request to get + * reprocess outputs. + * + * Regular capture requests: + * 1. For each capture request in the JSON object, create a full-size capture request with + * the settings in the JSON object. + * 2. Remember and clear noise reduction, edge enhancement, and effective exposure factor + * from the regular capture requests. (Those settings will be used for reprocess requests.) + * 3. Submit the regular capture requests. + * + * Reprocess capture requests: + * 4. Wait for the regular capture results and use them to create reprocess capture requests. + * 5. Wait for the regular capture output images and queue them to the image writer. + * 6. Set the noise reduction, edge enhancement, and effective exposure factor from #2. + * 7. Submit the reprocess capture requests. + * + * The output images and results for the regular capture requests won't be written to socket. + * The output images and results for the reprocess capture requests will be written to socket. + */ + private void doReprocessCapture(JSONObject params) throws ItsException { + ImageWriter imageWriter = null; + ArrayList<Integer> noiseReductionModes = new ArrayList<>(); + ArrayList<Integer> edgeModes = new ArrayList<>(); + ArrayList<Float> effectiveExposureFactors = new ArrayList<>(); + + mCountRawOrDng.set(0); + mCountJpg.set(0); + mCountYuv.set(0); + mCountRaw10.set(0); + mCountRaw12.set(0); + mCountCapRes.set(0); + mCaptureRawIsDng = false; + mCaptureRawIsStats = false; + + try { + // Parse the JSON to get the list of capture requests. + List<CaptureRequest.Builder> inputRequests = + ItsSerializer.deserializeRequestList(mCamera, params); + + // Prepare the image readers for reprocess input and reprocess outputs. + int inputFormat = getReprocessInputFormat(params); + Size inputSize = ItsUtils.getMaxOutputSize(mCameraCharacteristics, inputFormat); + JSONArray jsonOutputSpecs = ItsUtils.getOutputSpecs(params); + prepareImageReadersWithOutputSpecs(jsonOutputSpecs, inputSize, inputFormat, + inputRequests.size()); + + // Prepare a reprocessable session. + int numOutputSurfaces = mOutputImageReaders.length; + InputConfiguration inputConfig = new InputConfiguration(inputSize.getWidth(), + inputSize.getHeight(), inputFormat); + List<Surface> outputSurfaces = new ArrayList<Surface>(); + boolean addSurfaceForInput = true; + for (int i = 0; i < numOutputSurfaces; i++) { + outputSurfaces.add(mOutputImageReaders[i].getSurface()); + if (mOutputImageReaders[i] == mInputImageReader) { + // If input and one of the outputs share the same image reader, avoid + // adding the same surfaces twice. + addSurfaceForInput = false; + } + } + + if (addSurfaceForInput) { + // Besides the output surfaces specified in JSON object, add an additional one + // for reprocess input. + outputSurfaces.add(mInputImageReader.getSurface()); + } + + BlockingSessionCallback sessionListener = new BlockingSessionCallback(); + mCamera.createReprocessableCaptureSession(inputConfig, outputSurfaces, sessionListener, + mCameraHandler); + mSession = sessionListener.waitAndGetSession(TIMEOUT_IDLE_MS); + + // Create an image writer for reprocess input. + Surface inputSurface = mSession.getInputSurface(); + imageWriter = ImageWriter.newInstance(inputSurface, inputRequests.size()); + + // Set up input reader listener and capture callback listener to get + // reprocess input buffers and the results in order to create reprocess capture + // requests. + ImageReaderListenerWaiter inputReaderListener = new ImageReaderListenerWaiter(); + mInputImageReader.setOnImageAvailableListener(inputReaderListener, mSaveHandlers[0]); + + CaptureCallbackWaiter captureCallbackWaiter = new CaptureCallbackWaiter(); + // Prepare the reprocess input request + for (CaptureRequest.Builder inputReqest : inputRequests) { + // Remember and clear noise reduction, edge enhancement, and effective exposure + // factors. + noiseReductionModes.add(inputReqest.get(CaptureRequest.NOISE_REDUCTION_MODE)); + edgeModes.add(inputReqest.get(CaptureRequest.EDGE_MODE)); + effectiveExposureFactors.add(inputReqest.get( + CaptureRequest.REPROCESS_EFFECTIVE_EXPOSURE_FACTOR)); + + inputReqest.set(CaptureRequest.NOISE_REDUCTION_MODE, + CaptureRequest.NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG); + inputReqest.set(CaptureRequest.EDGE_MODE, CaptureRequest.EDGE_MODE_ZERO_SHUTTER_LAG); + inputReqest.set(CaptureRequest.REPROCESS_EFFECTIVE_EXPOSURE_FACTOR, null); + inputReqest.addTarget(mInputImageReader.getSurface()); + mSession.capture(inputReqest.build(), captureCallbackWaiter, mResultHandler); + } + + // Wait for reprocess input images + ArrayList<CaptureRequest.Builder> reprocessOutputRequests = new ArrayList<>(); + for (int i = 0; i < inputRequests.size(); i++) { + TotalCaptureResult result = + captureCallbackWaiter.getResult(TIMEOUT_CALLBACK * 1000); + reprocessOutputRequests.add(mCamera.createReprocessCaptureRequest(result)); + imageWriter.queueInputImage(inputReaderListener.getImage(TIMEOUT_CALLBACK * 1000)); + } + + // Start performing reprocess captures. + + mCaptureResults = new CaptureResult[inputRequests.size()]; + + // Prepare reprocess capture requests. + for (int i = 0; i < numOutputSurfaces; i++) { + ImageReader.OnImageAvailableListener outputReaderListener = + createAvailableListener(mCaptureCallback); + mOutputImageReaders[i].setOnImageAvailableListener(outputReaderListener, + mSaveHandlers[i]); + } + + // Initiate the captures. + for (int i = 0; i < reprocessOutputRequests.size(); i++) { + CaptureRequest.Builder req = reprocessOutputRequests.get(i); + for (ImageReader outputImageReader : mOutputImageReaders) { + req.addTarget(outputImageReader.getSurface()); + } + + req.set(CaptureRequest.NOISE_REDUCTION_MODE, noiseReductionModes.get(i)); + req.set(CaptureRequest.EDGE_MODE, edgeModes.get(i)); + req.set(CaptureRequest.REPROCESS_EFFECTIVE_EXPOSURE_FACTOR, + effectiveExposureFactors.get(i)); + + mSession.capture(req.build(), mCaptureResultListener, mResultHandler); + } + + // Plan for how many callbacks need to be received throughout the duration of this + // sequence of capture requests. There is one callback per image surface, and one + // callback for the CaptureResult, for each capture. + int numCaptures = reprocessOutputRequests.size(); + mCountCallbacksRemaining.set(numCaptures * (numOutputSurfaces + 1)); + + // Make sure all callbacks have been hit (wait until captures are done). + // If no timeouts are received after a timeout, then fail. + int currentCount = mCountCallbacksRemaining.get(); + while (currentCount > 0) { + try { + Thread.sleep(TIMEOUT_CALLBACK*1000); + } catch (InterruptedException e) { + throw new ItsException("Timeout failure", e); + } + int newCount = mCountCallbacksRemaining.get(); + if (newCount == currentCount) { + throw new ItsException( + "No callback received within timeout"); + } + currentCount = newCount; + } + } catch (android.hardware.camera2.CameraAccessException e) { + throw new ItsException("Access error: ", e); + } finally { + closeImageReaders(); + if (mSession != null) { + mSession.close(); + mSession = null; + } + if (imageWriter != null) { + imageWriter.close(); + } + } + } + @Override public final void onSensorChanged(SensorEvent event) { synchronized(mEventLock) { @@ -1179,13 +1450,39 @@ ByteBuffer buf = ByteBuffer.wrap(img); int count = mCountRaw10.getAndIncrement(); mSocketRunnableObj.sendResponseCaptureBuffer("raw10Image", buf); + } else if (format == ImageFormat.RAW12) { + Logt.i(TAG, "Received RAW12 capture"); + byte[] img = ItsUtils.getDataFromImage(capture); + ByteBuffer buf = ByteBuffer.wrap(img); + int count = mCountRaw12.getAndIncrement(); + mSocketRunnableObj.sendResponseCaptureBuffer("raw12Image", buf); } else if (format == ImageFormat.RAW_SENSOR) { Logt.i(TAG, "Received RAW16 capture"); int count = mCountRawOrDng.getAndIncrement(); if (! mCaptureRawIsDng) { byte[] img = ItsUtils.getDataFromImage(capture); - ByteBuffer buf = ByteBuffer.wrap(img); - mSocketRunnableObj.sendResponseCaptureBuffer("rawImage", buf); + if (! mCaptureRawIsStats) { + ByteBuffer buf = ByteBuffer.wrap(img); + mSocketRunnableObj.sendResponseCaptureBuffer("rawImage", buf); + } else { + // Compute the requested stats on the raw frame, and return the results + // in a new "stats image". + long startTimeMs = SystemClock.elapsedRealtime(); + int w = capture.getWidth(); + int h = capture.getHeight(); + int gw = mCaptureStatsGridWidth; + int gh = mCaptureStatsGridHeight; + float[] stats = StatsImage.computeStatsImage(img, w, h, gw, gh); + long endTimeMs = SystemClock.elapsedRealtime(); + Log.e(TAG, "Raw stats computation takes " + (endTimeMs - startTimeMs) + " ms"); + + ByteBuffer bBuf = ByteBuffer.allocateDirect(stats.length * 4); + bBuf.order(ByteOrder.nativeOrder()); + FloatBuffer fBuf = bBuf.asFloatBuffer(); + fBuf.put(stats); + fBuf.position(0); + mSocketRunnableObj.sendResponseCaptureBuffer("rawStatsImage", bBuf); + } } else { // Wait until the corresponding capture result is ready, up to a timeout. long t0 = android.os.SystemClock.elapsedRealtime(); @@ -1379,7 +1676,7 @@ int count = mCountCapRes.getAndIncrement(); mCaptureResults[count] = result; mSocketRunnableObj.sendResponseCaptureResult(mCameraCharacteristics, - request, result, mCaptureReaders); + request, result, mOutputImageReaders); mCountCallbacksRemaining.decrementAndGet(); } } catch (ItsException e) { @@ -1395,4 +1692,93 @@ Logt.e(TAG, "Script error: capture failed"); } }; + + private class CaptureCallbackWaiter extends CameraCaptureSession.CaptureCallback { + private final LinkedBlockingQueue<TotalCaptureResult> mResultQueue = + new LinkedBlockingQueue<>(); + + @Override + public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, + long timestamp, long frameNumber) { + } + + @Override + public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, + TotalCaptureResult result) { + try { + mResultQueue.put(result); + } catch (InterruptedException e) { + throw new UnsupportedOperationException( + "Can't handle InterruptedException in onImageAvailable"); + } + } + + @Override + public void onCaptureFailed(CameraCaptureSession session, CaptureRequest request, + CaptureFailure failure) { + Logt.e(TAG, "Script error: capture failed"); + } + + public TotalCaptureResult getResult(long timeoutMs) throws ItsException { + TotalCaptureResult result; + try { + result = mResultQueue.poll(timeoutMs, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + throw new ItsException(e); + } + + if (result == null) { + throw new ItsException("Getting an image timed out after " + timeoutMs + + "ms"); + } + + return result; + } + } + + private static class ImageReaderListenerWaiter implements ImageReader.OnImageAvailableListener { + private final LinkedBlockingQueue<Image> mImageQueue = new LinkedBlockingQueue<>(); + + @Override + public void onImageAvailable(ImageReader reader) { + try { + mImageQueue.put(reader.acquireNextImage()); + } catch (InterruptedException e) { + throw new UnsupportedOperationException( + "Can't handle InterruptedException in onImageAvailable"); + } + } + + public Image getImage(long timeoutMs) throws ItsException { + Image image; + try { + image = mImageQueue.poll(timeoutMs, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + throw new ItsException(e); + } + + if (image == null) { + throw new ItsException("Getting an image timed out after " + timeoutMs + + "ms"); + } + return image; + } + } + + private int getReprocessInputFormat(JSONObject params) throws ItsException { + String reprocessFormat; + try { + reprocessFormat = params.getString("reprocessFormat"); + } catch (org.json.JSONException e) { + throw new ItsException("Error parsing reprocess format: " + e); + } + + if (reprocessFormat.equals("yuv")) { + return ImageFormat.YUV_420_888; + } else if (reprocessFormat.equals("private")) { + return ImageFormat.PRIVATE; + } + + throw new ItsException("Uknown reprocess format: " + reprocessFormat); + } }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsUtils.java index 2011314..6fd050b 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsUtils.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsUtils.java
@@ -91,11 +91,21 @@ } } - public static Size[] getRawOutputSizes(CameraCharacteristics ccs) + public static Size[] getRaw16OutputSizes(CameraCharacteristics ccs) throws ItsException { return getOutputSizes(ccs, ImageFormat.RAW_SENSOR); } + public static Size[] getRaw10OutputSizes(CameraCharacteristics ccs) + throws ItsException { + return getOutputSizes(ccs, ImageFormat.RAW10); + } + + public static Size[] getRaw12OutputSizes(CameraCharacteristics ccs) + throws ItsException { + return getOutputSizes(ccs, ImageFormat.RAW12); + } + public static Size[] getJpegOutputSizes(CameraCharacteristics ccs) throws ItsException { return getOutputSizes(ccs, ImageFormat.JPEG); @@ -106,6 +116,11 @@ return getOutputSizes(ccs, ImageFormat.YUV_420_888); } + public static Size getMaxOutputSize(CameraCharacteristics ccs, int format) + throws ItsException { + return getMaxSize(getOutputSizes(ccs, format)); + } + private static Size[] getOutputSizes(CameraCharacteristics ccs, int format) throws ItsException { StreamConfigurationMap configMap = ccs.get( @@ -113,7 +128,37 @@ if (configMap == null) { throw new ItsException("Failed to get stream config"); } - return configMap.getOutputSizes(format); + Size[] normalSizes = configMap.getOutputSizes(format); + Size[] slowSizes = configMap.getHighResolutionOutputSizes(format); + Size[] allSizes = null; + if (normalSizes != null && slowSizes != null) { + allSizes = new Size[normalSizes.length + slowSizes.length]; + System.arraycopy(normalSizes, 0, allSizes, 0, + normalSizes.length); + System.arraycopy(slowSizes, 0, allSizes, normalSizes.length, + slowSizes.length); + } else if (normalSizes != null) { + allSizes = normalSizes; + } else if (slowSizes != null) { + allSizes = slowSizes; + } + return allSizes; + } + + public static Size getMaxSize(Size[] sizes) { + if (sizes == null || sizes.length == 0) { + throw new IllegalArgumentException("sizes was empty"); + } + + Size maxSize = sizes[0]; + for (int i = 1; i < sizes.length; i++) { + if (sizes[i].getWidth() * sizes[i].getHeight() > + maxSize.getWidth() * maxSize.getHeight()) { + maxSize = sizes[i]; + } + } + + return maxSize; } public static byte[] getDataFromImage(Image image) @@ -139,7 +184,7 @@ buffer.get(data); return data; } else if (format == ImageFormat.YUV_420_888 || format == ImageFormat.RAW_SENSOR - || format == ImageFormat.RAW10) { + || format == ImageFormat.RAW10 || format == ImageFormat.RAW12) { int offset = 0; data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8]; int maxRowSize = planes[0].getRowStride(); @@ -213,6 +258,7 @@ return 3 == planes.length; case ImageFormat.RAW_SENSOR: case ImageFormat.RAW10: + case ImageFormat.RAW12: case ImageFormat.JPEG: return 1 == planes.length; default: @@ -220,4 +266,3 @@ } } } -
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/StatsImage.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/StatsImage.java new file mode 100644 index 0000000..037177c --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/StatsImage.java
@@ -0,0 +1,35 @@ +/* + * Copyright (C) 2010 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.camera.its; + +import android.util.Log; + +public class StatsImage { + + static { + try { + System.loadLibrary("ctsverifier_jni"); + } catch (UnsatisfiedLinkError e) { + Log.e("StatsImage", "Error loading cts verifier JNI library"); + e.printStackTrace(); + } + } + + public native static float[] computeStatsImage( + byte[] img, int width, int height, int gridW, int gridH); + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java index 36acf42..3c108da 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
@@ -230,6 +230,11 @@ new Feature("android.software.voice_recognizers", false), }; + public static final Feature[] ALL_MNC_FEATURES = { + new Feature(PackageManager.FEATURE_MIDI, false), + new Feature(PackageManager.FEATURE_AUDIO_PRO, false), + }; + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -261,6 +266,9 @@ // add features from latest to last so that the latest requirements are put in the set first int apiVersion = Build.VERSION.SDK_INT; + if (apiVersion >= Build.VERSION_CODES.M) { + Collections.addAll(features, ALL_MNC_FEATURES); + } if (apiVersion >= Build.VERSION_CODES.LOLLIPOP) { Collections.addAll(features, ALL_LOLLIPOP_FEATURES); }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java new file mode 100644 index 0000000..073412d --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java
@@ -0,0 +1,381 @@ +package com.android.cts.verifier.managedprovisioning; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.app.KeyguardManager; +import android.content.DialogInterface; +import android.content.Intent; +import android.hardware.fingerprint.FingerprintManager; +import android.os.Bundle; +import android.os.CancellationSignal; +import android.os.CountDownTimer; +import android.provider.Settings; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyPermanentlyInvalidatedException; +import android.security.keystore.KeyProperties; +import android.security.keystore.UserNotAuthenticatedException; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Toast; + +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.DialogTestListActivity; +import com.android.cts.verifier.R; +import com.android.cts.verifier.TestResult; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; + +/** + * Test device credential-bound keys in work profile. + * Currently there are two types, one is keys bound to lockscreen passwords which can be configured + * to remain available within a certain timeout after the latest successful user authentication. + * The other is keys bound to fingerprint authentication which require explicit fingerprint + * authentication before they can be accessed. + */ +public class AuthenticationBoundKeyTestActivity extends DialogTestListActivity { + + public static final String ACTION_AUTH_BOUND_KEY_TEST = + "com.android.cts.verifier.managedprovisioning.action.AUTH_BOUND_KEY_TEST"; + + private static final int AUTHENTICATION_DURATION_SECONDS = 5; + private static final String LOCKSCREEN_KEY_NAME = "mp_lockscreen_key"; + private static final String FINGERPRINT_KEY_NAME = "mp_fingerprint_key"; + private static final byte[] SECRET_BYTE_ARRAY = new byte[] {1, 2, 3, 4, 5, 6}; + private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1; + private static final int FINGERPRINT_PERMISSION_REQUEST_CODE = 0; + + private static final int LOCKSCREEN = 1; + private static final int FINGERPRINT = 2; + + private static final String KEYSTORE_NAME = "AndroidKeyStore"; + private static final String CIPHER_TRANSFORMATION = KeyProperties.KEY_ALGORITHM_AES + "/" + + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7; + + + private KeyguardManager mKeyguardManager; + private FingerprintManager mFingerprintManager; + private boolean mFingerprintSupported; + + private DialogTestListItem mLockScreenBoundKeyTest; + private DialogTestListItem mFingerprintBoundKeyTest; + + private Cipher mFingerprintCipher; + + public AuthenticationBoundKeyTestActivity() { + super(R.layout.provisioning_byod, + R.string.provisioning_byod_auth_bound_key, + R.string.provisioning_byod_auth_bound_key_info, + R.string.provisioning_byod_auth_bound_key_instruction); + } + + + @Override + protected void onCreate(Bundle savedInstanceState) { + mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); + mFingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); + mFingerprintSupported = mFingerprintManager != null + && mFingerprintManager.isHardwareDetected(); + // Need to have valid mFingerprintSupported value before calling super.onCreate() because + // mFingerprintSupported is used in setupTests() which gets called by super.onCreate(). + super.onCreate(savedInstanceState); + + mPrepareTestButton.setText(R.string.provisioning_byod_auth_bound_key_set_up); + mPrepareTestButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View arg0) { + startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS)); + } + }); + if (mFingerprintSupported) { + requestPermissions(new String[] {Manifest.permission.USE_FINGERPRINT}, + FINGERPRINT_PERMISSION_REQUEST_CODE); + } + } + + private class LockscreenCountDownTester extends CountDownTimer { + + private Toast mToast; + + public LockscreenCountDownTester() { + // Wait for AUTHENTICATION_DURATION_SECONDS so the key is evicted before the real test. + super(AUTHENTICATION_DURATION_SECONDS * 1000, 1000); + mToast = Toast.makeText(AuthenticationBoundKeyTestActivity.this, "", Toast.LENGTH_SHORT); + } + + @Override + public void onFinish() { + mToast.cancel(); + if (tryEncryptWithLockscreenKey()) { + showToast("Test failed. Key accessible without auth."); + setTestResult(mLockScreenBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } else { + // Start the Confirm Credentials screen. + Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null); + if (intent != null) { + startActivityForResult(intent, CONFIRM_CREDENTIALS_REQUEST_CODE); + } else { + showToast("Test failed. No lockscreen password exists."); + setTestResult(mLockScreenBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } + } + } + + @Override + public void onTick(long millisUntilFinished) { + mToast.setText(String.format("Lockscreen challenge start in %d seconds..", + millisUntilFinished / 1000)); + mToast.show(); + } + } + + + @Override + protected void setupTests(ArrayTestListAdapter adapter) { + mLockScreenBoundKeyTest = new DialogTestListItem(this, + R.string.provisioning_byod_lockscreen_bound_key, + "BYOD_LockScreenBoundKeyTest") { + + @Override + public void performTest(DialogTestListActivity activity) { + if (checkPreconditions()) { + createKey(LOCKSCREEN); + new LockscreenCountDownTester().start(); + } + } + }; + adapter.add(mLockScreenBoundKeyTest); + + if (mFingerprintSupported) { + mFingerprintBoundKeyTest = new DialogTestListItem(this, + R.string.provisioning_byod_fingerprint_bound_key, + "BYOD_FingerprintBoundKeyTest") { + + @Override + public void performTest(DialogTestListActivity activity) { + if (checkPreconditions()) { + createKey(FINGERPRINT); + mFingerprintCipher = initFingerprintEncryptionCipher(); + if (tryEncryptWithFingerprintKey(mFingerprintCipher)) { + showToast("Test failed. Key accessible without auth."); + setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } else { + new FingerprintAuthDialogFragment().show(getFragmentManager(), + "fingerprint_dialog"); + } + } + } + }; + adapter.add(mFingerprintBoundKeyTest); + } + } + + private boolean checkPreconditions() { + if (!mKeyguardManager.isKeyguardSecure()) { + showToast("Please set a lockscreen password."); + return false; + } else if (mFingerprintSupported && !mFingerprintManager.hasEnrolledFingerprints()) { + showToast("Please enroll a fingerprint."); + return false; + } else { + return true; + } + } + + private String getKeyName(int testType) { + return testType == LOCKSCREEN ? LOCKSCREEN_KEY_NAME : FINGERPRINT_KEY_NAME; + } + /** + * Creates a symmetric key in the Android Key Store which can only be used after the user has + * authenticated with device credentials. + */ + private void createKey(int testType) { + try { + // Set the alias of the entry in Android KeyStore where the key will appear + // and the constrains (purposes) in the constructor of the Builder + KeyGenParameterSpec.Builder builder; + builder = new KeyGenParameterSpec.Builder(getKeyName(testType), + KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + .setUserAuthenticationRequired(true) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7); + if (testType == LOCKSCREEN) { + // Require that the user unlocked the lockscreen in the last 5 seconds + builder.setUserAuthenticationValidityDurationSeconds( + AUTHENTICATION_DURATION_SECONDS); + } + KeyGenerator keyGenerator = KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, KEYSTORE_NAME); + keyGenerator.init(builder.build()); + keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException | NoSuchProviderException + | InvalidAlgorithmParameterException e) { + throw new RuntimeException("Failed to create a symmetric key", e); + } + } + + private SecretKey loadSecretKey(int testType) { + try { + KeyStore keyStore = KeyStore.getInstance(KEYSTORE_NAME); + keyStore.load(null); + return (SecretKey) keyStore.getKey(getKeyName(testType), null); + } catch (UnrecoverableKeyException | CertificateException |KeyStoreException | IOException + | NoSuchAlgorithmException e) { + throw new RuntimeException("Failed to load a symmetric key", e); + } + } + + private boolean tryEncryptWithLockscreenKey() { + try { + // Try encrypting something, it will only work if the user authenticated within + // the last AUTHENTICATION_DURATION_SECONDS seconds. + Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, loadSecretKey(LOCKSCREEN)); + cipher.doFinal(SECRET_BYTE_ARRAY); + return true; + } catch (UserNotAuthenticatedException e) { + // User is not authenticated, let's authenticate with device credentials. + return false; + } catch (KeyPermanentlyInvalidatedException e) { + // This happens if the lock screen has been disabled or reset after the key was + // generated. + createKey(LOCKSCREEN); + showToast("Set up lockscreen after test ran. Retry the test."); + return false; + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException + | NoSuchPaddingException | NoSuchAlgorithmException e) { + throw new RuntimeException("Encrypt with lockscreen-bound key failed", e); + } + } + + private Cipher initFingerprintEncryptionCipher() { + try { + Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, loadSecretKey(FINGERPRINT)); + return cipher; + } catch (NoSuchPaddingException | NoSuchAlgorithmException e) { + return null; + } catch (KeyPermanentlyInvalidatedException e) { + // This happens if the lock screen has been disabled or reset after the key was + // generated after the key was generated. + createKey(FINGERPRINT); + showToast("Set up lockscreen after test ran. Retry the test."); + return null; + } catch (InvalidKeyException e) { + throw new RuntimeException("Init cipher with fingerprint-bound key failed", e); + } + } + + private boolean tryEncryptWithFingerprintKey(Cipher cipher) { + + try { + cipher.doFinal(SECRET_BYTE_ARRAY); + return true; + } catch (IllegalBlockSizeException e) { + // Cannot encrypt, key is unavailable + return false; + } catch (BadPaddingException e) { + throw new RuntimeException(e); + } + } + + @Override + protected void handleActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case CONFIRM_CREDENTIALS_REQUEST_CODE: + if (resultCode == RESULT_OK) { + if (tryEncryptWithLockscreenKey()) { + setTestResult(mLockScreenBoundKeyTest, TestResult.TEST_RESULT_PASSED); + } else { + showToast("Test failed. Key not accessible after auth"); + setTestResult(mLockScreenBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } + } else { + showToast("Lockscreen challenge canceled."); + setTestResult(mLockScreenBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } + break; + default: + super.handleActivityResult(requestCode, resultCode, data); + } + } + + private void showToast(String message) { + Toast.makeText(this, message, Toast.LENGTH_LONG).show(); + } + + public class FingerprintAuthDialogFragment extends DialogFragment { + + private CancellationSignal mCancellationSignal; + private FingerprintManagerCallback mFingerprintManagerCallback; + private boolean mSelfCancelled; + + class FingerprintManagerCallback extends FingerprintManager.AuthenticationCallback { + @Override + public void onAuthenticationError(int errMsgId, CharSequence errString) { + if (!mSelfCancelled) { + showToast(errString.toString()); + } + } + + @Override + public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { + showToast(helpString.toString()); + } + + @Override + public void onAuthenticationFailed() { + showToast(getString(R.string.sec_fp_auth_failed)); + } + + @Override + public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { + if (tryEncryptWithFingerprintKey(mFingerprintCipher)) { + showToast("Test passed."); + setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_PASSED); + } else { + showToast("Test failed. Key not accessible after auth"); + setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_FAILED); + } + FingerprintAuthDialogFragment.this.dismiss(); + } + } + + @Override + public void onDismiss(DialogInterface dialog) { + mCancellationSignal.cancel(); + mSelfCancelled = true; + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + mCancellationSignal = new CancellationSignal(); + mSelfCancelled = false; + mFingerprintManagerCallback = new FingerprintManagerCallback(); + mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(mFingerprintCipher), + mCancellationSignal, 0, mFingerprintManagerCallback, null); + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setMessage(R.string.sec_fp_dialog_message); + return builder.create(); + } + + } + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java index af3a7d5..b129665 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -16,33 +16,25 @@ package com.android.cts.verifier.managedprovisioning; -import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.provider.Settings; import android.util.Log; -import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.view.View.OnClickListener; -import android.widget.ArrayAdapter; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.TextView; import android.widget.Toast; -import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.DialogTestListActivity; import com.android.cts.verifier.R; import com.android.cts.verifier.TestListActivity; - -import java.util.ArrayList; -import java.util.List; +import com.android.cts.verifier.TestListAdapter.TestListItem; +import com.android.cts.verifier.TestResult; /** * CTS verifier test for BYOD managed provisioning flow. @@ -55,61 +47,56 @@ * The first two verifications are performed automatically, by interacting with profile owner using * cross-profile intents, while the last two are carried out manually by the user. */ -public class ByodFlowTestActivity extends PassFailButtons.ListActivity { +public class ByodFlowTestActivity extends DialogTestListActivity { private final String TAG = "ByodFlowTestActivity"; - private static final int REQUEST_STATUS = 1; + private static final int REQUEST_MANAGED_PROVISIONING = 0; + private static final int REQUEST_PROFILE_OWNER_STATUS = 1; + private static final int REQUEST_INTENT_FILTERS_STATUS = 2; private ComponentName mAdminReceiverComponent; - private TestAdapter mTestListAdapter; - private View mStartProvisioningButton; - private List<TestItem> mTests = new ArrayList<TestItem>(); + private DialogTestListItem mProfileOwnerInstalled; + private DialogTestListItem mProfileAccountVisibleTest; + private DialogTestListItem mDeviceAdminVisibleTest; + private DialogTestListItem mWorkAppVisibleTest; + private DialogTestListItem mCrossProfileIntentFiltersTestFromPersonal; + private DialogTestListItem mCrossProfileIntentFiltersTestFromWork; + private DialogTestListItem mAppLinkingTest; + private DialogTestListItem mDisableNonMarketTest; + private DialogTestListItem mEnableNonMarketTest; + private DialogTestListItem mWorkNotificationBadgedTest; + private DialogTestListItem mWorkStatusBarIconTest; + private DialogTestListItem mWorkStatusBarToastTest; + private DialogTestListItem mAppSettingsVisibleTest; + private DialogTestListItem mLocationSettingsVisibleTest; + private DialogTestListItem mBatterySettingsVisibleTest; + private DialogTestListItem mDataUsageSettingsVisibleTest; + private DialogTestListItem mCredSettingsVisibleTest; + private DialogTestListItem mPrintSettingsVisibleTest; + private DialogTestListItem mIntentFiltersTest; + private DialogTestListItem mPermissionLockdownTest; + private DialogTestListItem mCrossProfileImageCaptureSupportTest; + private DialogTestListItem mCrossProfileVideoCaptureSupportTest; + private DialogTestListItem mCrossProfileAudioCaptureSupportTest; + private TestListItem mKeyguardDisabledFeaturesTest; + private DialogTestListItem mDisableNfcBeamTest; + private TestListItem mAuthenticationBoundKeyTest; - protected DevicePolicyManager mDevicePolicyManager; - - private TestItem mProfileOwnerInstalled; - private TestItem mProfileAccountVisibleTest; - private TestItem mDeviceAdminVisibleTest; - private TestItem mWorkAppVisibleTest; - private TestItem mCrossProfileIntentFiltersTest; - private TestItem mDisableNonMarketTest; - private TestItem mEnableNonMarketTest; - private TestItem mWorkNotificationBadgedTest; - private TestItem mAppSettingsVisibleTest; - private TestItem mLocationSettingsVisibleTest; - private TestItem mCredSettingsVisibleTest; - private TestItem mPrintSettingsVisibleTest; - private TestItem mCrossProfileImageCaptureSupportTest; - private TestItem mCrossProfileVideoCaptureSupportTest; - private TestItem mCrossProfileAudioCaptureSupportTest; - private TestItem mDisableNfcBeamTest; - - private int mCurrentTestPosition; + public ByodFlowTestActivity() { + super(R.layout.provisioning_byod, + R.string.provisioning_byod, R.string.provisioning_byod_info, + R.string.provisioning_byod_instructions); + } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName()); - mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); + disableComponent(); - - setContentView(R.layout.provisioning_byod); - setInfoResources(R.string.provisioning_byod, R.string.provisioning_byod_info, -1); - setPassFailButtonClickListeners(); - getPassButton().setEnabled(false); - setResult(RESULT_CANCELED); - - setupTests(); - - mTestListAdapter = new TestAdapter(this); - setListAdapter(mTestListAdapter); - mTestListAdapter.addAll(mTests); - - mCurrentTestPosition = 0; - - mStartProvisioningButton = findViewById(R.id.byod_start); - mStartProvisioningButton.setOnClickListener(new OnClickListener() { + mPrepareTestButton.setText(R.string.provisioning_byod_start); + mPrepareTestButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startByodProvisioning(); @@ -135,22 +122,34 @@ // This is called when managed provisioning completes successfully without reboot. super.onNewIntent(intent); if (ByodHelperActivity.ACTION_PROFILE_OWNER_STATUS.equals(intent.getAction())) { - handleStatusUpdate(intent); + handleStatusUpdate(RESULT_OK, intent); } } @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - // Called after queryProfileOwner() - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == REQUEST_STATUS && resultCode == RESULT_OK) { - handleStatusUpdate(data); + protected void handleActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case REQUEST_MANAGED_PROVISIONING: + return; + case REQUEST_PROFILE_OWNER_STATUS: { + // Called after queryProfileOwner() + handleStatusUpdate(resultCode, data); + } break; + case REQUEST_INTENT_FILTERS_STATUS: { + // Called after checkIntentFilters() + handleIntentFiltersStatus(resultCode); + } break; + default: { + super.handleActivityResult(requestCode, resultCode, data); + } } } - private void handleStatusUpdate(Intent data) { - boolean provisioned = data.getBooleanExtra(ByodHelperActivity.EXTRA_PROVISIONED, false); - setTestResult(mProfileOwnerInstalled, provisioned ? TestResult.Passed : TestResult.Failed); + private void handleStatusUpdate(int resultCode, Intent data) { + boolean provisioned = data != null && + data.getBooleanExtra(ByodHelperActivity.EXTRA_PROVISIONED, false); + setTestResult(mProfileOwnerInstalled, (provisioned && resultCode == RESULT_OK) ? + TestResult.TEST_RESULT_PASSED : TestResult.TEST_RESULT_FAILED); } @Override @@ -161,10 +160,13 @@ super.finish(); } - private void setupTests() { - mProfileOwnerInstalled = new TestItem(this, R.string.provisioning_byod_profileowner) { + @Override + protected void setupTests(ArrayTestListAdapter adapter) { + mProfileOwnerInstalled = new DialogTestListItem(this, + R.string.provisioning_byod_profileowner, + "BYOD_ProfileOwnerInstalled") { @Override - public void performTest(ByodFlowTestActivity activity) { + public void performTest(DialogTestListActivity activity) { queryProfileOwner(true); } }; @@ -173,86 +175,186 @@ * To keep the image in this test up to date, use the instructions in * {@link ByodIconSamplerActivity}. */ - mWorkAppVisibleTest = new TestItemWithIcon(this, + mWorkAppVisibleTest = new DialogTestListItemWithIcon(this, R.string.provisioning_byod_workapps_visible, + "BYOD_WorkAppVisibleTest", R.string.provisioning_byod_workapps_visible_instruction, new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), R.drawable.badged_icon); - mWorkNotificationBadgedTest = new TestItemWithIcon(this, + mWorkNotificationBadgedTest = new DialogTestListItemWithIcon(this, R.string.provisioning_byod_work_notification, + "BYOD_WorkNotificationBadgedTest", R.string.provisioning_byod_work_notification_instruction, new Intent(WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION), R.drawable.ic_corp_icon); - mDisableNonMarketTest = new TestItem(this, R.string.provisioning_byod_nonmarket_deny, + Intent workStatusIcon = new Intent(WorkStatusTestActivity.ACTION_WORK_STATUS_ICON); + workStatusIcon.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mWorkStatusBarIconTest = new DialogTestListItemWithIcon(this, + R.string.provisioning_byod_work_status_icon, + "BYOD_WorkStatusBarIconTest", + R.string.provisioning_byod_work_status_icon_instruction, + workStatusIcon, + R.drawable.stat_sys_managed_profile_status); + + Intent workStatusToast = new Intent(WorkStatusTestActivity.ACTION_WORK_STATUS_TOAST); + workStatusToast.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mWorkStatusBarToastTest = new DialogTestListItem(this, + R.string.provisioning_byod_work_status_toast, + "BYOD_WorkStatusBarToastTest", + R.string.provisioning_byod_work_status_toast_instruction, + workStatusToast); + + mDisableNonMarketTest = new DialogTestListItem(this, + R.string.provisioning_byod_nonmarket_deny, + "BYOD_DisableNonMarketTest", R.string.provisioning_byod_nonmarket_deny_info, new Intent(ByodHelperActivity.ACTION_INSTALL_APK) .putExtra(ByodHelperActivity.EXTRA_ALLOW_NON_MARKET_APPS, false)); - mEnableNonMarketTest = new TestItem(this, R.string.provisioning_byod_nonmarket_allow, + mEnableNonMarketTest = new DialogTestListItem(this, + R.string.provisioning_byod_nonmarket_allow, + "BYOD_EnableNonMarketTest", R.string.provisioning_byod_nonmarket_allow_info, new Intent(ByodHelperActivity.ACTION_INSTALL_APK) .putExtra(ByodHelperActivity.EXTRA_ALLOW_NON_MARKET_APPS, true)); - mProfileAccountVisibleTest = new TestItem(this, R.string.provisioning_byod_profile_visible, + mProfileAccountVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_profile_visible, + "BYOD_ProfileAccountVisibleTest", R.string.provisioning_byod_profile_visible_instruction, new Intent(Settings.ACTION_SETTINGS)); - mAppSettingsVisibleTest = new TestItem(this, R.string.provisioning_byod_app_settings, + mAppSettingsVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_app_settings, + "BYOD_AppSettingsVisibleTest", R.string.provisioning_byod_app_settings_instruction, new Intent(Settings.ACTION_APPLICATION_SETTINGS)); - mDeviceAdminVisibleTest = new TestItem(this, R.string.provisioning_byod_admin_visible, + mDeviceAdminVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_admin_visible, + "BYOD_DeviceAdminVisibleTest", R.string.provisioning_byod_admin_visible_instruction, new Intent(Settings.ACTION_SECURITY_SETTINGS)); - mCredSettingsVisibleTest = new TestItem(this, R.string.provisioning_byod_cred_settings, + mCredSettingsVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_cred_settings, + "BYOD_CredSettingsVisibleTest", R.string.provisioning_byod_cred_settings_instruction, new Intent(Settings.ACTION_SECURITY_SETTINGS)); - mLocationSettingsVisibleTest = new TestItem(this, + mLocationSettingsVisibleTest = new DialogTestListItem(this, R.string.provisioning_byod_location_settings, + "BYOD_LocationSettingsVisibleTest", R.string.provisioning_byod_location_settings_instruction, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); - mPrintSettingsVisibleTest = new TestItem(this, R.string.provisioning_byod_print_settings, + mBatterySettingsVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_battery_settings, + "BYOD_BatterySettingsVisibleTest", + R.string.provisioning_byod_battery_settings_instruction, + new Intent(Intent.ACTION_POWER_USAGE_SUMMARY)); + + mDataUsageSettingsVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_data_usage_settings, + "BYOD_DataUsageSettingsVisibleTest", + R.string.provisioning_byod_data_usage_settings_instruction, + new Intent(Settings.ACTION_SETTINGS)); + + mPrintSettingsVisibleTest = new DialogTestListItem(this, + R.string.provisioning_byod_print_settings, + "BYOD_PrintSettingsVisibleTest", R.string.provisioning_byod_print_settings_instruction, new Intent(Settings.ACTION_PRINT_SETTINGS)); - Intent intent = new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE); + Intent intent = new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_WORK); + intent.putExtra(CrossProfileTestActivity.EXTRA_STARTED_FROM_WORK, false); Intent chooser = Intent.createChooser(intent, getResources().getString(R.string.provisioning_cross_profile_chooser)); - mCrossProfileIntentFiltersTest = new TestItem(this, - R.string.provisioning_byod_cross_profile, - R.string.provisioning_byod_cross_profile_instruction, + mCrossProfileIntentFiltersTestFromPersonal = new DialogTestListItem(this, + R.string.provisioning_byod_cross_profile_from_personal, + "BYOD_CrossProfileIntentFiltersTestFromPersonal", + R.string.provisioning_byod_cross_profile_from_personal_instruction, chooser); - mTests.add(mProfileOwnerInstalled); + mCrossProfileIntentFiltersTestFromWork = new DialogTestListItem(this, + R.string.provisioning_byod_cross_profile_from_work, + "BYOD_CrossProfileIntentFiltersTestFromWork", + R.string.provisioning_byod_cross_profile_from_work_instruction, + new Intent(ByodHelperActivity.ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)); + + mAppLinkingTest = new DialogTestListItem(this, + R.string.provisioning_app_linking, + "BYOD_AppLinking", + R.string.provisioning_byod_app_linking_instruction, + new Intent(ByodHelperActivity.ACTION_TEST_APP_LINKING_DIALOG)); + + mKeyguardDisabledFeaturesTest = TestListItem.newTest(this, + R.string.provisioning_byod_keyguard_disabled_features, + KeyguardDisabledFeaturesActivity.class.getName(), + new Intent(this, KeyguardDisabledFeaturesActivity.class), null); + + mAuthenticationBoundKeyTest = TestListItem.newTest(this, + R.string.provisioning_byod_auth_bound_key, + AuthenticationBoundKeyTestActivity.class.getName(), + new Intent(AuthenticationBoundKeyTestActivity.ACTION_AUTH_BOUND_KEY_TEST), + null); + + // Test for checking if the required intent filters are set during managed provisioning. + mIntentFiltersTest = new DialogTestListItem(this, + R.string.provisioning_byod_cross_profile_intent_filters, + "BYOD_IntentFiltersTest") { + @Override + public void performTest(DialogTestListActivity activity) { + checkIntentFilters(); + } + }; + + Intent permissionCheckIntent = new Intent( + PermissionLockdownTestActivity.ACTION_MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN); + mPermissionLockdownTest = new DialogTestListItem(this, + R.string.device_profile_owner_permission_lockdown_test, + "BYOD_PermissionLockdownTest", + R.string.profile_owner_permission_lockdown_test_info, + permissionCheckIntent); + + adapter.add(mProfileOwnerInstalled); // Badge related tests - mTests.add(mWorkAppVisibleTest); - mTests.add(mWorkNotificationBadgedTest); + adapter.add(mWorkAppVisibleTest); + adapter.add(mWorkNotificationBadgedTest); + adapter.add(mWorkStatusBarIconTest); + adapter.add(mWorkStatusBarToastTest); // Settings related tests. - mTests.add(mProfileAccountVisibleTest); - mTests.add(mDeviceAdminVisibleTest); - mTests.add(mCredSettingsVisibleTest); - mTests.add(mAppSettingsVisibleTest); - mTests.add(mLocationSettingsVisibleTest); - mTests.add(mPrintSettingsVisibleTest); + adapter.add(mProfileAccountVisibleTest); + adapter.add(mDeviceAdminVisibleTest); + adapter.add(mCredSettingsVisibleTest); + adapter.add(mAppSettingsVisibleTest); + adapter.add(mLocationSettingsVisibleTest); + adapter.add(mBatterySettingsVisibleTest); + adapter.add(mDataUsageSettingsVisibleTest); + adapter.add(mPrintSettingsVisibleTest); - mTests.add(mCrossProfileIntentFiltersTest); - mTests.add(mDisableNonMarketTest); - mTests.add(mEnableNonMarketTest); + adapter.add(mCrossProfileIntentFiltersTestFromPersonal); + adapter.add(mCrossProfileIntentFiltersTestFromWork); + adapter.add(mAppLinkingTest); + adapter.add(mDisableNonMarketTest); + adapter.add(mEnableNonMarketTest); + adapter.add(mIntentFiltersTest); + adapter.add(mPermissionLockdownTest); + adapter.add(mKeyguardDisabledFeaturesTest); + adapter.add(mAuthenticationBoundKeyTest); if (canResolveIntent(ByodHelperActivity.getCaptureImageIntent())) { // Capture image intent can be resolved in primary profile, so test. - mCrossProfileImageCaptureSupportTest = new TestItem(this, + mCrossProfileImageCaptureSupportTest = new DialogTestListItem(this, R.string.provisioning_byod_capture_image_support, + "BYOD_CrossProfileImageCaptureSupportTest", R.string.provisioning_byod_capture_image_support_info, new Intent(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_IMAGE)); - mTests.add(mCrossProfileImageCaptureSupportTest); + adapter.add(mCrossProfileImageCaptureSupportTest); } else { // Capture image intent cannot be resolved in primary profile, so skip test. Toast.makeText(ByodFlowTestActivity.this, @@ -262,11 +364,12 @@ if (canResolveIntent(ByodHelperActivity.getCaptureVideoIntent())) { // Capture video intent can be resolved in primary profile, so test. - mCrossProfileVideoCaptureSupportTest = new TestItem(this, + mCrossProfileVideoCaptureSupportTest = new DialogTestListItem(this, R.string.provisioning_byod_capture_video_support, + "BYOD_CrossProfileVideoCaptureSupportTest", R.string.provisioning_byod_capture_video_support_info, new Intent(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_VIDEO)); - mTests.add(mCrossProfileVideoCaptureSupportTest); + adapter.add(mCrossProfileVideoCaptureSupportTest); } else { // Capture video intent cannot be resolved in primary profile, so skip test. Toast.makeText(ByodFlowTestActivity.this, @@ -275,11 +378,12 @@ } if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) { - mDisableNfcBeamTest = new TestItem(this, R.string.provisioning_byod_nfc_beam, + mDisableNfcBeamTest = new DialogTestListItem(this, R.string.provisioning_byod_nfc_beam, + "BYOD_DisableNfcBeamTest", R.string.provisioning_byod_nfc_beam_allowed_instruction, new Intent(ByodHelperActivity.ACTION_TEST_NFC_BEAM)) { @Override - public void performTest(final ByodFlowTestActivity activity) { + public void performTest(final DialogTestListActivity activity) { activity.showManualTestDialog(mDisableNfcBeamTest, new DefaultTestCallback(mDisableNfcBeamTest) { @Override @@ -289,8 +393,10 @@ ByodHelperActivity.ACTION_TEST_NFC_BEAM); testNfcBeamIntent.putExtra(NfcTestActivity.EXTRA_DISALLOW_BY_POLICY, true); - TestItem disableNfcBeamTest2 = new TestItem(activity, + DialogTestListItem disableNfcBeamTest2 = + new DialogTestListItem(activity, R.string.provisioning_byod_nfc_beam, + "BYOD_DisableNfcBeamTest", R.string.provisioning_byod_nfc_beam_disallowed_instruction, testNfcBeamIntent); // The result should be reflected on the original test. @@ -300,17 +406,18 @@ }); } }; - mTests.add(mDisableNfcBeamTest); + adapter.add(mDisableNfcBeamTest); } /* TODO: reinstate when bug b/20131958 is fixed if (canResolveIntent(ByodHelperActivity.getCaptureAudioIntent())) { // Capture audio intent can be resolved in primary profile, so test. - mCrossProfileAudioCaptureSupportTest = new TestItem(this, + mCrossProfileAudioCaptureSupportTest = new DialogTestListItem(this, R.string.provisioning_byod_capture_audio_support, + "BYOD_CrossProfileAudioCaptureSupportTest", R.string.provisioning_byod_capture_audio_support_info, new Intent(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_AUDIO)); - mTests.add(mCrossProfileAudioCaptureSupportTest); + adapter.add(mCrossProfileAudioCaptureSupportTest); } else { // Capture audio intent cannot be resolved in primary profile, so skip test. Toast.makeText(ByodFlowTestActivity.this, @@ -320,89 +427,18 @@ */ } - @Override - protected void onListItemClick(ListView l, View v, int position, long id) { - super.onListItemClick(l, v, position, id); - mCurrentTestPosition = position; - TestItem test = (TestItem) getListAdapter().getItem(position); - test.performTest(this); - } - // Return whether the intent can be resolved in the current profile private boolean canResolveIntent(Intent intent) { return intent.resolveActivity(getPackageManager()) != null; } - private class DefaultTestCallback implements TestItem.TestCallback { - final private TestItem mTest; - - public DefaultTestCallback(TestItem test) { - mTest = test; - } - - @Override - public void onPass() { - clearRemainingState(mTest); - setTestResult(mTest, TestResult.Passed); - } - - @Override - public void onFail() { - clearRemainingState(mTest); - setTestResult(mTest, TestResult.Failed); - } - } - - private void showManualTestDialog(final TestItem test) { - showManualTestDialog(test, new DefaultTestCallback(test)); - } - - private void showManualTestDialog(final TestItem test, final TestItem.TestCallback callback) { - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_dialog_info) - .setTitle(R.string.provisioning_byod) - .setNeutralButton(R.string.provisioning_byod_go, null) - .setPositiveButton(R.string.pass_button_text, new AlertDialog.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - callback.onPass(); - } - }) - .setNegativeButton(R.string.fail_button_text, new AlertDialog.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - callback.onFail(); - } - }); - View customView = test.getCustomView(); - if (customView != null) { - dialogBuilder.setView(customView); - } else { - dialogBuilder.setMessage(test.getManualTestInstruction()); - } - final AlertDialog dialog = dialogBuilder.show(); - // Note: Setting the OnClickListener on the Dialog rather than the Builder, prevents the - // dialog being dismissed on onClick. - dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - try { - ByodFlowTestActivity.this.startActivity(test.getManualTestIntent()); - } catch (ActivityNotFoundException e) { - Toast.makeText(ByodFlowTestActivity.this, - "Cannot start " + test.getManualTestIntent(), Toast.LENGTH_LONG).show(); - setTestResult(test, TestResult.Failed); - dialog.dismiss(); - } - } - }); - } - - private void clearRemainingState(final TestItem test) { + @Override + protected void clearRemainingState(final DialogTestListItem test) { + super.clearRemainingState(test); if (WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION.equals( test.getManualTestIntent().getAction())) { try { - ByodFlowTestActivity.this.startActivity(new Intent( + startActivity(new Intent( WorkNotificationTestActivity.ACTION_CLEAR_WORK_NOTIFICATION)); } catch (ActivityNotFoundException e) { // User shouldn't run this test before work profile is set up. @@ -410,29 +446,15 @@ } } - private void setTestResult(TestItem test, TestResult result) { - test.setPassFailState(result); - - boolean testSucceeds = true; - for(TestItem aTest : mTests) { - testSucceeds &= (aTest.getPassFailState() == TestResult.Passed); - } - getPassButton().setEnabled(testSucceeds); - mTestListAdapter.notifyDataSetChanged(); - - this.getListView().smoothScrollToPosition(mCurrentTestPosition + 1); - } - private void startByodProvisioning() { Intent sending = new Intent(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE); - sending.putExtra(DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME, - mAdminReceiverComponent.getPackageName()); - sending.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminReceiverComponent); + sending.putExtra(DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME, + mAdminReceiverComponent); if (sending.resolveActivity(getPackageManager()) != null) { // ManagedProvisioning must be started with startActivityForResult, but we don't // care about the result, so passing 0 as a requestCode - startActivityForResult(sending, 0); + startActivityForResult(sending, REQUEST_MANAGED_PROVISIONING); } else { showToast(R.string.provisioning_byod_disabled); } @@ -441,11 +463,11 @@ private void queryProfileOwner(boolean showToast) { try { Intent intent = new Intent(ByodHelperActivity.ACTION_QUERY_PROFILE_OWNER); - startActivityForResult(intent, REQUEST_STATUS); + startActivityForResult(intent, REQUEST_PROFILE_OWNER_STATUS); } catch (ActivityNotFoundException e) { Log.d(TAG, "queryProfileOwner: ActivityNotFoundException", e); - setTestResult(mProfileOwnerInstalled, TestResult.Failed); + setTestResult(mProfileOwnerInstalled, TestResult.TEST_RESULT_FAILED); if (showToast) { showToast(R.string.provisioning_byod_no_activity); } @@ -463,140 +485,50 @@ } } + private void checkIntentFilters() { + try { + // We disable the ByodHelperActivity in the primary profile. So, this intent + // will be handled by the ByodHelperActivity in the managed profile. + Intent intent = new Intent(ByodHelperActivity.ACTION_CHECK_INTENT_FILTERS); + startActivityForResult(intent, REQUEST_INTENT_FILTERS_STATUS); + } catch (ActivityNotFoundException e) { + Log.d(TAG, "checkIntentFilters: ActivityNotFoundException", e); + setTestResult(mIntentFiltersTest, TestResult.TEST_RESULT_FAILED); + showToast(R.string.provisioning_byod_no_activity); + } + } + + private void handleIntentFiltersStatus(int resultCode) { + // we use the resultCode from ByodHelperActivity in the managed profile to know if certain + // intents fired from the managed profile are forwarded. + final boolean intentFiltersSetForManagedIntents = (resultCode == RESULT_OK); + // Since the ByodFlowTestActivity is running in the primary profile, we directly use + // the IntentFiltersTestHelper to know if certain intents fired from the primary profile + // are forwarded. + final boolean intentFiltersSetForPrimaryIntents = + new IntentFiltersTestHelper(this).checkCrossProfileIntentFilters( + IntentFiltersTestHelper.FLAG_INTENTS_FROM_PRIMARY); + final boolean intentFiltersSet = + intentFiltersSetForPrimaryIntents & intentFiltersSetForManagedIntents; + setTestResult(mIntentFiltersTest, + intentFiltersSet ? TestResult.TEST_RESULT_PASSED : TestResult.TEST_RESULT_FAILED); + } + private void disableComponent() { // Disable app components in the current profile, so only the counterpart in the other profile // can respond (via cross-profile intent filter) - getPackageManager().setComponentEnabledSetting(new ComponentName( - this, ByodHelperActivity.class), - PackageManager.COMPONENT_ENABLED_STATE_DISABLED, - PackageManager.DONT_KILL_APP); - getPackageManager().setComponentEnabledSetting(new ComponentName( - this, WorkNotificationTestActivity.class), - PackageManager.COMPONENT_ENABLED_STATE_DISABLED, - PackageManager.DONT_KILL_APP); - } - - private void showToast(int messageId) { - String message = getString(messageId); - Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); - } - - enum TestResult { - Unknown, Failed, Passed - } - - static class TestItem { - - public interface TestCallback { - void onPass(); - void onFail(); - } - - private String mDisplayName; - private TestResult mPassed; - private boolean mManualTest; - private String mManualInstruction; - private Intent mManualIntent; - - public TestItem(Context context, int nameResId) { - mDisplayName = context.getString(nameResId); - mPassed = TestResult.Unknown; - mManualTest = false; - } - - public void performTest(ByodFlowTestActivity activity) { - if (isManualTest()) { - activity.showManualTestDialog(this); - } - } - - public TestItem(Context context, int nameResId, int testInstructionResId, Intent testIntent) { - mDisplayName = context.getString(nameResId); - mPassed = TestResult.Unknown; - mManualTest = true; - mManualInstruction = context.getString(testInstructionResId); - mManualIntent = testIntent; - } - - @Override - public String toString() { - return mDisplayName; - } - - TestResult getPassFailState() { - return mPassed; - } - - void setPassFailState(TestResult state) { - mPassed = state; - } - - public boolean isManualTest() { - return mManualTest; - } - - public String getManualTestInstruction() { - return mManualInstruction; - } - - public Intent getManualTestIntent() { - return mManualIntent; - } - - public View getCustomView() { - return null; + final String[] components = { + ByodHelperActivity.class.getName(), + WorkNotificationTestActivity.class.getName(), + WorkStatusTestActivity.class.getName(), + PermissionLockdownTestActivity.ACTIVITY_ALIAS, + AuthenticationBoundKeyTestActivity.class.getName() + }; + for (String component : components) { + getPackageManager().setComponentEnabledSetting(new ComponentName(this, component), + PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP); } } - static class TestItemWithIcon extends TestItem { - - private int mImageResId; - private Context mContext; - - public TestItemWithIcon(Context context, int nameResId, int testInstructionResId, - Intent testIntent, int imageResId) { - super(context, nameResId, testInstructionResId, testIntent); - mContext = context; - mImageResId = imageResId; - } - - @Override - public View getCustomView() { - LayoutInflater layoutInflater = LayoutInflater.from(mContext); - View view = layoutInflater.inflate(R.layout.byod_custom_view, - null /* root */); - ((ImageView) view.findViewById(R.id.sample_icon)).setImageResource(mImageResId); - ((TextView) view.findViewById(R.id.message)).setText(getManualTestInstruction()); - return view; - } - } - - static class TestAdapter extends ArrayAdapter<TestItem> { - - public TestAdapter(Context context) { - super(context, android.R.layout.simple_list_item_1); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - TextView view = (TextView) super.getView(position, convertView, parent); - - TestItem item = getItem(position); - int backgroundResource = 0; - int iconResource = 0; - if (item.getPassFailState() == TestResult.Passed) { - backgroundResource = R.drawable.test_pass_gradient; - iconResource = R.drawable.fs_good; - } else if (item.getPassFailState() == TestResult.Failed){ - backgroundResource = R.drawable.test_fail_gradient; - iconResource = R.drawable.fs_error; - } - view.setBackgroundResource(backgroundResource); - view.setPadding(10, 0, 10, 0); - view.setCompoundDrawablePadding(10); - view.setCompoundDrawablesWithIntrinsicBounds(0, 0, iconResource, 0); - - return view; - } - } }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java index 800137a..9ea5061 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -27,6 +27,7 @@ import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; +import android.os.UserManager; import android.provider.MediaStore; import android.provider.Settings; import android.support.v4.content.FileProvider; @@ -39,7 +40,6 @@ import java.util.ArrayList; import com.android.cts.verifier.R; -import com.android.cts.verifier.managedprovisioning.ByodFlowTestActivity.TestResult; import com.android.cts.verifier.managedprovisioning.ByodPresentMediaDialog.DialogCallback; /** @@ -68,14 +68,37 @@ public static final String ACTION_CAPTURE_AND_CHECK_VIDEO = "com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_VIDEO"; // Primage -> managed intent: request to capture and check an audio recording public static final String ACTION_CAPTURE_AND_CHECK_AUDIO = "com.android.cts.verifier.managedprovisioning.BYOD_CAPTURE_AND_CHECK_AUDIO"; + public static final String ACTION_KEYGUARD_DISABLED_FEATURES = + "com.android.cts.verifier.managedprovisioning.BYOD_KEYGUARD_DISABLED_FEATURES"; + public static final String ACTION_LOCKNOW = + "com.android.cts.verifier.managedprovisioning.BYOD_LOCKNOW"; public static final String ACTION_TEST_NFC_BEAM = "com.android.cts.verifier.managedprovisioning.TEST_NFC_BEAM"; public static final String EXTRA_PROVISIONED = "extra_provisioned"; + public static final String EXTRA_PARAMETER_1 = "extra_parameter_1"; // Primary -> managed intent: set unknown sources restriction and install package public static final String ACTION_INSTALL_APK = "com.android.cts.verifier.managedprovisioning.BYOD_INSTALL_APK"; public static final String EXTRA_ALLOW_NON_MARKET_APPS = INSTALL_NON_MARKET_APPS; + // Primary -> managed intent: check if the required cross profile intent filters are set. + public static final String ACTION_CHECK_INTENT_FILTERS = + "com.android.cts.verifier.managedprovisioning.action.CHECK_INTENT_FILTERS"; + + // Primary -> managed intent: will send a cross profile intent and check if the user sees an + // intent picker dialog and can open the apps. + public static final String ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG = + "com.android.cts.verifier.managedprovisioning.action.TEST_CROSS_PROFILE_INTENTS_DIALOG"; + + // Primary -> managed intent: will send an app link intent and check if the user sees a + // dialog and can open the apps. This test is extremely similar to + // ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG, but the intent used is a web intent, and there is + // some behavior which is specific to web intents. + public static final String ACTION_TEST_APP_LINKING_DIALOG = + "com.android.cts.verifier.managedprovisioning.action.TEST_APP_LINKING_DIALOG"; + + public static final int RESULT_FAILED = RESULT_FIRST_USER; + private static final int REQUEST_INSTALL_PACKAGE = 1; private static final int REQUEST_IMAGE_CAPTURE = 2; private static final int REQUEST_VIDEO_CAPTURE = 3; @@ -143,7 +166,15 @@ // Not yet ready to finish- wait until the result comes back return; + // Queried by CtsVerifier in the primary side using startActivityForResult. + } else if (action.equals(ACTION_CHECK_INTENT_FILTERS)) { + final boolean intentFiltersSetForManagedIntents = + new IntentFiltersTestHelper(this).checkCrossProfileIntentFilters( + IntentFiltersTestHelper.FLAG_INTENTS_FROM_MANAGED); + setResult(intentFiltersSetForManagedIntents? RESULT_OK : RESULT_FAILED, null); } else if (action.equals(ACTION_CAPTURE_AND_CHECK_IMAGE)) { + // We need the camera permission to send the image capture intent. + grantCameraPermissionToSelf(); Intent captureImageIntent = getCaptureImageIntent(); mImageUri = getTempUri("image.jpg"); captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); @@ -156,6 +187,8 @@ } return; } else if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO)) { + // We need the camera permission to send the video capture intent. + grantCameraPermissionToSelf(); Intent captureVideoIntent = getCaptureVideoIntent(); mVideoUri = getTempUri("video.mp4"); captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri); @@ -177,12 +210,30 @@ finish(); } return; + } else if (ACTION_KEYGUARD_DISABLED_FEATURES.equals(action)) { + final int value = intent.getIntExtra(EXTRA_PARAMETER_1, + DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE); + ComponentName admin = DeviceAdminTestReceiver.getReceiverComponentName(); + mDevicePolicyManager.setKeyguardDisabledFeatures(admin, value); + } else if (ACTION_LOCKNOW.equals(action)) { + mDevicePolicyManager.lockNow(); + setResult(RESULT_OK); } else if (action.equals(ACTION_TEST_NFC_BEAM)) { Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class); testNfcBeamIntent.putExtras(intent); startActivity(testNfcBeamIntent); finish(); return; + } else if (action.equals(ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)) { + sendIntentInsideChooser(new Intent( + CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL)); + } else if (action.equals(ACTION_TEST_APP_LINKING_DIALOG)) { + mDevicePolicyManager.addUserRestriction( + DeviceAdminTestReceiver.getReceiverComponentName(), + UserManager.ALLOW_PARENT_PROFILE_APP_LINKING); + Intent toSend = new Intent(Intent.ACTION_VIEW); + toSend.setData(Uri.parse("http://com.android.cts.verifier")); + sendIntentInsideChooser(toSend); } // This activity has no UI and is only used to respond to CtsVerifier in the primary side. finish(); @@ -263,6 +314,10 @@ return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); } + public static Intent createLockIntent() { + return new Intent(ACTION_LOCKNOW); + } + private Uri getTempUri(String fileName) { final File file = new File(getFilesDir() + File.separator + "images" + File.separator + fileName); @@ -308,6 +363,19 @@ Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } + private void grantCameraPermissionToSelf() { + mDevicePolicyManager.setPermissionGrantState(mAdminReceiverComponent, getPackageName(), + android.Manifest.permission.CAMERA, + DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + } + + private void sendIntentInsideChooser(Intent toSend) { + toSend.putExtra(CrossProfileTestActivity.EXTRA_STARTED_FROM_WORK, true); + Intent chooser = Intent.createChooser(toSend, + getResources().getString(R.string.provisioning_cross_profile_chooser)); + startActivity(chooser); + } + @Override public void onDialogClose() { finish();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CrossProfileTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CrossProfileTestActivity.java index 6c38e12..3f316f21 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CrossProfileTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CrossProfileTestActivity.java
@@ -35,7 +35,12 @@ */ public class CrossProfileTestActivity extends Activity { // Intent for app in both profiles - public static final String ACTION_CROSS_PROFILE = "com.android.cts.verifier.managedprovisioning.CROSS_PROFILE"; + public static final String ACTION_CROSS_PROFILE_TO_PERSONAL = + "com.android.cts.verifier.managedprovisioning.CROSS_PROFILE_TO_PERSONAL"; + public static final String ACTION_CROSS_PROFILE_TO_WORK = + "com.android.cts.verifier.managedprovisioning.CROSS_PROFILE_TO_WORK"; + public static final String EXTRA_STARTED_FROM_WORK + = "com.android.cts.verifier.managedprovisioning.STARTED_FROM_WORK"; @Override public void onCreate(Bundle savedInstanceState) { @@ -45,9 +50,15 @@ // Check if we are running in the work or personal side, by testing if currently we are the // profile owner or not. - textView.setText(isProfileOwner() ? R.string.provisioning_byod_cross_profile_app_work - : R.string.provisioning_byod_cross_profile_app_personal); - + boolean inWorkProfile = isProfileOwner(); + boolean startedFromWork = getIntent().getBooleanExtra(EXTRA_STARTED_FROM_WORK, false); + if (inWorkProfile && !startedFromWork) { + textView.setText(R.string.provisioning_byod_cross_profile_app_work); + } else if (!inWorkProfile && startedFromWork) { + textView.setText(R.string.provisioning_byod_cross_profile_app_personal); + } else { // started from the same side we're currently running in + textView.setText(R.string.provisioning_byod_cross_profile_app_ctsverifier); + } findViewById(R.id.button_finish).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java index 15349ab..ed6b5eb 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -22,9 +22,7 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.content.pm.PackageManager; import android.util.Log; -import android.widget.Toast; /** * Profile owner receiver for BYOD flow test. @@ -32,6 +30,16 @@ */ public class DeviceAdminTestReceiver extends DeviceAdminReceiver { private static final String TAG = "DeviceAdminTestReceiver"; + private static final String DEVICE_OWNER_PKG = + "com.android.cts.verifier"; + private static final String ADMIN_RECEIVER_TEST_CLASS = + DEVICE_OWNER_PKG + ".managedprovisioning.DeviceAdminTestReceiver"; + private static final ComponentName RECEIVER_COMPONENT_NAME = new ComponentName( + DEVICE_OWNER_PKG, ADMIN_RECEIVER_TEST_CLASS); + + public static ComponentName getReceiverComponentName() { + return RECEIVER_COMPONENT_NAME; + } @Override public void onProfileProvisioningComplete(Context context, Intent intent) { @@ -49,19 +57,31 @@ filter.addAction(ByodHelperActivity.ACTION_QUERY_PROFILE_OWNER); filter.addAction(ByodHelperActivity.ACTION_REMOVE_PROFILE_OWNER); filter.addAction(ByodHelperActivity.ACTION_INSTALL_APK); + filter.addAction(ByodHelperActivity.ACTION_CHECK_INTENT_FILTERS); filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_IMAGE); filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_VIDEO); filter.addAction(ByodHelperActivity.ACTION_CAPTURE_AND_CHECK_AUDIO); + filter.addAction(ByodHelperActivity.ACTION_KEYGUARD_DISABLED_FEATURES); + filter.addAction(ByodHelperActivity.ACTION_LOCKNOW); filter.addAction(ByodHelperActivity.ACTION_TEST_NFC_BEAM); - filter.addAction(CrossProfileTestActivity.ACTION_CROSS_PROFILE); + filter.addAction(ByodHelperActivity.ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG); + filter.addAction(ByodHelperActivity.ACTION_TEST_APP_LINKING_DIALOG); + filter.addAction(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_WORK); filter.addAction(WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION); + filter.addAction(WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION_ON_LOCKSCREEN); filter.addAction(WorkNotificationTestActivity.ACTION_CLEAR_WORK_NOTIFICATION); + filter.addAction(WorkStatusTestActivity.ACTION_WORK_STATUS_TOAST); + filter.addAction(WorkStatusTestActivity.ACTION_WORK_STATUS_ICON); + filter.addAction( + PermissionLockdownTestActivity.ACTION_MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN); + filter.addAction(AuthenticationBoundKeyTestActivity.ACTION_AUTH_BOUND_KEY_TEST); dpm.addCrossProfileIntentFilter(getWho(context), filter, DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT); // Work -> primary direction filter = new IntentFilter(); filter.addAction(ByodHelperActivity.ACTION_PROFILE_OWNER_STATUS); + filter.addAction(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL); dpm.addCrossProfileIntentFilter(getWho(context), filter, DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java new file mode 100644 index 0000000..c7e785c --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java
@@ -0,0 +1,92 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.content.Intent; +import android.database.DataSetObserver; +import android.os.Bundle; + +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.IntentDrivenTestActivity; +import com.android.cts.verifier.IntentDrivenTestActivity.ButtonInfo; +import com.android.cts.verifier.IntentDrivenTestActivity.TestInfo; +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.TestListAdapter.TestListItem; + +/** + * Activity that lists all device owner negative tests. + */ +public class DeviceOwnerNegativeTestActivity extends PassFailButtons.TestListActivity { + + private static final String ACTION_PROVISION_MANAGED_DEVICE + = "com.android.managedprovisioning.ACTION_PROVISION_MANAGED_DEVICE"; + private static final Intent PROVISION_DEVICE_INTENT = + new Intent(ACTION_PROVISION_MANAGED_DEVICE); + + private static final String DEVICE_OWNER_NEGATIVE_TEST = "DEVICE_OWNER_PROVISIONING_NEGATIVE"; + private static final TestInfo DEVICE_OWNER_NEGATIVE_TEST_INFO = new TestInfo( + DEVICE_OWNER_NEGATIVE_TEST, + R.string.device_owner_negative_test, + R.string.device_owner_negative_test_info, + new ButtonInfo( + R.string.start_device_owner_provisioning_button, + PROVISION_DEVICE_INTENT)); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.pass_fail_list); + setInfoResources(R.string.device_owner_provisioning_tests, + R.string.device_owner_provisioning_tests_info, 0); + setPassFailButtonClickListeners(); + + final ArrayTestListAdapter adapter = new ArrayTestListAdapter(this); + adapter.add(TestListItem.newCategory(this, R.string.device_owner_provisioning_category)); + + Intent startTestIntent = new Intent(this, IntentDrivenTestActivity.class) + .putExtra(IntentDrivenTestActivity.EXTRA_ID, + DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId()) + .putExtra(IntentDrivenTestActivity.EXTRA_TITLE, + DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle()) + .putExtra(IntentDrivenTestActivity.EXTRA_INFO, + DEVICE_OWNER_NEGATIVE_TEST_INFO.getInfoText()) + .putExtra(IntentDrivenTestActivity.EXTRA_BUTTONS, + DEVICE_OWNER_NEGATIVE_TEST_INFO.getButtons()); + + + adapter.add(TestListItem.newTest(this, DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle(), + DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId(), startTestIntent, null)); + + adapter.registerDataSetObserver(new DataSetObserver() { + @Override + public void onChanged() { + updatePassButton(); + } + }); + + setTestListAdapter(adapter); + } + + /** + * Enable Pass Button when the all tests passed. + */ + private void updatePassButton() { + getPassButton().setEnabled(mAdapter.allTestsPassed()); + } +} +
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java new file mode 100644 index 0000000..a6a5e5a --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -0,0 +1,333 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.database.DataSetObserver; +import android.os.Bundle; +import android.os.UserManager; +import android.provider.Settings; +import android.util.Log; +import android.view.View; +import android.view.View.OnClickListener; + +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.IntentDrivenTestActivity; +import com.android.cts.verifier.IntentDrivenTestActivity.ButtonInfo; +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.TestListAdapter.TestListItem; +import com.android.cts.verifier.TestResult; + +/** + * Activity that lists all positive device owner tests. Requires the following adb command be issued + * by the user prior to starting the tests: + * + * adb shell dpm set-device-owner + * 'com.android.cts.verifier/com.android.cts.verifier.managedprovisioning.DeviceAdminTestReceiver' + */ +public class DeviceOwnerPositiveTestActivity extends PassFailButtons.TestListActivity { + private static final String TAG = "DeviceOwnerPositiveTestActivity"; + + static final String EXTRA_COMMAND = "extra-command"; + static final String EXTRA_TEST_ID = "extra-test-id"; + static final String COMMAND_SET_POLICY = "set-policy"; + static final String EXTRA_POLICY = "extra-policy"; + static final String EXTRA_PARAMETER_1 = "extra_parameter_1"; + static final String EXTRA_PARAMETER_2 = "extra_parameter_2"; + static final String COMMAND_ADD_USER_RESTRICTION = "add-user-restriction"; + static final String COMMAND_CLEAR_USER_RESTRICTION = "clear-user-restriction"; + static final String EXTRA_RESTRICTION = "extra-restriction"; + static final String COMMAND_TEAR_DOWN = "tear-down"; + static final String COMMAND_CHECK_DEVICE_OWNER = "check-device-owner"; + static final String COMMAND_SET_GLOBAL_SETTING = "set-global-setting"; + static final String COMMAND_SET_STATUSBAR_DISABLED = "set-statusbar-disabled"; + static final String COMMAND_SET_KEYGUARD_DISABLED = "set-keyguard-disabled"; + static final String COMMAND_CHECK_PERMISSION_LOCKDOWN = "check-permission-lockdown"; + static final String EXTRA_SETTING = "extra-setting"; + + private static final String CHECK_DEVICE_OWNER_TEST_ID = "CHECK_DEVICE_OWNER"; + private static final String DEVICE_ADMIN_SETTINGS_ID = "DEVICE_ADMIN_SETTINGS"; + private static final String WIFI_LOCKDOWN_TEST_ID = WifiLockdownTestActivity.class.getName(); + private static final String DISABLE_STATUS_BAR_TEST_ID = "DISABLE_STATUS_BAR"; + private static final String DISABLE_KEYGUARD_TEST_ID = "DISABLE_KEYGUARD"; + private static final String CHECK_PERMISSION_LOCKDOWN_TEST_ID = + PermissionLockdownTestActivity.class.getName(); + private static final String DISALLOW_CONFIG_BT_ID = "DISALLOW_CONFIG_BT"; + private static final String DISALLOW_CONFIG_WIFI_ID = "DISALLOW_CONFIG_WIFI"; + private static final String REMOVE_DEVICE_OWNER_TEST_ID = "REMOVE_DEVICE_OWNER"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.positive_device_owner); + setInfoResources(R.string.device_owner_positive_tests, + R.string.device_owner_positive_tests_info, 0); + setPassFailButtonClickListeners(); + + final ArrayTestListAdapter adapter = new ArrayTestListAdapter(this); + adapter.add(TestListItem.newCategory(this, R.string.device_owner_positive_category)); + + addTestsToAdapter(adapter); + + adapter.registerDataSetObserver(new DataSetObserver() { + @Override + public void onChanged() { + updatePassButton(); + } + }); + + setTestListAdapter(adapter); + + View setDeviceOwnerButton = findViewById(R.id.set_device_owner_button); + setDeviceOwnerButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + new AlertDialog.Builder( + DeviceOwnerPositiveTestActivity.this) + .setIcon(android.R.drawable.ic_dialog_info) + .setTitle(R.string.set_device_owner_dialog_title) + .setMessage(R.string.set_device_owner_dialog_text) + .setPositiveButton(android.R.string.ok, null) + .show(); + } + }); + + } + + @Override + public void finish() { + // Pass and fail buttons are known to call finish() when clicked, and this is when we want + // to remove the device owner. + startActivity(createTearDownIntent()); + super.finish(); + } + + /** + * Enable Pass Button when all tests passed. + */ + private void updatePassButton() { + getPassButton().setEnabled(mAdapter.allTestsPassed()); + } + + private void addTestsToAdapter(final ArrayTestListAdapter adapter) { + adapter.add(createTestItem(this, CHECK_DEVICE_OWNER_TEST_ID, + R.string.device_owner_check_device_owner_test, + new Intent(this, CommandReceiver.class) + .putExtra(EXTRA_COMMAND, COMMAND_CHECK_DEVICE_OWNER) + )); + + // device admin settings + adapter.add(createInteractiveTestItem(this, DEVICE_ADMIN_SETTINGS_ID, + R.string.device_owner_device_admin_visible, + R.string.device_owner_device_admin_visible_info, + new ButtonInfo( + R.string.device_owner_settings_go, + new Intent(Settings.ACTION_SECURITY_SETTINGS)))); + + PackageManager packageManager = getPackageManager(); + if (packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) { + // WiFi Lock down tests + adapter.add(createTestItem(this, WIFI_LOCKDOWN_TEST_ID, + R.string.device_owner_wifi_lockdown_test, + new Intent(this, WifiLockdownTestActivity.class))); + + // DISALLOW_CONFIG_WIFI + adapter.add(createInteractiveTestItem(this, DISALLOW_CONFIG_WIFI_ID, + R.string.device_owner_disallow_config_wifi, + R.string.device_owner_disallow_config_wifi_info, + new ButtonInfo[] { + new ButtonInfo( + R.string.device_owner_user_restriction_set, + createSetUserRestrictionIntent( + UserManager.DISALLOW_CONFIG_WIFI)), + new ButtonInfo( + R.string.device_owner_settings_go, + new Intent(Settings.ACTION_WIFI_SETTINGS))})); + } + + // DISALLOW_CONFIG_BLUETOOTH + if (packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { + adapter.add(createInteractiveTestItem(this, DISALLOW_CONFIG_BT_ID, + R.string.device_owner_disallow_config_bt, + R.string.device_owner_disallow_config_bt_info, + new ButtonInfo[] { + new ButtonInfo( + R.string.device_owner_user_restriction_set, + createSetUserRestrictionIntent( + UserManager.DISALLOW_CONFIG_BLUETOOTH)), + new ButtonInfo( + R.string.device_owner_settings_go, + new Intent(Settings.ACTION_BLUETOOTH_SETTINGS))})); + } + + // setStatusBarDisabled + adapter.add(createInteractiveTestItem(this, DISABLE_STATUS_BAR_TEST_ID, + R.string.device_owner_disable_statusbar_test, + R.string.device_owner_disable_statusbar_test_info, + new ButtonInfo[] { + new ButtonInfo( + R.string.device_owner_disable_statusbar_button, + createDeviceOwnerIntentWithBooleanParameter( + COMMAND_SET_STATUSBAR_DISABLED, true)), + new ButtonInfo( + R.string.device_owner_reenable_statusbar_button, + createDeviceOwnerIntentWithBooleanParameter( + COMMAND_SET_STATUSBAR_DISABLED, false))})); + + // setKeyguardDisabled + adapter.add(createInteractiveTestItem(this, DISABLE_KEYGUARD_TEST_ID, + R.string.device_owner_disable_keyguard_test, + R.string.device_owner_disable_keyguard_test_info, + new ButtonInfo[] { + new ButtonInfo( + R.string.device_owner_disable_keyguard_button, + createDeviceOwnerIntentWithBooleanParameter( + COMMAND_SET_KEYGUARD_DISABLED, true)), + new ButtonInfo( + R.string.device_owner_reenable_keyguard_button, + createDeviceOwnerIntentWithBooleanParameter( + COMMAND_SET_KEYGUARD_DISABLED, false))})); + + // setPermissionGrantState + adapter.add(createTestItem(this, CHECK_PERMISSION_LOCKDOWN_TEST_ID, + R.string.device_profile_owner_permission_lockdown_test, + new Intent(PermissionLockdownTestActivity.ACTION_CHECK_PERMISSION_LOCKDOWN))); + + // removeDeviceOwner + adapter.add(createInteractiveTestItem(this, REMOVE_DEVICE_OWNER_TEST_ID, + R.string.device_owner_remove_device_owner_test, + R.string.device_owner_remove_device_owner_test_info, + new ButtonInfo( + R.string.remove_device_owner_button, + createTearDownIntent()))); + } + + static TestListItem createInteractiveTestItem(Activity activity, String id, int titleRes, + int infoRes, ButtonInfo buttonInfo) { + return createInteractiveTestItem(activity, id, titleRes, infoRes, + new ButtonInfo[] { buttonInfo }); + } + + static TestListItem createInteractiveTestItem(Activity activity, String id, int titleRes, + int infoRes, ButtonInfo[] buttonInfos) { + return TestListItem.newTest(activity, titleRes, + id, new Intent(activity, IntentDrivenTestActivity.class) + .putExtra(IntentDrivenTestActivity.EXTRA_ID, id) + .putExtra(IntentDrivenTestActivity.EXTRA_TITLE, titleRes) + .putExtra(IntentDrivenTestActivity.EXTRA_INFO, infoRes) + .putExtra(IntentDrivenTestActivity.EXTRA_BUTTONS, buttonInfos), + null); + } + + static TestListItem createTestItem(Activity activity, String id, int titleRes, + Intent intent) { + return TestListItem.newTest(activity, titleRes, id, intent.putExtra(EXTRA_TEST_ID, id), + null); + } + + private Intent createTearDownIntent() { + return new Intent(this, CommandReceiver.class) + .putExtra(EXTRA_COMMAND, COMMAND_TEAR_DOWN); + } + + private Intent createDeviceOwnerIntentWithBooleanParameter(String command, boolean value) { + return new Intent(this, CommandReceiver.class) + .putExtra(EXTRA_COMMAND, command) + .putExtra(EXTRA_PARAMETER_1, value); + } + + private Intent createSetUserRestrictionIntent(String restriction) { + return new Intent(this, CommandReceiver.class) + .putExtra(EXTRA_COMMAND, COMMAND_ADD_USER_RESTRICTION) + .putExtra(EXTRA_RESTRICTION, restriction); + } + + public static class CommandReceiver extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = getIntent(); + String command = intent.getStringExtra(EXTRA_COMMAND); + try { + DevicePolicyManager dpm = (DevicePolicyManager) + getSystemService(Context.DEVICE_POLICY_SERVICE); + ComponentName admin = DeviceAdminTestReceiver.getReceiverComponentName(); + Log.i(TAG, "Command: " + command); + + if (COMMAND_ADD_USER_RESTRICTION.equals(command)) { + String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION); + dpm.addUserRestriction(admin, restrictionKey); + Log.i(TAG, "Added user restriction " + restrictionKey); + } else if (COMMAND_CLEAR_USER_RESTRICTION.equals(command)) { + String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION); + dpm.clearUserRestriction(admin, restrictionKey); + Log.i(TAG, "Cleared user restriction " + restrictionKey); + } else if (COMMAND_TEAR_DOWN.equals(command)) { + tearDown(dpm, admin); + } else if (COMMAND_SET_GLOBAL_SETTING.equals(command)) { + final String setting = intent.getStringExtra(EXTRA_SETTING); + final String value = intent.getStringExtra(EXTRA_PARAMETER_1); + dpm.setGlobalSetting(admin, setting, value); + } else if (COMMAND_SET_STATUSBAR_DISABLED.equals(command)) { + final boolean value = intent.getBooleanExtra(EXTRA_PARAMETER_1, false); + dpm.setStatusBarDisabled(admin, value); + } else if (COMMAND_SET_KEYGUARD_DISABLED.equals(command)) { + final boolean value = intent.getBooleanExtra(EXTRA_PARAMETER_1, false); + if (value) { + dpm.resetPassword(null, 0); + } + dpm.setKeyguardDisabled(admin, value); + } else if (COMMAND_CHECK_DEVICE_OWNER.equals(command)) { + if (dpm.isDeviceOwnerApp(getPackageName())) { + TestResult.setPassedResult(this, intent.getStringExtra(EXTRA_TEST_ID), + null, null); + } else { + TestResult.setFailedResult(this, intent.getStringExtra(EXTRA_TEST_ID), + getString(R.string.device_owner_incorrect_device_owner), null); + } + } else { + Log.e(TAG, "Invalid command: " + command); + } + } catch (Exception e) { + Log.e(TAG, "Command " + command + " failed with exception " + e); + } finally { + // No matter what happened, don't let the activity run + finish(); + } + } + + private void tearDown(DevicePolicyManager dpm, ComponentName admin) { + if (dpm == null || !dpm.isDeviceOwnerApp(getPackageName())) { + return; + } + + dpm.setStatusBarDisabled(admin, false); + dpm.setKeyguardDisabled(admin, false); + dpm.clearUserRestriction(admin, UserManager.DISALLOW_CONFIG_BLUETOOTH); + dpm.clearUserRestriction(admin, UserManager.DISALLOW_CONFIG_WIFI); + dpm.clearDeviceOwnerApp(getPackageName()); + } + } +} +
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java deleted file mode 100644 index 7cb3825..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerTestActivity.java +++ /dev/null
@@ -1,93 +0,0 @@ -package com.android.cts.verifier.managedprovisioning; - -import android.app.AlertDialog; -import android.app.admin.DevicePolicyManager; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.database.DataSetObserver; -import android.os.Bundle; -import android.provider.Settings; -import android.util.Log; -import android.view.View; -import android.view.ViewGroup; -import android.view.View.OnClickListener; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - -import com.android.cts.verifier.ArrayTestListAdapter; -import com.android.cts.verifier.IntentDrivenTestActivity; -import com.android.cts.verifier.IntentDrivenTestActivity.ButtonInfo; -import com.android.cts.verifier.IntentDrivenTestActivity.TestInfo; -import com.android.cts.verifier.PassFailButtons; -import com.android.cts.verifier.R; -import com.android.cts.verifier.TestListAdapter.TestListItem; - -import java.util.ArrayList; -import java.util.List; - -/** - * Activity that lists all device owner provisioning tests. - */ -public class DeviceOwnerTestActivity extends PassFailButtons.TestListActivity { - - private static final String ACTION_PROVISION_MANAGED_DEVICE - = "com.android.managedprovisioning.ACTION_PROVISION_MANAGED_DEVICE"; - private static final Intent PROVISION_DEVICE_INTENT = - new Intent(ACTION_PROVISION_MANAGED_DEVICE); - - private static final String DEVICE_OWNER_NEGATIVE_TEST = "DEVICE_OWNER_PROVISIONING_NEGATIVE"; - private static final TestInfo DEVICE_OWNER_NEGATIVE_TEST_INFO = new TestInfo( - DEVICE_OWNER_NEGATIVE_TEST, - R.string.device_owner_negative_test, - R.string.device_owner_negative_test_info, - new ButtonInfo( - R.string.start_device_owner_provisioning_button, - PROVISION_DEVICE_INTENT)); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.pass_fail_list); - setInfoResources(R.string.device_owner_provisioning_tests, - R.string.device_owner_provisioning_tests_info, 0); - setPassFailButtonClickListeners(); - - final ArrayTestListAdapter adapter = new ArrayTestListAdapter(this); - adapter.add(TestListItem.newCategory(this, R.string.device_owner_provisioning_category)); - - Intent startTestIntent = new Intent(this, IntentDrivenTestActivity.class) - .putExtra(IntentDrivenTestActivity.EXTRA_ID, - DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId()) - .putExtra(IntentDrivenTestActivity.EXTRA_TITLE, - DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle()) - .putExtra(IntentDrivenTestActivity.EXTRA_INFO, - DEVICE_OWNER_NEGATIVE_TEST_INFO.getInfoText()) - .putExtra(IntentDrivenTestActivity.EXTRA_BUTTONS, - DEVICE_OWNER_NEGATIVE_TEST_INFO.getButtons()); - - - adapter.add(TestListItem.newTest(this, DEVICE_OWNER_NEGATIVE_TEST_INFO.getTitle(), - DEVICE_OWNER_NEGATIVE_TEST_INFO.getTestId(), startTestIntent, null)); - - adapter.registerDataSetObserver(new DataSetObserver() { - @Override - public void onChanged() { - updatePassButton(); - } - }); - - setTestListAdapter(adapter); - } - - /** - * Enable Pass Button when the all tests passed. - */ - private void updatePassButton() { - getPassButton().setEnabled(mAdapter.allTestsPassed()); - } -} -
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java new file mode 100644 index 0000000..eef6299 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
@@ -0,0 +1,382 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.app.Activity; +import android.app.admin.DevicePolicyManager; +import android.app.DownloadManager; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.media.audiofx.AudioEffect; +import android.net.Uri; +import android.nfc.cardemulation.CardEmulation; +import android.os.Bundle; +import android.os.Environment; +import android.os.UserHandle; +import android.provider.AlarmClock; +import android.provider.CalendarContract.Events; +import android.provider.MediaStore; +import android.provider.Settings; +import android.speech.RecognizerIntent; +import android.util.Log; +import android.widget.Toast; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; + +/** + * Helper class for testing if the required cross profile intent filters are set during the + * managed provisioning. + */ +public class IntentFiltersTestHelper { + + private static final String TAG = "IntentFiltersTestHelper"; + + // These are the intents which can be forwarded to the managed profile. + private static final ArrayList<Intent> forwardedIntentsFromPrimary = + new ArrayList<>(Arrays.asList( + new Intent(Intent.ACTION_SEND).setType("*/*"), + new Intent(Intent.ACTION_SEND_MULTIPLE).setType("*/*") + )); + + // These are the intents which can be forwarded to the primary profile. + private static final ArrayList<Intent> forwardedIntentsFromManaged = + new ArrayList<>(Arrays.asList( + new Intent(AlarmClock.ACTION_SET_ALARM), + new Intent(AlarmClock.ACTION_SET_TIMER), + new Intent(AlarmClock.ACTION_SHOW_ALARMS), + new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), + new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS), + new Intent(Settings.ACTION_CAPTIONING_SETTINGS), + new Intent(Settings.ACTION_DATE_SETTINGS), + new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS), + new Intent(Settings.ACTION_DISPLAY_SETTINGS), + new Intent(Settings.ACTION_LOCALE_SETTINGS), + new Intent(Settings.ACTION_PRIVACY_SETTINGS), + new Intent(Settings.ACTION_SETTINGS), + new Intent(Settings.ACTION_WIRELESS_SETTINGS), + new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD), + new Intent("android.net.vpn.SETTINGS"), + new Intent("android.settings.ACCOUNT_SYNC_SETTINGS"), + new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS), + new Intent("android.settings.LICENSE"), + new Intent("android.settings.NOTIFICATION_SETTINGS"), + new Intent("android.settings.USER_SETTINGS"), + new Intent("android.settings.ZEN_MODE_SETTINGS"), + new Intent("com.android.settings.ACCESSIBILITY_COLOR_SPACE_SETTINGS"), + new Intent("com.android.settings.STORAGE_USB_SETTINGS"), + new Intent("com.android.settings.TTS_SETTINGS"), + new Intent("com.android.settings.USER_DICTIONARY_EDIT"), + new Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS), + new Intent(Settings.ACTION_SYNC_SETTINGS), + new Intent(Settings.ACTION_ADD_ACCOUNT), + new Intent(Intent.ACTION_GET_CONTENT).setType("*/*").addCategory( + Intent.CATEGORY_OPENABLE), + new Intent(Intent.ACTION_OPEN_DOCUMENT).setType("*/*").addCategory( + Intent.CATEGORY_OPENABLE), + new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS), + new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS), + new Intent(Settings.ACTION_APPLICATION_SETTINGS) + )); + + // These are the intents which cannot be forwarded to the primary profile. + private static final ArrayList<Intent> notForwardedIntentsFromManaged = + new ArrayList<>(Arrays.asList( + new Intent(Intent.ACTION_INSERT).setData( + Uri.parse("content://browser/bookmarks")), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("http://www.example.com")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_SENDTO).setData( + Uri.parse("mailto:user@example.com")), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("mailto:user@example.com")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("geo:0,0?q=BuckinghamPalace")), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("http://example.com/oceans.mp4")).setType("video/mp4"), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("http://www.example.com/horse.mp3")).setType("audio/*"), + new Intent(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("market://details?id=com.android.chrome")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_WEB_SEARCH), + new Intent(Settings.ACTION_SEARCH_SETTINGS), + new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE), + new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData( + Uri.parse("package:com.android.chrome")), + new Intent(Intent.ACTION_INSERT).setData(Events.CONTENT_URI), + new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS) + )); + + // This flag specifies we are dealing with intents fired from the primary profile. + public static final int FLAG_INTENTS_FROM_PRIMARY = 1; + // This flag specifies we are dealing with intents fired from the managed profile. + public static final int FLAG_INTENTS_FROM_MANAGED = 2; + + private Context mContext; + + IntentFiltersTestHelper(Context context) { + mContext = context; + + addIntentsThatDependOnDeviceFeatures(); + } + + private void addIntentsThatDependOnDeviceFeatures() { + PackageManager pm = mContext.getPackageManager(); + + if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:123")), + new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:123")), + new Intent("android.intent.action.CALL_EMERGENCY").setData( + Uri.parse("tel:123")), + new Intent("android.intent.action.CALL_PRIVILEGED").setData( + Uri.parse("tel:123")), + new Intent(Intent.ACTION_VIEW).setData(Uri.parse("tel:123")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS), + new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS), + new Intent(Intent.ACTION_SENDTO).setData(Uri.parse("sms:07700900100")), + new Intent(Intent.ACTION_SENDTO).setData(Uri.parse("smsto:07700900100")), + new Intent(Intent.ACTION_SENDTO).setData(Uri.parse("mms:07700900100")), + new Intent(Intent.ACTION_SENDTO).setData(Uri.parse("mmsto:07700900100")), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("sms:07700900100?body=Hello%20world")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("smsto:07700900100?body=Hello%20world")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("mms:07700900100?body=Hello%20world")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Intent.ACTION_VIEW).setData( + Uri.parse("mmsto:07700900100?body=Hello%20world")).addCategory( + Intent.CATEGORY_BROWSABLE), + new Intent(Settings.ACTION_APN_SETTINGS))); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_NFC)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(Settings.ACTION_NFC_SETTINGS), + new Intent(Settings.ACTION_NFCSHARING_SETTINGS), + new Intent(Settings.ACTION_NFC_PAYMENT_SETTINGS))); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) { + forwardedIntentsFromManaged.add( + new Intent(CardEmulation.ACTION_CHANGE_DEFAULT)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(MediaStore.ACTION_IMAGE_CAPTURE), + new Intent(MediaStore.ACTION_VIDEO_CAPTURE), + new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA), + new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA), + new Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE), + new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE))); + } + + final String state = Environment.getExternalStorageState(); + if (Environment.MEDIA_MOUNTED.equals(state)) { + forwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_MEMORY_CARD_SETTINGS)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_WIFI)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(Settings.ACTION_WIFI_IP_SETTINGS), + new Intent(Settings.ACTION_WIFI_SETTINGS))); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION), + new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH))); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_LOCATION)) { + forwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(Settings.ACTION_SOUND_SETTINGS), + new Intent("android.settings.ACTION_OTHER_SOUND_SETTINGS"))); + notForwardedIntentsFromManaged.add( + new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_HOME_SCREEN)) { + forwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_HOME_SETTINGS)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_INPUT_METHODS)) { + forwardedIntentsFromManaged.addAll(Arrays.asList( + new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), + new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS))); + notForwardedIntentsFromManaged.add( + new Intent("android.settings.SHOW_INPUT_METHOD_PICKER")); + } + + if (!pm.hasSystemFeature(PackageManager.FEATURE_WATCH)) { + forwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_DREAM_SETTINGS)); + } + + if (!pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { + forwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS)); + } + + if (pm.hasSystemFeature(PackageManager.FEATURE_PRINTING)) { + notForwardedIntentsFromManaged.add( + new Intent(Settings.ACTION_PRINT_SETTINGS)); + } + } + + public boolean checkCrossProfileIntentFilters(int flag) { + boolean crossProfileIntentFiltersSet; + if (flag == FLAG_INTENTS_FROM_PRIMARY) { + crossProfileIntentFiltersSet = checkForIntentsFromPrimary(); + } else { + crossProfileIntentFiltersSet = checkForIntentsFromManaged(); + } + return crossProfileIntentFiltersSet; + } + + /** + * Checks if required cross profile intent filters are set for the intents fired from the + * primary profile. + */ + private boolean checkForIntentsFromPrimary() { + // Get the class name of the intentForwarderActivity in the primary profile by firing an + // intent which we know will be forwarded from primary profile to managed profile. + ActivityInfo forwarderActivityInfo = + getForwarderActivityInfo(ByodHelperActivity.ACTION_QUERY_PROFILE_OWNER); + if (forwarderActivityInfo == null) { + return false; + } + + // Check for intents which can be forwarded to the managed profile. + Intent intent = checkForIntentsNotHandled(forwardedIntentsFromPrimary, + forwarderActivityInfo, true); + if (intent != null) { + Log.d(TAG, intent + " from primary profile should be forwarded to the " + + "managed profile but is not."); + return false; + } + + return true; + } + + /** + * Checks if required cross profile intent filters are set for the intents fired from the + * managed profile. + */ + private boolean checkForIntentsFromManaged() { + // Get the class name of the intentForwarderActivity in the managed profile by firing an + // intent which we know will be forwarded from managed profile to primary profile. + ActivityInfo forwarderActivityInfo = + getForwarderActivityInfo(ByodHelperActivity.ACTION_PROFILE_OWNER_STATUS); + if (forwarderActivityInfo == null) { + return false; + } + + // Check for intents which can be forwarded to the primary profile. + Intent intent = checkForIntentsNotHandled(forwardedIntentsFromManaged, + forwarderActivityInfo, true); + if (intent != null) { + Log.d(TAG, intent + " from managed profile should be forwarded to the " + + "primary profile but is not."); + return false; + } + + // Check for intents which cannot be forwarded to the primary profile. + intent = checkForIntentsNotHandled(notForwardedIntentsFromManaged, + forwarderActivityInfo, false); + if (intent != null) { + Log.d(TAG, intent + " from managed profile should not be forwarded to the " + + "primary profile but it is."); + return false; + } + + return true; + } + + /** + * Checks if the intentForwarderActivity can handle the intent passed. + */ + private boolean canForwarderActivityHandleIntent(Intent intent, + ActivityInfo forwarderActivityInfo) { + // Get all the activities which can handle the intent. + List<ResolveInfo> resolveInfoList = + mContext.getPackageManager().queryIntentActivities(intent, + PackageManager.MATCH_DEFAULT_ONLY); + // Check if intentForwarderActivity is part of the list. + for (ResolveInfo resolveInfo : resolveInfoList) { + if (forwarderActivityInfo.packageName.equals(resolveInfo.activityInfo.packageName) + && forwarderActivityInfo.name.equals(resolveInfo.activityInfo.name)) { + return true; + } + } + return false; + } + + /** + * Returns the class name of the intentForwarderActivity. + */ + private ActivityInfo getForwarderActivityInfo(String action) { + Intent intent = new Intent(action); + List<ResolveInfo> resolveInfoList = + mContext.getPackageManager().queryIntentActivities(intent, + PackageManager.MATCH_DEFAULT_ONLY); + if (resolveInfoList.isEmpty() || resolveInfoList.size() > 1) { + Log.d(TAG, "There should be exactly one activity IntentForwarder which " + + "handles the intent " + intent); + return null; + } + return resolveInfoList.get(0).activityInfo; + } + + /** + * Checks if the intents passed are correctly handled. + * @return {@code null} if all the intents are correctly handled + * otherwise, the first intent in the list which is not handled correctly. + */ + private Intent checkForIntentsNotHandled(ArrayList<Intent> intentList, + ActivityInfo expectedForwarderActivityInfo, boolean canResolve) { + for (Intent intent : intentList) { + if (canForwarderActivityHandleIntent(intent, + expectedForwarderActivityInfo) != canResolve) { + return intent; + } + } + return null; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java new file mode 100644 index 0000000..1a158f8 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java
@@ -0,0 +1,129 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.app.admin.DevicePolicyManager; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.hardware.fingerprint.FingerprintManager; +import android.os.Bundle; +import android.provider.Settings; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Toast; + +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.DialogTestListActivity; +import com.android.cts.verifier.R; + +public class KeyguardDisabledFeaturesActivity extends DialogTestListActivity { + + private DevicePolicyManager mDpm; + + public KeyguardDisabledFeaturesActivity() { + super(R.layout.provisioning_byod, + R.string.provisioning_byod_keyguard_disabled_features, + R.string.provisioning_byod_keyguard_disabled_features_info, + R.string.provisioning_byod_keyguard_disabled_features_instruction); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); + + mPrepareTestButton.setText( + R.string.provisioning_byod_keyguard_disabled_features_prepare_button); + mPrepareTestButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (!mDpm.isAdminActive(DeviceAdminTestReceiver.getReceiverComponentName())) { + Toast.makeText(KeyguardDisabledFeaturesActivity.this, + R.string.provisioning_byod_keyguard_disabled_features_not_admin, + Toast.LENGTH_SHORT).show(); + return; + } + mDpm.resetPassword("testpassword", 0); + setKeyguardDisabledFeatures(DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS | + DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT | + DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS); + } + }); + } + + @Override + public void finish() { + // Pass and fail buttons are known to call finish() when clicked, and this is when we want to + // clear the password. + final ComponentName adminComponent = DeviceAdminTestReceiver.getReceiverComponentName(); + if (mDpm.isAdminActive(adminComponent)) { + mDpm.resetPassword(null, 0); + mDpm.removeActiveAdmin(adminComponent); + } + super.finish(); + } + + private void setKeyguardDisabledFeatures(final int flags) { + Intent setKeyguardDisabledFeaturesIntent = + new Intent(ByodHelperActivity.ACTION_KEYGUARD_DISABLED_FEATURES) + .putExtra(ByodHelperActivity.EXTRA_PARAMETER_1, flags); + startActivity(setKeyguardDisabledFeaturesIntent); + } + + @Override + protected void setupTests(ArrayTestListAdapter adapter) { + adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_disable_trust_agents, + "BYOD_DisableTrustAgentsTest", + R.string.provisioning_byod_disable_trust_agents_instruction, + new Intent(Settings.ACTION_SECURITY_SETTINGS))); + adapter.add(new DialogTestListItemWithIcon(this, + R.string.provisioning_byod_disable_notifications, + "BYOD_DisableUnredactedNotifications", + R.string.provisioning_byod_disable_notifications_instruction, + new Intent(WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION_ON_LOCKSCREEN), + R.drawable.ic_corp_icon)); + FingerprintManager fpm = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE); + if (fpm.isHardwareDetected()) { + adapter.add(new DialogTestListItem(this, + R.string.provisioning_byod_fingerprint_disabled_in_settings, + "BYOD_FingerprintDisabledInSettings", + R.string.provisioning_byod_fingerprint_disabled_in_settings_instruction, + new Intent(Settings.ACTION_SECURITY_SETTINGS))); + adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_disable_fingerprint, + "BYOD_DisableFingerprint", + R.string.provisioning_byod_disable_fingerprint_instruction, + ByodHelperActivity.createLockIntent())); + } + } + + @Override + protected void clearRemainingState(final DialogTestListItem test) { + super.clearRemainingState(test); + if (WorkNotificationTestActivity.ACTION_WORK_NOTIFICATION_ON_LOCKSCREEN.equals( + test.getManualTestIntent().getAction())) { + try { + startActivity(new Intent( + WorkNotificationTestActivity.ACTION_CLEAR_WORK_NOTIFICATION)); + } catch (ActivityNotFoundException e) { + // User shouldn't run this test before work profile is set up. + } + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java new file mode 100644 index 0000000..ea7e801 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java
@@ -0,0 +1,195 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.app.admin.DevicePolicyManager; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import android.provider.Settings; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.RadioGroup; +import android.widget.TextView; +import android.widget.Toast; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +public class PermissionLockdownTestActivity extends PassFailButtons.Activity + implements RadioGroup.OnCheckedChangeListener { + private static final String PERMISSION_APP_PACKAGE = "com.android.cts.permissionapp"; + + // Alias used for starting the activity from ByodFlowTestActivity (Managed profile tests). + static final String ACTIVITY_ALIAS + = "com.android.cts.verifier.managedprovisioning" + + ".ManagedProfilePermissionLockdownTestActivity"; + + private static final String MANAGED_PROVISIONING_ACTION_PREFIX + = "com.android.cts.verifier.managedprovisioning.action."; + // Indicates that activity is started for device owner case. + static final String ACTION_CHECK_PERMISSION_LOCKDOWN + = MANAGED_PROVISIONING_ACTION_PREFIX + "CHECK_PERMISSION_LOCKDOWN"; + // Indicates that activity is started for profile owner case. + static final String ACTION_MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN + = MANAGED_PROVISIONING_ACTION_PREFIX + "MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN"; + + // Permission grant states will be set on this permission. + private static final String CONTACTS_PERMISSION = android.Manifest.permission.READ_CONTACTS; + + private boolean mDeviceOwnerTest; + private DevicePolicyManager mDevicePolicyManager; + private ComponentName mAdmin; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.permission_lockdown); + + mDevicePolicyManager = + (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); + mAdmin = DeviceAdminTestReceiver.getReceiverComponentName(); + + mDeviceOwnerTest = + ACTION_CHECK_PERMISSION_LOCKDOWN.equals(getIntent().getAction()) ? true : false; + // Return immediately if we are neither profile nor device owner. + if (!isProfileOrDeviceOwner()) { + setTestResultAndFinish(false); + return; + } + + buildLayout(); + } + + private void buildLayout() { + PackageManager packageManager = getPackageManager(); + ApplicationInfo applicationInfo = null; + try { + // We need to make sure that the CtsPermissionApp is installed on the device or + // work profile. + applicationInfo = packageManager.getApplicationInfo( + PERMISSION_APP_PACKAGE, 0 /* flags */); + } catch (PackageManager.NameNotFoundException e) { + showToast(getString(R.string.package_not_found, PERMISSION_APP_PACKAGE)); + setTestResultAndFinish(false); + return; + } + + ImageView packageIconImageView = (ImageView) findViewById(R.id.package_icon); + packageIconImageView.setImageDrawable(packageManager.getApplicationIcon(applicationInfo)); + TextView packageNameTextView = (TextView) findViewById(R.id.package_name); + packageNameTextView.setText(packageManager.getApplicationLabel(applicationInfo)); + + TextView permissionNameTextView = (TextView) findViewById(R.id.permission_name); + permissionNameTextView.setText(CONTACTS_PERMISSION); + + // Get the current permission grant state for initializing the RadioGroup. + int currentPermissionState = mDevicePolicyManager.getPermissionGrantState(mAdmin, + PERMISSION_APP_PACKAGE, CONTACTS_PERMISSION); + RadioGroup permissionRadioGroup = (RadioGroup) findViewById(R.id.permission_group); + switch (currentPermissionState) { + case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { + permissionRadioGroup.check(R.id.permission_allow); + } break; + case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { + permissionRadioGroup.check(R.id.permission_default); + } break; + case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { + permissionRadioGroup.check(R.id.permission_deny); + } break; + } + permissionRadioGroup.setOnCheckedChangeListener(this); + + addFinishOrPassFailButtons(); + } + + private void addFinishOrPassFailButtons() { + // In case of device owner, we include the pass-fail buttons where as in case of profile + // owner, we add a finish button. + ViewGroup parentView = (ViewGroup) findViewById(R.id.permission_lockdown_activity); + if (mDeviceOwnerTest) { + parentView.addView( + getLayoutInflater().inflate(R.layout.pass_fail_buttons, parentView, false)); + setInfoResources(R.string.device_profile_owner_permission_lockdown_test, + R.string.device_owner_permission_lockdown_test_info, 0); + setPassFailButtonClickListeners(); + } else { + Button finishButton = new Button(this); + finishButton.setText(R.string.finish_button_label); + finishButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + PermissionLockdownTestActivity.this.setTestResultAndFinish(false); + } + }); + parentView.addView(finishButton); + } + } + + // Dispatches an intent to open the Settings screen for CtsPermissionApp. + public void openSettings(View v) { + Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(Uri.fromParts("package", PERMISSION_APP_PACKAGE, null)) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + startActivity(intent); + } catch (ActivityNotFoundException e) { + showToast(getString(R.string.activity_not_found, intent)); + } + } + + @Override + public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { + int permissionGrantState = -1; + switch (checkedId) { + case R.id.permission_allow: { + permissionGrantState = DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED; + } break; + case R.id.permission_default: { + permissionGrantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; + } break; + case R.id.permission_deny: { + permissionGrantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; + } break; + } + mDevicePolicyManager.setPermissionGrantState(mAdmin, PERMISSION_APP_PACKAGE, + CONTACTS_PERMISSION, permissionGrantState); + } + + private boolean isProfileOrDeviceOwner() { + String adminPackage = mAdmin.getPackageName(); + if (mDeviceOwnerTest && !mDevicePolicyManager.isDeviceOwnerApp(adminPackage)) { + showToast(getString(R.string.not_device_owner, adminPackage)); + return false; + } else if (!mDeviceOwnerTest && !mDevicePolicyManager.isProfileOwnerApp(adminPackage)) { + showToast(getString(R.string.not_profile_owner, adminPackage)); + return false; + } + return true; + } + + private void showToast(String toast) { + Toast.makeText(this, toast, Toast.LENGTH_LONG).show(); + } +} \ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java new file mode 100644 index 0000000..4a292eb --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WifiLockdownTestActivity.java
@@ -0,0 +1,173 @@ +/* + * Copyright (C) 2015 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.managedprovisioning; + +import android.app.AlertDialog; +import android.content.Intent; +import android.database.DataSetObserver; +import android.os.Bundle; +import android.provider.Settings; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.EditText; +import android.widget.RadioGroup; + +import com.android.cts.verifier.ArrayTestListAdapter; +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; +import com.android.cts.verifier.IntentDrivenTestActivity.ButtonInfo; + +import com.android.compatibility.common.util.WifiConfigCreator; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_NONE; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_WPA; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_WEP; + +/** + * Activity to test WiFi configuration lockdown functionality. A locked down WiFi config + * must not be editable/forgettable in Settings. + */ +public class WifiLockdownTestActivity extends PassFailButtons.TestListActivity { + private static final String TAG = "WifiLockdownTestActivity"; + + private static final int NONE = R.id.device_owner_keymgmnt_none; + private static final int WPA = R.id.device_owner_keymgmnt_wpa; + private static final int WEP = R.id.device_owner_keymgmnt_wep; + + private static final String CONFIG_MODIFIABLE_WHEN_UNLOCKED_TEST_ID = "UNLOCKED_MODIFICATION"; + private static final String CONFIG_NOT_MODIFIABLE_WHEN_LOCKED_TEST_ID = "LOCKED_MODIFICATION"; + private static final String CONFIG_CONNECTABLE_WHEN_LOCKED_TEST_ID = "LOCKED_CONNECT"; + private static final String CONFIG_REMOVABLE_WHEN_UNLOCKED_TEST_ID = "UNLOCKED_REMOVE"; + + private WifiConfigCreator mConfigCreator; + private ButtonInfo[] mSwitchLockdownOffButtonInfos; + private ButtonInfo[] mSwitchLockdownOnButtonInfos; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mConfigCreator = new WifiConfigCreator(this); + setContentView(R.layout.wifi_lockdown); + setInfoResources(R.string.device_owner_wifi_lockdown_test, + R.string.device_owner_wifi_lockdown_info, 0); + setPassFailButtonClickListeners(); + + final ArrayTestListAdapter adapter = new ArrayTestListAdapter(this); + + final ButtonInfo goToWifiSettings = new ButtonInfo( + R.string.wifi_lockdown_go_settings_wifi_button, + new Intent(Settings.ACTION_WIFI_SETTINGS)); + mSwitchLockdownOffButtonInfos = new ButtonInfo[] { new ButtonInfo( + R.string.switch_wifi_lockdown_off_button, + new Intent(this, DeviceOwnerPositiveTestActivity.CommandReceiver.class) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_COMMAND, + DeviceOwnerPositiveTestActivity.COMMAND_SET_GLOBAL_SETTING) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_SETTING, + Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_PARAMETER_1, "0" + )), goToWifiSettings }; + mSwitchLockdownOnButtonInfos = new ButtonInfo[] { new ButtonInfo( + R.string.switch_wifi_lockdown_on_button, + new Intent(this, DeviceOwnerPositiveTestActivity.CommandReceiver.class) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_COMMAND, + DeviceOwnerPositiveTestActivity.COMMAND_SET_GLOBAL_SETTING) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_SETTING, + Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN) + .putExtra(DeviceOwnerPositiveTestActivity.EXTRA_PARAMETER_1, "1" + )), goToWifiSettings }; + + addTestsToAdapter(adapter); + + adapter.registerDataSetObserver(new DataSetObserver() { + @Override + public void onChanged() { + updatePassButton(); + } + }); + + setTestListAdapter(adapter); + + View createConfigButton = findViewById(R.id.create_wifi_config_button); + createConfigButton .setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + EditText ssidEditor = (EditText) findViewById(R.id.device_owner_wifi_ssid); + RadioGroup authMethods = (RadioGroup) findViewById( + R.id.device_owner_keyManagementMethods); + int checkedRadioId = authMethods.getCheckedRadioButtonId(); + if (checkedRadioId == -1) { + checkedRadioId = NONE; + } + int netId = mConfigCreator.addNetwork(ssidEditor.getText().toString(), false, + convertKeyManagement(checkedRadioId), "defaultpassword"); + if (netId == -1) { + new AlertDialog.Builder( + WifiLockdownTestActivity.this) + .setIcon(android.R.drawable.ic_dialog_info) + .setTitle(R.string.wifi_lockdown_add_network_failed_dialog_title) + .setMessage(R.string.wifi_lockdown_add_network_failed_dialog_text) + .setPositiveButton(android.R.string.ok, null) + .show(); + } + } + }); + } + + /** + * Enable Pass Button when all tests passed. + */ + private void updatePassButton() { + getPassButton().setEnabled(mAdapter.allTestsPassed()); + } + + private void addTestsToAdapter(final ArrayTestListAdapter adapter) { + adapter.add(DeviceOwnerPositiveTestActivity.createInteractiveTestItem(this, + CONFIG_MODIFIABLE_WHEN_UNLOCKED_TEST_ID, + R.string.device_owner_wifi_config_unlocked_modification_test, + R.string.device_owner_wifi_config_unlocked_modification_test_info, + mSwitchLockdownOffButtonInfos)); + adapter.add(DeviceOwnerPositiveTestActivity.createInteractiveTestItem(this, + CONFIG_NOT_MODIFIABLE_WHEN_LOCKED_TEST_ID, + R.string.device_owner_wifi_config_locked_modification_test, + R.string.device_owner_wifi_config_locked_modification_test_info, + mSwitchLockdownOnButtonInfos)); + adapter.add(DeviceOwnerPositiveTestActivity.createInteractiveTestItem(this, + CONFIG_CONNECTABLE_WHEN_LOCKED_TEST_ID, + R.string.device_owner_wifi_config_locked_connection_test, + R.string.device_owner_wifi_config_locked_connection_test_info, + mSwitchLockdownOnButtonInfos)); + adapter.add(DeviceOwnerPositiveTestActivity.createInteractiveTestItem(this, + CONFIG_REMOVABLE_WHEN_UNLOCKED_TEST_ID, + R.string.device_owner_wifi_config_unlocked_removal_test, + R.string.device_owner_wifi_config_unlocked_removal_test_info, + mSwitchLockdownOffButtonInfos)); + } + + private int convertKeyManagement(int radioButtonId) { + switch (radioButtonId) { + case NONE: { + return SECURITY_TYPE_NONE; + } + case WPA: { + return SECURITY_TYPE_WPA; + } + case WEP: { + return SECURITY_TYPE_WEP; + } + } + return SECURITY_TYPE_NONE; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkNotificationTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkNotificationTestActivity.java index c85ccf5..a912d2c 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkNotificationTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkNotificationTestActivity.java
@@ -19,7 +19,9 @@ import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; +import android.app.admin.DevicePolicyManager; import android.content.Context; +import android.content.Intent; import android.os.Bundle; import com.android.cts.verifier.R; @@ -30,26 +32,37 @@ public class WorkNotificationTestActivity extends Activity { public static final String ACTION_WORK_NOTIFICATION = "com.android.cts.verifier.managedprovisioning.WORK_NOTIFICATION"; + public static final String ACTION_WORK_NOTIFICATION_ON_LOCKSCREEN = + "com.android.cts.verifier.managedprovisioning.LOCKSCREEN_NOTIFICATION"; public static final String ACTION_CLEAR_WORK_NOTIFICATION = "com.android.cts.verifier.managedprovisioning.CLEAR_WORK_NOTIFICATION"; private static final int NOTIFICATION_ID = 7; + private NotificationManager mNotificationManager; + + private void showWorkNotification(int visibility) { + final Notification notification = new Notification.Builder(this) + .setSmallIcon(R.drawable.icon) + .setContentTitle(getString(R.string.provisioning_byod_work_notification_title)) + .setVisibility(visibility) + .setAutoCancel(true) + .build(); + mNotificationManager.notify(NOTIFICATION_ID, notification); + } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String action = getIntent().getAction(); - final NotificationManager notificationManager = (NotificationManager) - getSystemService(Context.NOTIFICATION_SERVICE); + mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (ACTION_WORK_NOTIFICATION.equals(action)) { - final Notification notification = new Notification.Builder(this) - .setSmallIcon(R.drawable.icon) - .setContentTitle(getString(R.string.provisioning_byod_work_notification_title)) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setAutoCancel(true) - .build(); - notificationManager.notify(NOTIFICATION_ID, notification); + showWorkNotification(Notification.VISIBILITY_PUBLIC); + } else if (ACTION_WORK_NOTIFICATION_ON_LOCKSCREEN.equals(action)) { + DevicePolicyManager dpm = (DevicePolicyManager) getSystemService( + Context.DEVICE_POLICY_SERVICE); + dpm.lockNow(); + showWorkNotification(Notification.VISIBILITY_PRIVATE); } else if (ACTION_CLEAR_WORK_NOTIFICATION.equals(action)) { - notificationManager.cancel(NOTIFICATION_ID); + mNotificationManager.cancel(NOTIFICATION_ID); } finish(); }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkStatusTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkStatusTestActivity.java new file mode 100644 index 0000000..ee9aa44 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/WorkStatusTestActivity.java
@@ -0,0 +1,61 @@ +/* + * Copyright (C) 2012 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.managedprovisioning; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.TextView; + +import com.android.cts.verifier.R; + +/** + * Test activity for work status tests. + */ +public class WorkStatusTestActivity extends Activity { + public static final String ACTION_WORK_STATUS_ICON + = "com.android.cts.verifier.managedprovisioning.WORK_STATUS_ICON"; + public static final String ACTION_WORK_STATUS_TOAST + = "com.android.cts.verifier.managedprovisioning.WORK_STATUS_TOAST"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.provisioning_cross_profile); + + findViewById(R.id.button_finish).setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + WorkStatusTestActivity.this.finish(); + } + }); + } + + @Override + public void onStart() { + super.onStart(); + String action = getIntent().getAction(); + TextView textView = (TextView) findViewById(R.id.text); + if (ACTION_WORK_STATUS_ICON.equals(action)) { + textView.setText(R.string.provisioning_byod_work_status_icon_activity); + } else if (ACTION_WORK_STATUS_TOAST.equals(action)) { + textView.setText(R.string.provisioning_byod_work_status_toast_activity); + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/LlcpVersionActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/LlcpVersionActivity.java new file mode 100644 index 0000000..ce5a3d4 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/LlcpVersionActivity.java
@@ -0,0 +1,123 @@ +/* + * Copyright (C) 2011 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.nfc; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.nfc.NdefMessage; +import android.nfc.NdefRecord; +import android.nfc.NfcAdapter; +import android.nfc.NfcEvent; +import android.nfc.NfcManager; +import android.os.Build; +import android.os.Bundle; +import android.widget.TextView; + +import java.nio.charset.Charset; + +/** + * Test activity that sends a particular NDEF Push message to another NFC device. + */ +public class LlcpVersionActivity extends PassFailButtons.Activity implements + NfcAdapter.CreateNdefMessageCallback { + + private static final int NFC_NOT_ENABLED_DIALOG_ID = 1; + private static final int NDEF_PUSH_NOT_ENABLED_DIALOG_ID = 2; + + private NfcAdapter mNfcAdapter; + private TextView mTextView; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.pass_fail_text); + setInfoResources(R.string.nfc_llcp_version_check, R.string.nfc_llcp_version_check_info, 0); + setPassFailButtonClickListeners(); + getPassButton().setEnabled(false); + + mTextView = (TextView) findViewById(R.id.text); + mTextView.setText(R.string.nfc_llcp_version_check_info); + + NfcManager nfcManager = (NfcManager) getSystemService(NFC_SERVICE); + mNfcAdapter = nfcManager.getDefaultAdapter(); + } + + private static NdefMessage getTestMessage() { + byte[] mimeBytes = "application/com.android.cts.verifier.nfc" + .getBytes(Charset.forName("US-ASCII")); + byte[] id = new byte[] {1, 3, 3, 7}; + byte[] payload = "CTS Verifier NDEF Push Tag".getBytes(Charset.forName("US-ASCII")); + return new NdefMessage(new NdefRecord[] { + new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, id, payload) + }); + } + + @Override + protected void onResume() { + super.onResume(); + + if (!mNfcAdapter.isEnabled()) { + showDialog(NFC_NOT_ENABLED_DIALOG_ID); + } else if (!mNfcAdapter.isNdefPushEnabled()) { + /* Sender must have NDEF push enabled */ + showDialog(NDEF_PUSH_NOT_ENABLED_DIALOG_ID); + } + + mNfcAdapter.setNdefPushMessageCallback(this, this); + } + + @Override + protected void onPause() { + super.onPause(); + } + + @Override + public Dialog onCreateDialog(int id, Bundle args) { + switch (id) { + case NFC_NOT_ENABLED_DIALOG_ID: + return NfcDialogs.createNotEnabledDialog(this); + case NDEF_PUSH_NOT_ENABLED_DIALOG_ID: + return NfcDialogs.createNdefPushNotEnabledDialog(this); + default: + return super.onCreateDialog(id, args); + } + } + + @Override + public NdefMessage createNdefMessage(NfcEvent event) { + if (event.peerLlcpMajorVersion <= 1 && event.peerLlcpMinorVersion < 2) { + runOnUiThread(new Runnable() { + @Override + public void run() { + mTextView.setText(R.string.nfc_llcp_version_check_failure); + } + }); + } else { + runOnUiThread(new Runnable() { + @Override + public void run() { + getPassButton().setEnabled(true); + mTextView.setText(R.string.nfc_llcp_version_check_success); + } + }); + } + return null; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NdefPushSenderActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NdefPushSenderActivity.java index f3f37c4..2f77895 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NdefPushSenderActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NdefPushSenderActivity.java
@@ -23,6 +23,7 @@ import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; +import android.nfc.NfcEvent; import android.nfc.NfcManager; import android.os.Bundle; import android.widget.TextView; @@ -32,7 +33,8 @@ /** * Test activity that sends a particular NDEF Push message to another NFC device. */ -public class NdefPushSenderActivity extends PassFailButtons.Activity { +public class NdefPushSenderActivity extends PassFailButtons.Activity implements + NfcAdapter.CreateNdefMessageCallback { static final NdefMessage TEST_MESSAGE = getTestMessage(); @@ -76,13 +78,12 @@ showDialog(NDEF_PUSH_NOT_ENABLED_DIALOG_ID); } - mNfcAdapter.enableForegroundNdefPush(this, TEST_MESSAGE); + mNfcAdapter.setNdefPushMessageCallback(this, this); } @Override protected void onPause() { super.onPause(); - mNfcAdapter.disableForegroundNdefPush(this); } @Override @@ -96,4 +97,9 @@ return super.onCreateDialog(id, args); } } + + @Override + public NdefMessage createNdefMessage(NfcEvent event) { + return getTestMessage(); + } }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NfcTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NfcTestActivity.java index cb90241..68fc027 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NfcTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/NfcTestActivity.java
@@ -28,6 +28,7 @@ import android.nfc.tech.MifareUltralight; import android.nfc.tech.Ndef; import android.nfc.tech.TagTechnology; +import android.os.Build; import android.os.Bundle; /** Activity that lists all the NFC tests. */ @@ -58,6 +59,11 @@ NdefPushReceiverActivity.class.getName(), new Intent(this, NdefPushReceiverActivity.class), null)); + if ("MNC".equals(Build.VERSION.CODENAME) || Build.VERSION.SDK_INT >= 23) { + adapter.add(TestListItem.newTest(this, R.string.nfc_llcp_version_check, + LlcpVersionActivity.class.getName(), + new Intent(this, LlcpVersionActivity.class), null)); + } adapter.add(TestListItem.newCategory(this, R.string.nfc_tag_verification)); adapter.add(TestListItem.newTest(this, R.string.nfc_ndef, NDEF_ID, getTagIntent(Ndef.class), null));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java index 035ce86..879916b 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java
@@ -40,12 +40,6 @@ if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) { adapter.add(TestListItem.newCategory(this, R.string.nfc_hce_reader_tests)); - /* - * Only add this test when supported in platform - adapter.add(TestListItem.newTest(this, R.string.nfc_hce_default_route_reader, - SimpleReaderActivity.class.getName(), - DefaultRouteEmulatorActivity.buildReaderIntent(this), null)); - */ adapter.add(TestListItem.newTest(this, R.string.nfc_hce_protocol_params_reader, ProtocolParamsReaderActivity.class.getName(),
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java index d8f196a..4898ab2 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
@@ -85,6 +85,7 @@ tests.add(new InsertContactsTest()); tests.add(new SetModeNoneTest()); tests.add(new NoneInterceptsAllTest()); + tests.add(new SetModeAllTest()); tests.add(new SetModePriorityTest()); tests.add(new PriorityInterceptsSomeTest()); tests.add(new SetModeAllTest());
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java index 07d9cc9..25a36b6 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
@@ -165,8 +165,9 @@ protected void onSaveInstanceState (Bundle outState) { final int stateIndex = mTestList.indexOf(mCurrentTest); outState.putInt(STATE, stateIndex); - outState.putInt(STATUS, mCurrentTest.status); - Log.i(TAG, "saved state(" + stateIndex + "}, status(" + (mCurrentTest.status) + ")"); + final int status = mCurrentTest == null ? SETUP : mCurrentTest.status; + outState.putInt(STATUS, status); + Log.i(TAG, "saved state(" + stateIndex + "}, status(" + status + ")"); } @Override @@ -383,6 +384,7 @@ @Override void test() { + mNm.cancelAll(); Intent settings = new Intent(NOTIFICATION_LISTENER_SETTINGS); if (settings.resolveActivity(mPackageManager) == null) { logFail("no settings activity");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/P2pTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/P2pTestListActivity.java index d133eda..920c9ae 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/P2pTestListActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/P2pTestListActivity.java
@@ -125,12 +125,12 @@ * If WiFi Direct is disabled, show the dialog to jump to system setting activity. **/ @Override - protected void onListItemClick(ListView listView, View view, int position, long id) { + protected void handleItemClick(ListView listView, View view, int position, long id) { if (!mIsP2pEnabled) { showP2pEnableDialog(); return; } - super.onListItemClick(listView, view, position, id); + super.handleItemClick(listView, view, position, id); } /**
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java new file mode 100644 index 0000000..70899c6 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
@@ -0,0 +1,247 @@ +/* + * Copyright (C) 2015 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.security; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.Manifest; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.app.KeyguardManager; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.hardware.fingerprint.FingerprintManager; +import android.os.Bundle; +import android.os.CancellationSignal; +import android.util.Log; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyPermanentlyInvalidatedException; +import android.security.keystore.KeyProperties; +import android.security.keystore.UserNotAuthenticatedException; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.Toast; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; + +public class FingerprintBoundKeysTest extends PassFailButtons.Activity { + private static final String TAG = "FingerprintBoundKeysTest"; + + /** Alias for our key in the Android Key Store. */ + private static final String KEY_NAME = "my_key"; + private static final byte[] SECRET_BYTE_ARRAY = new byte[] {1, 2, 3, 4, 5, 6}; + private static final int AUTHENTICATION_DURATION_SECONDS = 5; + private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1; + private static final int FINGERPRINT_PERMISSION_REQUEST_CODE = 0; + + private FingerprintManager mFingerprintManager; + private KeyguardManager mKeyguardManager; + private FingerprintAuthDialogFragment mFingerprintDialog; + private Cipher mCipher; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.sec_screen_lock_keys_main); + setPassFailButtonClickListeners(); + setInfoResources(R.string.sec_fingerprint_bound_key_test, R.string.sec_fingerprint_bound_key_test_info, -1); + getPassButton().setEnabled(false); + requestPermissions(new String[]{Manifest.permission.USE_FINGERPRINT}, + FINGERPRINT_PERMISSION_REQUEST_CODE); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] state) { + if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && state[0] == PackageManager.PERMISSION_GRANTED) { + mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE); + mKeyguardManager = (KeyguardManager) getSystemService(KeyguardManager.class); + + try { + KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); + keyStore.load(null); + SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); + mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + + KeyProperties.BLOCK_MODE_CBC + "/" + + KeyProperties.ENCRYPTION_PADDING_PKCS7); + + mCipher.init(Cipher.ENCRYPT_MODE, secretKey); + } catch (KeyPermanentlyInvalidatedException e) { + createKey(); + showToast("The key has been invalidated, please try again.\n"); + } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException + | NoSuchAlgorithmException | InvalidKeyException e) { + throw new RuntimeException("Failed to init Cipher", e); + } + + Button startTestButton = (Button) findViewById(R.id.sec_start_test_button); + startTestButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (tryEncrypt()) { + showToast("Test failed. Key accessible without auth."); + } else { + showAuthenticationScreen(); + } + } + + }); + + if (!mKeyguardManager.isKeyguardSecure()) { + // Show a message that the user hasn't set up a lock screen. + showToast( "Secure lock screen hasn't been set up.\n" + + "Go to 'Settings -> Security -> Screen lock' to set up a lock screen"); + startTestButton.setEnabled(false); + } else if (!mFingerprintManager.hasEnrolledFingerprints()) { + showToast("No fingerprints enrolled.\n" + + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint"); + startTestButton.setEnabled(false); + } else { + createKey(); + } + } + } + + /** + * Creates a symmetric key in the Android Key Store which can only be used after the user has + * authenticated with device credentials within the last X seconds. + */ + private void createKey() { + // Generate a key to decrypt payment credentials, tokens, etc. + // This will most likely be a registration step for the user when they are setting up your app. + try { + KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); + keyStore.load(null); + KeyGenerator keyGenerator = KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + + // Set the alias of the entry in Android KeyStore where the key will appear + // and the constrains (purposes) in the constructor of the Builder + keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, + KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + .setUserAuthenticationRequired(true) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) + .build()); + keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException | NoSuchProviderException + | InvalidAlgorithmParameterException | KeyStoreException + | CertificateException | IOException e) { + throw new RuntimeException("Failed to create a symmetric key", e); + } + } + + /** + * Tries to encrypt some data with the generated key in {@link #createKey} which is + * only works if the user has just authenticated via device credentials. + */ + private boolean tryEncrypt() { + try { + mCipher.doFinal(SECRET_BYTE_ARRAY); + return true; + } catch (BadPaddingException | IllegalBlockSizeException e) { + return false; + } + } + + private void showAuthenticationScreen() { + mFingerprintDialog = new FingerprintAuthDialogFragment(); + mFingerprintDialog.show(getFragmentManager(), "fingerprint_dialog"); + } + + private void showToast(String message) { + Toast.makeText(this, message, Toast.LENGTH_LONG) + .show(); + } + + public class FingerprintAuthDialogFragment extends DialogFragment { + + private CancellationSignal mCancellationSignal; + private FingerprintManagerCallback mFingerprintManagerCallback; + private boolean mSelfCancelled; + + class FingerprintManagerCallback extends FingerprintManager.AuthenticationCallback { + @Override + public void onAuthenticationError(int errMsgId, CharSequence errString) { + if (!mSelfCancelled) { + showToast(errString.toString()); + } + } + + @Override + public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { + showToast(helpString.toString()); + } + + @Override + public void onAuthenticationFailed() { + showToast(getString(R.string.sec_fp_auth_failed)); + } + + @Override + public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { + if (tryEncrypt()) { + showToast("Test passed."); + getPassButton().setEnabled(true); + FingerprintAuthDialogFragment.this.dismiss(); + } else { + showToast("Test failed. Key not accessible after auth"); + } + } + } + + @Override + public void onDismiss(DialogInterface dialog) { + mCancellationSignal.cancel(); + mSelfCancelled = true; + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + mCancellationSignal = new CancellationSignal(); + mSelfCancelled = false; + mFingerprintManagerCallback = new FingerprintManagerCallback(); + mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(mCipher), + mCancellationSignal, 0, mFingerprintManagerCallback, null); + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setMessage(R.string.sec_fp_dialog_message); + return builder.create(); + } + + } +} + +
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/KeyChainTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/KeyChainTest.java new file mode 100644 index 0000000..ebdb4c0 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/KeyChainTest.java
@@ -0,0 +1,464 @@ +/* + * Copyright (C) 2015 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.security; + +import android.app.Activity; +import android.content.Intent; +import android.content.res.Resources; +import android.os.AsyncTask; +import android.os.Bundle; +import android.provider.Settings; +import android.security.KeyChain; +import android.security.KeyChainAliasCallback; +import android.security.KeyChainException; +import android.text.method.ScrollingMovementMethod; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import com.google.mockwebserver.MockResponse; +import com.google.mockwebserver.MockWebServer; + +import java.io.InputStream; +import java.io.IOException; +import java.io.ByteArrayOutputStream; +import java.net.Socket; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; +import java.util.List; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.X509ExtendedKeyManager; + +import libcore.java.security.TestKeyStore; +import libcore.javax.net.ssl.TestSSLContext; + +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +/** + * Simple activity based test that exercises the KeyChain API + */ +public class KeyChainTest extends PassFailButtons.Activity implements View.OnClickListener { + + private static final String TAG = "KeyChainTest"; + + private static final int REQUEST_CA_INSTALL = 1; + + private TextView mInstructionView; + private TextView mLogView; + private Button mResetButton; + private Button mSkipButton; + private Button mNextButton; + + private List<Step> mSteps; + int mCurrentStep; + + private KeyStore mKeyStore; + private static final char[] KEYSTORE_PASSWORD = "".toCharArray(); + + // How long to wait before giving up on the user selecting a key alias. + private static final int KEYCHAIN_ALIAS_TIMEOUT_MS = (int) TimeUnit.MINUTES.toMillis(5L); + + @Override public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + View root = getLayoutInflater().inflate(R.layout.keychain_main, null); + setContentView(root); + + setInfoResources(R.string.keychain_test, R.string.keychain_info, -1); + setPassFailButtonClickListeners(); + + mInstructionView = (TextView) root.findViewById(R.id.test_instruction); + mLogView = (TextView) root.findViewById(R.id.test_log); + mLogView.setMovementMethod(new ScrollingMovementMethod()); + + mNextButton = (Button) root.findViewById(R.id.action_next); + mNextButton.setOnClickListener(this); + + mResetButton = (Button) root.findViewById(R.id.action_reset); + mResetButton.setOnClickListener(this); + + mSkipButton = (Button) root.findViewById(R.id.action_skip); + mSkipButton.setOnClickListener(this); + + resetProgress(); + } + + @Override + public void onClick(View v) { + Step step = mSteps.get(mCurrentStep); + if (v == mNextButton) { + switch (step.task.getStatus()) { + case PENDING: { + step.task.execute(); + break; + } + case FINISHED: { + if (mCurrentStep + 1 < mSteps.size()) { + mCurrentStep += 1; + updateUi(); + } else { + mSkipButton.setVisibility(View.INVISIBLE); + mNextButton.setVisibility(View.INVISIBLE); + } + break; + } + } + } else if (v == mSkipButton) { + step.task.cancel(false); + mCurrentStep += 1; + updateUi(); + } else if (v == mResetButton) { + resetProgress(); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case REQUEST_CA_INSTALL: { + if (resultCode == RESULT_OK) { + log("CA Certificate installed successfully"); + } else { + log("REQUEST_CA_INSTALL failed with result code: " + resultCode); + } + break; + } + default: + throw new IllegalStateException("requestCode == " + requestCode); + } + } + + private void resetProgress() { + getPassButton().setEnabled(false); + mLogView.setText(""); + + mSteps = new ArrayList<>(); + mSteps.add(new Step(R.string.keychain_setup_desc, false, new SetupTestKeyStoreTask())); + mSteps.add(new Step(R.string.keychain_install_desc, true, new InstallCredentialsTask())); + mSteps.add(new Step(R.string.keychain_https_desc, false, new TestHttpsRequestTask())); + mSteps.add(new Step(R.string.keychain_reset_desc, true, new ClearCredentialsTask())); + mCurrentStep = 0; + + updateUi(); + } + + private void updateUi() { + mLogView.setText(""); + + if (mCurrentStep >= mSteps.size()) { + mSkipButton.setVisibility(View.INVISIBLE); + mNextButton.setVisibility(View.INVISIBLE); + getPassButton().setEnabled(true); + return; + } + + final Step step = mSteps.get(mCurrentStep); + if (step.task.getStatus() == AsyncTask.Status.PENDING) { + mInstructionView.setText(step.instructionTextId); + } + mSkipButton.setVisibility(step.skippable ? View.VISIBLE : View.INVISIBLE); + mNextButton.setVisibility(View.VISIBLE); + } + + private class SetupTestKeyStoreTask extends AsyncTask<Void, Void, Void> { + @Override + protected Void doInBackground(Void... params) { + final Certificate[] chain = new Certificate[2]; + final Key privKey; + + log("Reading resources"); + Resources res = getResources(); + ByteArrayOutputStream userKey = new ByteArrayOutputStream(); + try { + InputStream is = res.openRawResource(R.raw.userkey); + byte[] buffer = new byte[4096]; + for (int n; (n = is.read(buffer, 0, buffer.length)) != -1;) { + userKey.write(buffer, 0, n); + } + } catch (IOException e) { + Log.e(TAG, "Reading private key failed", e); + return null; + } + log("Private key length: " + userKey.size() + " bytes"); + + log("Setting up KeyStore"); + try { + KeyFactory keyFact = KeyFactory.getInstance("RSA"); + privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(userKey.toByteArray())); + + final CertificateFactory f = CertificateFactory.getInstance("X.509"); + chain[0] = f.generateCertificate(res.openRawResource(R.raw.usercert)); + chain[1] = f.generateCertificate(res.openRawResource(R.raw.cacert)); + } catch (GeneralSecurityException gse) { + Log.w(TAG, "Certificate generation failed", gse); + return null; + } + + try { + // Create a PKCS12 keystore populated with key + certificate chain + KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(null, null); + ks.setKeyEntry("alias", privKey, KEYSTORE_PASSWORD, chain); + mKeyStore = ks; + log("KeyStore initialized"); + } catch (Exception e) { + log("KeyStore initialization failed"); + Log.e(TAG, "", e); + } + return null; + } + } + + private class InstallCredentialsTask extends AsyncTask<Void, Void, Void> { + @Override + protected Void doInBackground(Void... params) { + try { + Intent intent = KeyChain.createInstallIntent(); + intent.putExtra(KeyChain.EXTRA_NAME, TAG); + + // Write keystore to byte array for installation + ByteArrayOutputStream pkcs12 = new ByteArrayOutputStream(); + mKeyStore.store(pkcs12, KEYSTORE_PASSWORD); + if (pkcs12.size() == 0) { + throw new AssertionError("Credential archive is empty"); + } + log("Requesting install of server's credentials"); + intent.putExtra(KeyChain.EXTRA_PKCS12, pkcs12.toByteArray()); + startActivityForResult(intent, REQUEST_CA_INSTALL); + } catch (Exception e) { + log("Failed to install credentials: " + e); + } + return null; + } + } + + private class TestHttpsRequestTask extends AsyncTask<Void, Void, Void> { + @Override + protected Void doInBackground(Void... params) { + try { + URL url = startWebServer(); + makeHttpsRequest(url); + } catch (Exception e) { + Log.e(TAG, "HTTPS request unsuccessful", e); + log("Connection failed"); + return null; + } + + runOnUiThread(new Runnable() { + @Override public void run() { + getPassButton().setEnabled(true); + } + }); + return null; + } + + /** + * Create a mock web server. + * The server authenticates itself to the client using the key pair and certificate from the + * PKCS#12 keystore used in this test. Client authentication uses default trust management: + * the server trusts only the certificates installed in the credential storage of this + * user/profile. + */ + private URL startWebServer() throws Exception { + log("Starting web server"); + String kmfAlgoritm = KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgoritm); + kmf.init(mKeyStore, KEYSTORE_PASSWORD); + SSLContext serverContext = SSLContext.getInstance("TLS"); + serverContext.init(kmf.getKeyManagers(), + null /* TrustManager[] */, + null /* SecureRandom */); + SSLSocketFactory sf = serverContext.getSocketFactory(); + SSLSocketFactory needsClientAuth = TestSSLContext.clientAuth(sf, + false /* Want client auth */, + true /* Need client auth */); + MockWebServer server = new MockWebServer(); + server.useHttps(needsClientAuth, false /* tunnelProxy */); + server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); + server.play(); + return server.getUrl("/"); + } + + /** + * Open a new connection to the server. + * The client authenticates itself to the server using a private key and certificate + * supplied by KeyChain. Server authentication uses default trust management: the client + * trusts only certificates installed in the credential storage of this user/profile. This + * setup is expected to work because the server uses a private key whose certificate was + * installed earlier during this test. + */ + private void makeHttpsRequest(URL url) throws Exception { + log("Making https request to " + url); + SSLContext clientContext = SSLContext.getInstance("TLS"); + clientContext.init(new KeyManager[] { new KeyChainKeyManager() }, + null /* TrustManager[] */, + null /* SecureRandom */); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setSSLSocketFactory(clientContext.getSocketFactory()); + if (connection.getResponseCode() != 200) { + log("Connection failed. Response code: " + connection.getResponseCode()); + throw new AssertionError(); + } + log("Connection succeeded."); + } + } + + private class ClearCredentialsTask extends AsyncTask<Void, Void, Void> { + @Override + protected Void doInBackground(Void... params) { + final Intent securitySettingsIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS); + startActivity(securitySettingsIntent); + log("Started action: " + Settings.ACTION_SECURITY_SETTINGS); + log("All tests complete!"); + return null; + } + } + + /** + * Key manager which synchronously prompts for its aliases via KeyChain + */ + private class KeyChainKeyManager extends X509ExtendedKeyManager { + @Override + public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { + log("KeyChainKeyManager chooseClientAlias"); + KeyChainAliasCallback aliasCallback = Mockito.mock(KeyChainAliasCallback.class); + KeyChain.choosePrivateKeyAlias(KeyChainTest.this, aliasCallback, + keyTypes, issuers, + socket.getInetAddress().getHostName(), socket.getPort(), + null); + + ArgumentCaptor<String> aliasCaptor = ArgumentCaptor.forClass(String.class); + Mockito.verify(aliasCallback, Mockito.timeout((int) KEYCHAIN_ALIAS_TIMEOUT_MS)) + .alias(aliasCaptor.capture()); + + log("Certificate alias: \"" + aliasCaptor.getValue() + "\""); + return aliasCaptor.getValue(); + } + + @Override + public String chooseServerAlias(String keyType, + Principal[] issuers, + Socket socket) { + // Not a client SSLSocket callback + throw new UnsupportedOperationException(); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + try { + log("KeyChainKeyManager getCertificateChain"); + X509Certificate[] certificateChain = + KeyChain.getCertificateChain(KeyChainTest.this, alias); + if (certificateChain == null) { + log("Null certificate chain!"); + return null; + } + log("Returned " + certificateChain.length + " certificates in chain"); + for (int i = 0; i < certificateChain.length; i++) { + Log.d(TAG, "certificate[" + i + "]=" + certificateChain[i]); + } + return certificateChain; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } catch (KeyChainException e) { + throw new RuntimeException(e); + } + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + // not a client SSLSocket callback + throw new UnsupportedOperationException(); + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + // not a client SSLSocket callback + throw new UnsupportedOperationException(); + } + + @Override + public PrivateKey getPrivateKey(String alias) { + try { + log("KeyChainKeyManager.getPrivateKey(\"" + alias + "\")"); + PrivateKey privateKey = KeyChain.getPrivateKey(KeyChainTest.this, alias); + Log.d(TAG, "privateKey = " + privateKey); + return privateKey; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } catch (KeyChainException e) { + throw new RuntimeException(e); + } + } + } + + /** + * Write a message to the log, also to a visible TextView if available. + */ + private void log(final String message) { + Log.d(TAG, message); + if (mLogView != null) { + runOnUiThread(new Runnable() { + @Override public void run() { + mLogView.append(message + "\n"); + } + }); + } + } + + /** + * Utility class to store one step per object. + */ + private static class Step { + // Instruction message to show before running + int instructionTextId; + + // Whether to allow a 'skip' button for this step + boolean skippable; + + // Set of commands to run when 'next' is pressed + AsyncTask<Void, Void, Void> task; + + public Step(int instructionTextId, boolean skippable, AsyncTask<Void, Void, Void> task) { + this.instructionTextId = instructionTextId; + this.skippable = skippable; + this.task = task; + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java new file mode 100644 index 0000000..863488b --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/ScreenLockBoundKeysTest.java
@@ -0,0 +1,204 @@ +/* + * Copyright (C) 2011 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.security; + +import com.android.cts.verifier.PassFailButtons; +import com.android.cts.verifier.R; + +import android.app.AlertDialog; +import android.app.KeyguardManager; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyPermanentlyInvalidatedException; +import android.security.keystore.KeyProperties; +import android.security.keystore.UserNotAuthenticatedException; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.Toast; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; + +public class ScreenLockBoundKeysTest extends PassFailButtons.Activity { + + /** Alias for our key in the Android Key Store. */ + private static final String KEY_NAME = "my_lock_key"; + private static final byte[] SECRET_BYTE_ARRAY = new byte[] {1, 2, 3, 4, 5, 6}; + private static final int AUTHENTICATION_DURATION_SECONDS = 5; + private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1; + + private KeyguardManager mKeyguardManager; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.sec_screen_lock_keys_main); + setPassFailButtonClickListeners(); + setInfoResources(R.string.sec_lock_bound_key_test, R.string.sec_lock_bound_key_test_info, -1); + + mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); + + getPassButton().setEnabled(false); + + Button startTestButton = (Button) findViewById(R.id.sec_start_test_button); + startTestButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + showToast("Test running..."); + v.postDelayed(new Runnable() { + @Override + public void run() { + if (tryEncrypt()) { + showToast("Test failed. Key accessible without auth."); + } else { + showAuthenticationScreen(); + } + } + }, + AUTHENTICATION_DURATION_SECONDS * 1000); + } + + }); + + if (!mKeyguardManager.isKeyguardSecure()) { + // Show a message that the user hasn't set up a lock screen. + Toast.makeText(this, + "Secure lock screen hasn't set up.\n" + + "Go to 'Settings -> Security -> Screenlock' to set up a lock screen", + Toast.LENGTH_LONG).show(); + startTestButton.setEnabled(false); + return; + } + + createKey(); + } + + /** + * Creates a symmetric key in the Android Key Store which can only be used after the user has + * authenticated with device credentials within the last X seconds. + */ + private void createKey() { + // Generate a key to decrypt payment credentials, tokens, etc. + // This will most likely be a registration step for the user when they are setting up your app. + try { + KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); + keyStore.load(null); + KeyGenerator keyGenerator = KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + + // Set the alias of the entry in Android KeyStore where the key will appear + // and the constrains (purposes) in the constructor of the Builder + keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, + KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + .setUserAuthenticationRequired(true) + // Require that the user has unlocked in the last 30 seconds + .setUserAuthenticationValidityDurationSeconds(AUTHENTICATION_DURATION_SECONDS) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) + .build()); + keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException | NoSuchProviderException + | InvalidAlgorithmParameterException | KeyStoreException + | CertificateException | IOException e) { + throw new RuntimeException("Failed to create a symmetric key", e); + } + } + + /** + * Tries to encrypt some data with the generated key in {@link #createKey} which is + * only works if the user has just authenticated via device credentials. + */ + private boolean tryEncrypt() { + try { + KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); + keyStore.load(null); + SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); + Cipher cipher = Cipher.getInstance( + KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + + KeyProperties.ENCRYPTION_PADDING_PKCS7); + + // Try encrypting something, it will only work if the user authenticated within + // the last AUTHENTICATION_DURATION_SECONDS seconds. + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + cipher.doFinal(SECRET_BYTE_ARRAY); + return true; + } catch (UserNotAuthenticatedException e) { + // User is not authenticated, let's authenticate with device credentials. + return false; + } catch (KeyPermanentlyInvalidatedException e) { + // This happens if the lock screen has been disabled or reset after the key was + // generated after the key was generated. + createKey(); + Toast.makeText(this, "Set up lockscreen after test ran. Retry the test.\n" + + e.getMessage(), + Toast.LENGTH_LONG).show(); + return false; + } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException | + CertificateException | UnrecoverableKeyException | IOException + | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) { + throw new RuntimeException(e); + } + } + + private void showAuthenticationScreen() { + // Create the Confirm Credentials screen. You can customize the title and description. Or + // we will provide a generic one for you if you leave it null + Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null); + if (intent != null) { + startActivityForResult(intent, CONFIRM_CREDENTIALS_REQUEST_CODE); + } + } + + private void showToast(String message) { + Toast.makeText(this, message, Toast.LENGTH_LONG) + .show(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch (requestCode) { + case CONFIRM_CREDENTIALS_REQUEST_CODE: + if (resultCode == RESULT_OK) { + if (tryEncrypt()) { + showToast("Test passed."); + getPassButton().setEnabled(true); + } else { + showToast("Test failed. Key not accessible after auth"); + } + } + } + } +} +
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaOutputSurface.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaOutputSurface.java new file mode 100644 index 0000000..b28e06b --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaOutputSurface.java
@@ -0,0 +1,322 @@ +/* + * Copyright (C) 2013 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; + +import android.graphics.SurfaceTexture; +import android.opengl.EGL14; +import android.opengl.EGLConfig; +import android.opengl.EGLContext; +import android.opengl.EGLDisplay; +import android.opengl.EGLSurface; +import android.util.Log; +import android.view.Surface; + + +// +// This file is copied from android.hardware.cts.media +// + +/** + * Holds state associated with a Surface used for MediaCodec decoder output. + * <p> + * The (width,height) constructor for this class will prepare GL, create a SurfaceTexture, + * and then create a Surface for that SurfaceTexture. The Surface can be passed to + * MediaCodec.configure() to receive decoder output. When a frame arrives, we latch the + * texture with updateTexImage, then render the texture with GL to a pbuffer. + * <p> + * The no-arg constructor skips the GL preparation step and doesn't allocate a pbuffer. + * Instead, it just creates the Surface and SurfaceTexture, and when a frame arrives + * we just draw it on whatever surface is current. + * <p> + * By default, the Surface will be using a BufferQueue in asynchronous mode, so we + * can potentially drop frames. + */ +class CtsMediaOutputSurface implements SurfaceTexture.OnFrameAvailableListener { + private static final String TAG = "OutputSurface"; + private static final boolean VERBOSE = false; + + private EGLDisplay mEGLDisplay = EGL14.EGL_NO_DISPLAY; + private EGLContext mEGLContext = EGL14.EGL_NO_CONTEXT; + private EGLSurface mEGLSurface = EGL14.EGL_NO_SURFACE; + + private SurfaceTexture mSurfaceTexture; + private Surface mSurface; + + private Object mFrameSyncObject = new Object(); // guards mFrameAvailable + private boolean mFrameAvailable; + + private CtsMediaTextureRender mTextureRender; + + /** + * Creates an OutputSurface backed by a pbuffer with the specifed dimensions. The new + * EGL context and surface will be made current. Creates a Surface that can be passed + * to MediaCodec.configure(). + */ + public CtsMediaOutputSurface(int width, int height) { + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException(); + } + + eglSetup(width, height); + makeCurrent(); + + setup(this); + } + + /** + * Creates an OutputSurface using the current EGL context (rather than establishing a + * new one). Creates a Surface that can be passed to MediaCodec.configure(). + */ + public CtsMediaOutputSurface() { + setup(this); + } + + public CtsMediaOutputSurface(final SurfaceTexture.OnFrameAvailableListener listener) { + setup(listener); + } + + /** + * Creates instances of TextureRender and SurfaceTexture, and a Surface associated + * with the SurfaceTexture. + */ + private void setup(SurfaceTexture.OnFrameAvailableListener listener) { + mTextureRender = new CtsMediaTextureRender(); + mTextureRender.surfaceCreated(); + + // Even if we don't access the SurfaceTexture after the constructor returns, we + // still need to keep a reference to it. The Surface doesn't retain a reference + // at the Java level, so if we don't either then the object can get GCed, which + // causes the native finalizer to run. + if (VERBOSE) Log.d(TAG, "textureID=" + mTextureRender.getTextureId()); + mSurfaceTexture = new SurfaceTexture(mTextureRender.getTextureId()); + + // This doesn't work if OutputSurface is created on the thread that CTS started for + // these test cases. + // + // The CTS-created thread has a Looper, and the SurfaceTexture constructor will + // create a Handler that uses it. The "frame available" message is delivered + // there, but since we're not a Looper-based thread we'll never see it. For + // this to do anything useful, OutputSurface must be created on a thread without + // a Looper, so that SurfaceTexture uses the main application Looper instead. + // + // Java language note: passing "this" out of a constructor is generally unwise, + // but we should be able to get away with it here. + mSurfaceTexture.setOnFrameAvailableListener(listener); + + mSurface = new Surface(mSurfaceTexture); + } + + /** + * Prepares EGL. We want a GLES 2.0 context and a surface that supports pbuffer. + */ + private void eglSetup(int width, int height) { + mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); + if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) { + throw new RuntimeException("unable to get EGL14 display"); + } + int[] version = new int[2]; + if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) { + mEGLDisplay = null; + throw new RuntimeException("unable to initialize EGL14"); + } + + // Configure EGL for pbuffer and OpenGL ES 2.0. We want enough RGB bits + // to be able to tell if the frame is reasonable. + int[] attribList = { + EGL14.EGL_RED_SIZE, 8, + EGL14.EGL_GREEN_SIZE, 8, + EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, + EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, + EGL14.EGL_NONE + }; + EGLConfig[] configs = new EGLConfig[1]; + int[] numConfigs = new int[1]; + if (!EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length, + numConfigs, 0)) { + throw new RuntimeException("unable to find RGB888+recordable ES2 EGL config"); + } + + // Configure context for OpenGL ES 2.0. + int[] attrib_list = { + EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, + EGL14.EGL_NONE + }; + mEGLContext = EGL14.eglCreateContext(mEGLDisplay, configs[0], EGL14.EGL_NO_CONTEXT, + attrib_list, 0); + checkEglError("eglCreateContext"); + if (mEGLContext == null) { + throw new RuntimeException("null context"); + } + + // Create a pbuffer surface. By using this for output, we can use glReadPixels + // to test values in the output. + int[] surfaceAttribs = { + EGL14.EGL_WIDTH, width, + EGL14.EGL_HEIGHT, height, + EGL14.EGL_NONE + }; + mEGLSurface = EGL14.eglCreatePbufferSurface(mEGLDisplay, configs[0], surfaceAttribs, 0); + checkEglError("eglCreatePbufferSurface"); + if (mEGLSurface == null) { + throw new RuntimeException("surface was null"); + } + } + + /** + * Discard all resources held by this class, notably the EGL context. + */ + public void release() { + if (mEGLDisplay != EGL14.EGL_NO_DISPLAY) { + EGL14.eglDestroySurface(mEGLDisplay, mEGLSurface); + EGL14.eglDestroyContext(mEGLDisplay, mEGLContext); + EGL14.eglReleaseThread(); + EGL14.eglTerminate(mEGLDisplay); + } + + mSurface.release(); + + // this causes a bunch of warnings that appear harmless but might confuse someone: + // W BufferQueue: [unnamed-3997-2] cancelBuffer: BufferQueue has been abandoned! + //mSurfaceTexture.release(); + + mEGLDisplay = EGL14.EGL_NO_DISPLAY; + mEGLContext = EGL14.EGL_NO_CONTEXT; + mEGLSurface = EGL14.EGL_NO_SURFACE; + + mTextureRender = null; + mSurface = null; + mSurfaceTexture = null; + } + + /** + * Makes our EGL context and surface current. + */ + public void makeCurrent() { + if (!EGL14.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) { + throw new RuntimeException("eglMakeCurrent failed"); + } + } + + /** + * Returns the Surface that we draw onto. + */ + public Surface getSurface() { + return mSurface; + } + + /** + * Replaces the fragment shader. + */ + public void changeFragmentShader(String fragmentShader) { + mTextureRender.changeFragmentShader(fragmentShader); + } + + /** + * Latches the next buffer into the texture. Must be called from the thread that created + * the OutputSurface object, after the onFrameAvailable callback has signaled that new + * data is available. + */ + public void awaitNewImage() { + final int TIMEOUT_MS = 500; + + synchronized (mFrameSyncObject) { + while (!mFrameAvailable) { + try { + // Wait for onFrameAvailable() to signal us. Use a timeout to avoid + // stalling the test if it doesn't arrive. + mFrameSyncObject.wait(TIMEOUT_MS); + if (!mFrameAvailable) { + // TODO: if "spurious wakeup", continue while loop + throw new RuntimeException("Surface frame wait timed out"); + } + } catch (InterruptedException ie) { + // shouldn't happen + throw new RuntimeException(ie); + } + } + mFrameAvailable = false; + } + + // Latch the data. + mTextureRender.checkGlError("before updateTexImage"); + mSurfaceTexture.updateTexImage(); + } + + /** + * Wait up to given timeout until new image become available. + * @param timeoutMs + * @return true if new image is available. false for no new image until timeout. + */ + public boolean checkForNewImage(int timeoutMs) { + synchronized (mFrameSyncObject) { + while (!mFrameAvailable) { + try { + // Wait for onFrameAvailable() to signal us. Use a timeout to avoid + // stalling the test if it doesn't arrive. + mFrameSyncObject.wait(timeoutMs); + if (!mFrameAvailable) { + return false; + } + } catch (InterruptedException ie) { + // shouldn't happen + throw new RuntimeException(ie); + } + } + mFrameAvailable = false; + } + + // Latch the data. + mTextureRender.checkGlError("before updateTexImage"); + mSurfaceTexture.updateTexImage(); + return true; + } + + /** + * Draws the data from SurfaceTexture onto the current EGL surface. + */ + public void drawImage() { + mTextureRender.drawFrame(mSurfaceTexture); + } + + public void latchImage() { + mTextureRender.checkGlError("before updateTexImage"); + mSurfaceTexture.updateTexImage(); + } + + @Override + public void onFrameAvailable(SurfaceTexture st) { + if (VERBOSE) Log.d(TAG, "new frame available"); + synchronized (mFrameSyncObject) { + if (mFrameAvailable) { + throw new RuntimeException("mFrameAvailable already set, frame could be dropped"); + } + mFrameAvailable = true; + mFrameSyncObject.notifyAll(); + } + } + + /** + * Checks for EGL errors. + */ + private void checkEglError(String msg) { + int error; + if ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) { + throw new RuntimeException(msg + ": EGL error: 0x" + Integer.toHexString(error)); + } + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaTextureRender.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaTextureRender.java new file mode 100644 index 0000000..a96033d --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/CtsMediaTextureRender.java
@@ -0,0 +1,306 @@ +/* + * Copyright (C) 2013 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; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import android.graphics.Bitmap; +import android.graphics.SurfaceTexture; +import android.opengl.GLES11Ext; +import android.opengl.GLES20; +import android.opengl.Matrix; +import android.util.Log; + + +// +// This file is copied from android.hardware.cts.media +// + +/** + * Code for rendering a texture onto a surface using OpenGL ES 2.0. + */ +class CtsMediaTextureRender { + private static final String TAG = "TextureRender"; + + private static final int FLOAT_SIZE_BYTES = 4; + private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES; + private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0; + private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3; + private final float[] mTriangleVerticesData = { + // X, Y, Z, U, V + -1.0f, -1.0f, 0, 0.f, 0.f, + 1.0f, -1.0f, 0, 1.f, 0.f, + -1.0f, 1.0f, 0, 0.f, 1.f, + 1.0f, 1.0f, 0, 1.f, 1.f, + }; + + private FloatBuffer mTriangleVertices; + + private static final String VERTEX_SHADER = + "uniform mat4 uMVPMatrix;\n" + + "uniform mat4 uSTMatrix;\n" + + "attribute vec4 aPosition;\n" + + "attribute vec4 aTextureCoord;\n" + + "varying vec2 vTextureCoord;\n" + + "void main() {\n" + + " gl_Position = uMVPMatrix * aPosition;\n" + + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + + "}\n"; + + private static final String FRAGMENT_SHADER = + "#extension GL_OES_EGL_image_external : require\n" + + "precision mediump float;\n" + // highp here doesn't seem to matter + "varying vec2 vTextureCoord;\n" + + "uniform samplerExternalOES sTexture;\n" + + "void main() {\n" + + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + + "}\n"; + + private float[] mMVPMatrix = new float[16]; + private float[] mSTMatrix = new float[16]; + + private int mProgram; + private int mTextureID = -12345; + private int muMVPMatrixHandle; + private int muSTMatrixHandle; + private int maPositionHandle; + private int maTextureHandle; + + public CtsMediaTextureRender() { + mTriangleVertices = ByteBuffer.allocateDirect( + mTriangleVerticesData.length * FLOAT_SIZE_BYTES) + .order(ByteOrder.nativeOrder()).asFloatBuffer(); + mTriangleVertices.put(mTriangleVerticesData).position(0); + + Matrix.setIdentityM(mSTMatrix, 0); + } + + public int getTextureId() { + return mTextureID; + } + + public void drawFrame(SurfaceTexture st) { + checkGlError("onDrawFrame start"); + st.getTransformMatrix(mSTMatrix); + + GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f); + GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); + + GLES20.glUseProgram(mProgram); + checkGlError("glUseProgram"); + + GLES20.glActiveTexture(GLES20.GL_TEXTURE0); + GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID); + + mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET); + GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, + TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); + checkGlError("glVertexAttribPointer maPosition"); + GLES20.glEnableVertexAttribArray(maPositionHandle); + checkGlError("glEnableVertexAttribArray maPositionHandle"); + + mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET); + GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, + TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); + checkGlError("glVertexAttribPointer maTextureHandle"); + GLES20.glEnableVertexAttribArray(maTextureHandle); + checkGlError("glEnableVertexAttribArray maTextureHandle"); + + Matrix.setIdentityM(mMVPMatrix, 0); + GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); + GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0); + + GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); + checkGlError("glDrawArrays"); + GLES20.glFinish(); + } + + /** + * Initializes GL state. Call this after the EGL surface has been created and made current. + */ + public void surfaceCreated() { + mProgram = createProgram(VERTEX_SHADER, FRAGMENT_SHADER); + if (mProgram == 0) { + throw new RuntimeException("failed creating program"); + } + maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition"); + checkGlError("glGetAttribLocation aPosition"); + if (maPositionHandle == -1) { + throw new RuntimeException("Could not get attrib location for aPosition"); + } + maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord"); + checkGlError("glGetAttribLocation aTextureCoord"); + if (maTextureHandle == -1) { + throw new RuntimeException("Could not get attrib location for aTextureCoord"); + } + + muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); + checkGlError("glGetUniformLocation uMVPMatrix"); + if (muMVPMatrixHandle == -1) { + throw new RuntimeException("Could not get attrib location for uMVPMatrix"); + } + + muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix"); + checkGlError("glGetUniformLocation uSTMatrix"); + if (muSTMatrixHandle == -1) { + throw new RuntimeException("Could not get attrib location for uSTMatrix"); + } + + + int[] textures = new int[1]; + GLES20.glGenTextures(1, textures, 0); + + mTextureID = textures[0]; + GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID); + checkGlError("glBindTexture mTextureID"); + + GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, + GLES20.GL_NEAREST); + GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, + GLES20.GL_LINEAR); + GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, + GLES20.GL_CLAMP_TO_EDGE); + GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, + GLES20.GL_CLAMP_TO_EDGE); + checkGlError("glTexParameter"); + } + + /** + * Replaces the fragment shader. + */ + public void changeFragmentShader(String fragmentShader) { + GLES20.glDeleteProgram(mProgram); + mProgram = createProgram(VERTEX_SHADER, fragmentShader); + if (mProgram == 0) { + throw new RuntimeException("failed creating program"); + } + } + + private int loadShader(int shaderType, String source) { + int shader = GLES20.glCreateShader(shaderType); + checkGlError("glCreateShader type=" + shaderType); + GLES20.glShaderSource(shader, source); + GLES20.glCompileShader(shader); + int[] compiled = new int[1]; + GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); + if (compiled[0] == 0) { + Log.e(TAG, "Could not compile shader " + shaderType + ":"); + Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader)); + GLES20.glDeleteShader(shader); + shader = 0; + } + return shader; + } + + private int createProgram(String vertexSource, String fragmentSource) { + int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); + if (vertexShader == 0) { + return 0; + } + int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); + if (pixelShader == 0) { + return 0; + } + + int program = GLES20.glCreateProgram(); + checkGlError("glCreateProgram"); + if (program == 0) { + Log.e(TAG, "Could not create program"); + } + GLES20.glAttachShader(program, vertexShader); + checkGlError("glAttachShader"); + GLES20.glAttachShader(program, pixelShader); + checkGlError("glAttachShader"); + GLES20.glLinkProgram(program); + int[] linkStatus = new int[1]; + GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); + if (linkStatus[0] != GLES20.GL_TRUE) { + Log.e(TAG, "Could not link program: "); + Log.e(TAG, GLES20.glGetProgramInfoLog(program)); + GLES20.glDeleteProgram(program); + program = 0; + } + return program; + } + + public void checkGlError(String op) { + int error; + while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { + Log.e(TAG, op + ": glError " + error); + throw new RuntimeException(op + ": glError " + error); + } + } + + /** + * Saves the current frame to disk as a PNG image. Frame starts from (0,0). + * <p> + * Useful for debugging. + */ + public static void saveFrame(String filename, int width, int height) { + // glReadPixels gives us a ByteBuffer filled with what is essentially big-endian RGBA + // data (i.e. a byte of red, followed by a byte of green...). We need an int[] filled + // with native-order ARGB data to feed to Bitmap. + // + // If we implement this as a series of buf.get() calls, we can spend 2.5 seconds just + // copying data around for a 720p frame. It's better to do a bulk get() and then + // rearrange the data in memory. (For comparison, the PNG compress takes about 500ms + // for a trivial frame.) + // + // So... we set the ByteBuffer to little-endian, which should turn the bulk IntBuffer + // get() into a straight memcpy on most Android devices. Our ints will hold ABGR data. + // Swapping B and R gives us ARGB. We need about 30ms for the bulk get(), and another + // 270ms for the color swap. + // + // Making this even more interesting is the upside-down nature of GL, which means we + // may want to flip the image vertically here. + + ByteBuffer buf = ByteBuffer.allocateDirect(width * height * 4); + buf.order(ByteOrder.LITTLE_ENDIAN); + GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf); + buf.rewind(); + + int pixelCount = width * height; + int[] colors = new int[pixelCount]; + buf.asIntBuffer().get(colors); + for (int i = 0; i < pixelCount; i++) { + int c = colors[i]; + colors[i] = (c & 0xff00ff00) | ((c & 0x00ff0000) >> 16) | ((c & 0x000000ff) << 16); + } + + FileOutputStream fos = null; + try { + fos = new FileOutputStream(filename); + Bitmap bmp = Bitmap.createBitmap(colors, width, height, Bitmap.Config.ARGB_8888); + bmp.compress(Bitmap.CompressFormat.PNG, 90, fos); + bmp.recycle(); + } catch (IOException ioe) { + throw new RuntimeException("Failed to write file " + filename, ioe); + } finally { + try { + if (fos != null) fos.close(); + } catch (IOException ioe2) { + throw new RuntimeException("Failed to close file " + filename, ioe2); + } + } + Log.d(TAG, "Saved " + width + "x" + height + " frame as '" + filename + "'"); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java new file mode 100644 index 0000000..83e3054 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
@@ -0,0 +1,321 @@ +package com.android.cts.verifier.sensors; + +import java.util.ArrayList; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import com.android.cts.verifier.R; +import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity; +import com.android.cts.verifier.sensors.helpers.SensorTestScreenManipulator; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.hardware.TriggerEvent; +import android.hardware.TriggerEventListener; +import android.hardware.cts.helpers.MovementDetectorHelper; +import android.hardware.cts.helpers.SensorStats; +import android.hardware.cts.helpers.SensorStats; +import android.hardware.cts.helpers.SensorTestStateNotSupportedException; +import android.hardware.cts.helpers.TestSensorEnvironment; +import android.hardware.cts.helpers.TestSensorEvent; +import android.hardware.cts.helpers.TestSensorEventListener; +import android.hardware.cts.helpers.TestSensorManager; +import android.hardware.cts.helpers.sensoroperations.TestSensorOperation; +import android.hardware.cts.helpers.SensorNotSupportedException; +import android.hardware.cts.helpers.sensorverification.BatchArrivalVerification; +import android.os.PowerManager; +import android.os.PowerManager.WakeLock; +import android.os.SystemClock; +import android.support.v4.content.LocalBroadcastManager; +import android.util.Log; +import android.view.MotionEvent; +import android.view.View; + +import junit.framework.Assert; + +public class DeviceSuspendTestActivity + extends SensorCtsVerifierTestActivity { + public DeviceSuspendTestActivity() { + super(DeviceSuspendTestActivity.class); + } + + private SensorTestScreenManipulator mScreenManipulator; + private PowerManager.WakeLock mDeviceSuspendLock; + private PendingIntent mPendingIntent; + private AlarmManager mAlarmManager; + private static String ACTION_ALARM = "DeviceSuspendTestActivity.ACTION_ALARM"; + private static String TAG = "DeviceSuspendSensorTest"; + private SensorManager mSensorManager; + + @Override + protected void activitySetUp() throws InterruptedException { + mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); + mScreenManipulator = new SensorTestScreenManipulator(this); + mScreenManipulator.initialize(this); + LocalBroadcastManager.getInstance(this).registerReceiver(myBroadCastReceiver, + new IntentFilter(ACTION_ALARM)); + + Intent intent = new Intent(this, AlarmReceiver.class); + mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + + mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); + + PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); + mDeviceSuspendLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "DeviceSuspendTestActivity"); + mDeviceSuspendLock.acquire(); + SensorTestLogger logger = getTestLogger(); + logger.logInstructions(R.string.snsr_device_suspend_test_instr); + waitForUserToBegin(); + } + + @Override + protected void activityCleanUp() { + mScreenManipulator.turnScreenOn(); + try { + playSound(); + } catch(InterruptedException e) { + // Ignore. + } + LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadCastReceiver); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (mScreenManipulator != null) { + mScreenManipulator.releaseScreenOn(); + mScreenManipulator.close(); + } + if (mDeviceSuspendLock.isHeld()) { + mDeviceSuspendLock.release(); + } + } + + public static class AlarmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + Intent alarm_intent = new Intent(context, DeviceSuspendTestActivity.class); + alarm_intent.setAction(DeviceSuspendTestActivity.ACTION_ALARM); + LocalBroadcastManager.getInstance(context).sendBroadcastSync(alarm_intent); + } + } + + public BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (!mDeviceSuspendLock.isHeld()) { + mDeviceSuspendLock.acquire(); + } + } + }; + + public String testAPWakeUpWhenReportLatencyExpiresAccel() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER, true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, true); + } + return runAPWakeUpWhenReportLatencyExpires(wakeUpSensor); + } + + public String testAPWakeUpWhenReportLatencyExpiresGyro() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE, true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_GYROSCOPE, true); + } + return runAPWakeUpWhenReportLatencyExpires(wakeUpSensor); + } + + public String testAPWakeUpWhenReportLatencyExpiresMag() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD,true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_MAGNETIC_FIELD, true); + } + return runAPWakeUpWhenFIFOFull(wakeUpSensor); + } + + public String testAPWakeUpWhenFIFOFullAccel() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER, true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, true); + } + return runAPWakeUpWhenFIFOFull(wakeUpSensor); + } + + public String testAPWakeUpWhenFIFOFullGyro() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE, true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_GYROSCOPE, true); + } + return runAPWakeUpWhenFIFOFull(wakeUpSensor); + } + + public String testAPWakeUpWhenFIFOFullMag() throws Throwable { + Sensor wakeUpSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD,true); + if (wakeUpSensor == null) { + throw new SensorNotSupportedException(Sensor.TYPE_MAGNETIC_FIELD, true); + } + return runAPWakeUpWhenFIFOFull(wakeUpSensor); + } + + public String testAccelBatchingInAPSuspendLargeReportLatency() throws Throwable { + Sensor accel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + if (accel == null) { + throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, false); + } + return runAPWakeUpByAlarmNonWakeSensor(accel, (int)TimeUnit.SECONDS.toMicros(1000)); + } + + public String testAccelBatchingInAPSuspendZeroReportLatency() throws Throwable { + Sensor accel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + if (accel == null) { + throw new SensorNotSupportedException(Sensor.TYPE_ACCELEROMETER, false); + } + return runAPWakeUpByAlarmNonWakeSensor(accel, 0); + } + + public String runAPWakeUpWhenReportLatencyExpires(Sensor sensor) throws Throwable { + int fifoMaxEventCount = sensor.getFifoMaxEventCount(); + if (fifoMaxEventCount == 0) { + throw new SensorTestStateNotSupportedException("Batching not supported."); + } + int maximumExpectedSamplingPeriodUs = sensor.getMaxDelay(); + if (maximumExpectedSamplingPeriodUs == 0) { + // If maxDelay is not defined, set the value for 5 Hz. + maximumExpectedSamplingPeriodUs = 200000; + } + int fifoBasedReportLatencyUs = fifoMaxEventCount * maximumExpectedSamplingPeriodUs; + + // Ensure that FIFO based report latency is at least 20 seconds, we need at least 10 + // seconds of time to allow the device to be in suspend state. + if (fifoBasedReportLatencyUs < 20000000L) { + throw new SensorTestStateNotSupportedException("FIFO too small to test reliably"); + } + + final int MAX_REPORT_LATENCY_US = 15000000; // 15 seconds + TestSensorEnvironment environment = new TestSensorEnvironment( + this, + sensor, + false, + maximumExpectedSamplingPeriodUs, + MAX_REPORT_LATENCY_US, + true /*isDeviceSuspendTest*/); + + TestSensorOperation op = TestSensorOperation.createOperation(environment, + mDeviceSuspendLock, + false); + final int ALARM_WAKE_UP_DELAY_MS = MAX_REPORT_LATENCY_US/1000 + + (int)TimeUnit.SECONDS.toMillis(10); + op.addVerification(BatchArrivalVerification.getDefault(environment)); + mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + ALARM_WAKE_UP_DELAY_MS, + mPendingIntent); + try { + Log.i(TAG, "Running .. " + getCurrentTestNode().getName() + " " + sensor.getName()); + op.execute(getCurrentTestNode()); + } finally { + mAlarmManager.cancel(mPendingIntent); + } + return null; + } + + public String runAPWakeUpWhenFIFOFull(Sensor sensor) throws Throwable { + int fifoMaxEventCount = sensor.getFifoMaxEventCount(); + if (fifoMaxEventCount == 0) { + throw new SensorTestStateNotSupportedException("Batching not supported."); + } + // Try to fill the FIFO at the fastest rate and check if the time is enough to run + // the manual test. + int maximumExpectedSamplingPeriodUs = sensor.getMinDelay(); + int fifoBasedReportLatencyUs = fifoMaxEventCount * maximumExpectedSamplingPeriodUs; + + final int MIN_LATENCY_US = (int)TimeUnit.SECONDS.toMicros(20); + // Ensure that FIFO based report latency is at least 20 seconds, we need at least 10 + // seconds of time to allow the device to be in suspend state. + if (fifoBasedReportLatencyUs < MIN_LATENCY_US) { + maximumExpectedSamplingPeriodUs = MIN_LATENCY_US/fifoMaxEventCount; + fifoBasedReportLatencyUs = MIN_LATENCY_US; + } + + final int MAX_REPORT_LATENCY_US = Integer.MAX_VALUE; + final int ALARM_WAKE_UP_DELAY_MS = fifoBasedReportLatencyUs/1000 + + (int)TimeUnit.SECONDS.toMillis(10); + TestSensorEnvironment environment = new TestSensorEnvironment( + this, + sensor, + false, + maximumExpectedSamplingPeriodUs, + MAX_REPORT_LATENCY_US, + true /*isDeviceSuspendTest*/); + + TestSensorOperation op = TestSensorOperation.createOperation(environment, + mDeviceSuspendLock, + true); + mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + ALARM_WAKE_UP_DELAY_MS, + mPendingIntent); + op.addDefaultVerifications(); + try { + Log.i(TAG, "Running .. " + getCurrentTestNode().getName() + " " + sensor.getName()); + op.execute(getCurrentTestNode()); + } finally { + mAlarmManager.cancel(mPendingIntent); + } + return null; + } + + public String runAPWakeUpByAlarmNonWakeSensor(Sensor sensor, int maxReportLatencyUs) + throws Throwable { + int fifoMaxEventCount = sensor.getFifoMaxEventCount(); + if (fifoMaxEventCount == 0) { + throw new SensorTestStateNotSupportedException("Batching not supported."); + } + int maximumExpectedSamplingPeriodUs = sensor.getMaxDelay(); + if (maximumExpectedSamplingPeriodUs == 0 || + maximumExpectedSamplingPeriodUs > 200000) { + // If maxDelay is not defined, set the value for 5 Hz. + maximumExpectedSamplingPeriodUs = 200000; + } + int fifoBasedReportLatencyUs = fifoMaxEventCount * maximumExpectedSamplingPeriodUs; + + // Ensure that FIFO based report latency is at least 20 seconds, we need at least 10 + // seconds of time to allow the device to be in suspend state. + if (fifoBasedReportLatencyUs < 20000000L) { + throw new SensorTestStateNotSupportedException("FIFO too small to test reliably"); + } + + TestSensorEnvironment environment = new TestSensorEnvironment( + this, + sensor, + false, + maximumExpectedSamplingPeriodUs, + maxReportLatencyUs, + true /*isDeviceSuspendTest*/); + + final int ALARM_WAKE_UP_DELAY_MS = 20000; + TestSensorOperation op = TestSensorOperation.createOperation(environment, + mDeviceSuspendLock, + true); + mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + ALARM_WAKE_UP_DELAY_MS, + mPendingIntent); + try { + Log.i(TAG, "Running .. " + getCurrentTestNode().getName() + " " + sensor.getName()); + op.execute(getCurrentTestNode()); + } finally { + mAlarmManager.cancel(mPendingIntent); + } + return null; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MotionIndicatorView.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MotionIndicatorView.java new file mode 100644 index 0000000..12d4582 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MotionIndicatorView.java
@@ -0,0 +1,409 @@ +/* + * Copyright (C) 2013 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; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.RectF; +import android.hardware.SensorManager; +import android.util.AttributeSet; +import android.util.Log; +import android.view.View; + +/** + * A view class that draws the user prompt + * + * The following piece of code should show how to use this view. + * + * public void testUI() { + * final int MAX_TILT_ANGLE = 70; // +/- 70 + * + * final int TILT_ANGLE_STEP = 5; // 5 degree(s) per step + * final int YAW_ANGLE_STEP = 10; // 10 degree(s) per step + * + * RangeCoveredRegister xCovered, yCovered, zCovered; + * xCovered = new RangeCoveredRegister(-MAX_TILT_ANGLE, +MAX_TILT_ANGLE, TILT_ANGLE_STEP); + * + * yCovered = new RangeCoveredRegister(-MAX_TILT_ANGLE, +MAX_TILT_ANGLE, TILT_ANGLE_STEP); + * zCovered = new RangeCoveredRegister(YAW_ANGLE_STEP); + * + * xCovered.update(40); + * xCovered.update(-40); + * xCovered.update(12); + * + * yCovered.update(50); + * yCovered.update(-51); + * + * zCovered.update(150); + * zCovered.update(42); + * + * setDataProvider(xCovered, yCovered, zCovered); + * enableAxis(RVCVRecordActivity.AXIS_ALL); //debug mode, show all three axis + * } + */ +public class MotionIndicatorView extends View { + private final String TAG = "MotionIndicatorView"; + private final boolean LOCAL_LOGV = false; + + private Paint mCursorPaint; + private Paint mLimitPaint; + private Paint mCoveredPaint; + private Paint mRangePaint; + private Paint mEraserPaint; + + // UI settings + private final int XBAR_WIDTH = 50; + private final int XBAR_MARGIN = 50; + private final int XBAR_CURSOR_ADD = 20; + + private final int YBAR_WIDTH = 50; + private final int YBAR_MARGIN = 50; + private final int YBAR_CURSOR_ADD = 20; + + private final int ZRING_WIDTH = 50; + private final int ZRING_CURSOR_ADD = 30; + + + private int mXSize, mYSize; + private RectF mZBoundOut, mZBoundOut2, mZBoundIn, mZBoundIn2; + + private RangeCoveredRegister mXCovered, mYCovered, mZCovered; + + private boolean mXEnabled, mYEnabled, mZEnabled; + + /** + * Constructor + * @param context + */ + public MotionIndicatorView(Context context) { + super(context); + init(); + } + + /** + * Constructor + * @param context Application context + * @param attrs + */ + public MotionIndicatorView(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + /** + * Initialize the Paint objects + */ + private void init() { + + mCursorPaint = new Paint(); + mCursorPaint.setColor(Color.BLUE); + + mLimitPaint = new Paint(); + mLimitPaint.setColor(Color.YELLOW); + + mCoveredPaint = new Paint(); + mCoveredPaint.setColor(Color.CYAN); + + mRangePaint = new Paint(); + mRangePaint.setColor(Color.DKGRAY); + + mEraserPaint = new Paint(); + mEraserPaint.setColor(Color.TRANSPARENT); + // ensure the erasing effect + mEraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); + } + + /** + * Connect the view to certain data provider objects + * @param x Data provider for x direction tilt angle + * @param y Data provider for y direction tilt angle + * @param z Data provider for z rotation + */ + public void setDataProvider(RangeCoveredRegister x, + RangeCoveredRegister y, + RangeCoveredRegister z) { + mXCovered = x; + mYCovered = y; + mZCovered = z; + } + + /** + * Set the active axis for display + * + * @param axis AXIS_X, AXIS_Y, AXIS_Z for x, y, z axis indicators, or AXIS_ALL for all three. + */ + public void enableAxis(int axis) { + mXEnabled = mYEnabled = mZEnabled = false; + + switch(axis) + { + case SensorManager.AXIS_X: + mXEnabled = true; + break; + case SensorManager.AXIS_Y: + mYEnabled = true; + break; + case SensorManager.AXIS_Z: + mZEnabled = true; + break; + case RVCVRecordActivity.AXIS_ALL: + mXEnabled = mYEnabled = mZEnabled = true; + } + } + + /** + * Doing some pre-calculation that only changes when view dimensions are changed. + * @param w + * @param h + * @param oldw + * @param oldh + */ + @Override + protected void onSizeChanged (int w, int h, int oldw, int oldh) { + mXSize = w; + mYSize = h; + + mZBoundOut = new RectF(w/2-w/2.5f, h/2-w/2.5f, w/2+w/2.5f, h/2+w/2.5f); + mZBoundOut2 = new RectF( + w/2-w/2.5f-ZRING_CURSOR_ADD, h/2-w/2.5f-ZRING_CURSOR_ADD, + w/2+w/2.5f+ZRING_CURSOR_ADD, h/2+w/2.5f+ZRING_CURSOR_ADD); + mZBoundIn = new RectF( + w/2-w/2.5f+ZRING_WIDTH, h/2-w/2.5f+ZRING_WIDTH, + w/2+w/2.5f-ZRING_WIDTH, h/2+w/2.5f-ZRING_WIDTH); + mZBoundIn2 = new RectF( + w/2-w/2.5f+ZRING_WIDTH+ZRING_CURSOR_ADD, h/2-w/2.5f+ZRING_WIDTH+ZRING_CURSOR_ADD, + w/2+w/2.5f-ZRING_WIDTH-ZRING_CURSOR_ADD, h/2+w/2.5f-ZRING_WIDTH-ZRING_CURSOR_ADD); + + if (LOCAL_LOGV) Log.v(TAG, "New view size = ("+w+", "+h+")"); + } + + /** + * Draw UI depends on the selected axis and registered value + * + * @param canvas the canvas to draw on + */ + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + int i,t; + + Paint p = new Paint(); + p.setColor(Color.YELLOW); + canvas.drawRect(10,10, 50, 50, p); + + if (mXEnabled && mXCovered != null) { + int xNStep = mXCovered.getNSteps() + 4; // two on each side as a buffer + int xStepSize = mXSize * 3/4 / xNStep; + int xLeft = mXSize * 1/8 + (mXSize * 3/4 % xNStep)/2; + + // base bar + canvas.drawRect(xLeft, XBAR_MARGIN, + xLeft+xStepSize*xNStep-1, XBAR_WIDTH+XBAR_MARGIN, mRangePaint); + + // covered range + for (i=0; i<mXCovered.getNSteps(); ++i) { + if (mXCovered.isCovered(i)) { + canvas.drawRect( + xLeft+xStepSize*(i+2), XBAR_MARGIN, + xLeft+xStepSize*(i+3)-1, XBAR_WIDTH + XBAR_MARGIN, + mCoveredPaint); + } + } + + // limit + canvas.drawRect(xLeft+xStepSize*2-4, XBAR_MARGIN, + xLeft+xStepSize*2+3, XBAR_WIDTH+XBAR_MARGIN, mLimitPaint); + canvas.drawRect(xLeft+xStepSize*(xNStep-2)-4, XBAR_MARGIN, + xLeft+xStepSize*(xNStep-2)+3, XBAR_WIDTH+XBAR_MARGIN, mLimitPaint); + + // cursor + t = (int)(xLeft+xStepSize*(mXCovered.getLastValue()+2)); + canvas.drawRect(t-4, XBAR_MARGIN-XBAR_CURSOR_ADD, t+3, + XBAR_WIDTH+XBAR_MARGIN+XBAR_CURSOR_ADD, mCursorPaint); + } + if (mYEnabled && mYCovered != null) { + int yNStep = mYCovered.getNSteps() + 4; // two on each side as a buffer + int yStepSize = mYSize * 3/4 / yNStep; + int yLeft = mYSize * 1/8 + (mYSize * 3/4 % yNStep)/2; + + // base bar + canvas.drawRect(YBAR_MARGIN, yLeft, + YBAR_WIDTH+YBAR_MARGIN, yLeft+yStepSize*yNStep-1, mRangePaint); + + // covered range + for (i=0; i<mYCovered.getNSteps(); ++i) { + if (mYCovered.isCovered(i)) { + canvas.drawRect( + YBAR_MARGIN, yLeft+yStepSize*(i+2), + YBAR_WIDTH + YBAR_MARGIN, yLeft+yStepSize*(i+3)-1, + mCoveredPaint); + } + } + + // limit + canvas.drawRect(YBAR_MARGIN, yLeft + yStepSize * 2 - 4, + YBAR_WIDTH + YBAR_MARGIN, yLeft + yStepSize * 2 + 3, mLimitPaint); + canvas.drawRect(YBAR_MARGIN, yLeft + yStepSize * (yNStep - 2) - 4, + YBAR_WIDTH + YBAR_MARGIN, yLeft + yStepSize * (yNStep - 2) + 3, mLimitPaint); + + // cursor + t = (int)(yLeft+yStepSize*(mYCovered.getLastValue()+2)); + canvas.drawRect( YBAR_MARGIN-YBAR_CURSOR_ADD, t-4, + YBAR_WIDTH+YBAR_MARGIN+YBAR_CURSOR_ADD, t+3, mCursorPaint); + } + + if (mZEnabled && mZCovered != null) { + float stepSize = 360.0f/mZCovered.getNSteps(); + + // base bar + canvas.drawArc(mZBoundOut,0, 360, true, mRangePaint); + + // covered range + for (i=0; i<mZCovered.getNSteps(); ++i) { + if (mZCovered.isCovered(i)) { + canvas.drawArc(mZBoundOut,i*stepSize-0.2f, stepSize+0.4f, + true, mCoveredPaint); + } + } + // clear center + canvas.drawArc(mZBoundIn, 0, 360, true, mEraserPaint); + // cursor + canvas.drawArc(mZBoundOut2, mZCovered.getLastValue()*stepSize- 1, 2, + true, mCursorPaint); + canvas.drawArc(mZBoundIn2, mZCovered.getLastValue()*stepSize-1.5f, 3, + true, mEraserPaint); + } + } +} + +/** + * A range register class for the RVCVRecord Activity + */ +class RangeCoveredRegister { + enum MODE { + LINEAR, + ROTATE2D + } + + private boolean[] mCovered; + private MODE mMode; + private int mStep; + private int mLow, mHigh; + private int mLastData; + + // high is not inclusive + RangeCoveredRegister(int low, int high, int step) { + mMode = MODE.LINEAR; + mStep = step; + mLow = low; + mHigh = high; + init(); + } + + RangeCoveredRegister(int step) { + mMode = MODE.ROTATE2D; + mStep = step; + mLow = 0; + mHigh = 360; + init(); + } + + private void init() { + if (mMode == MODE.LINEAR) { + mCovered = new boolean[(mHigh-mLow)/mStep]; + }else { + mCovered = new boolean[360/mStep]; + } + } + + /** + * Test if the range defined is fully covered. + * + * @return if the range is fully covered, return true; otherwise false. + */ + public boolean isFullyCovered() { + for (boolean i:mCovered) { + if (!i) return false; + } + return true; + } + + /** + * Test if a specific step is covered. + * + * @param i the step number + * @return if the step specified is covered, return true; otherwise false. + */ + public boolean isCovered(int i) { + return mCovered[i]; + } + + /** + * + * + * @param data + * @return if this update changes the status of + */ + public boolean update(int data) { + mLastData = data; + + if (mMode == MODE.ROTATE2D) { + data %= 360; + } + + int iStep = (data - mLow)/mStep; + + if (iStep>=0 && iStep<getNSteps()) { + // only record valid data + mLastData = data; + + if (mCovered[iStep]) { + return false; + } else { + mCovered[iStep] = true; + return true; + } + } + return false; + } + + /** + * Get the number of steps in this register + * + * @return The number of steps in this register + */ + public int getNSteps() { + //if (mCovered == null) { + //return 0; + //} + return mCovered.length; + } + + /** + * Get the last value updated + * + * @return The last value updated + */ + public float getLastValue() { + // ensure float division + return ((float)(mLastData - mLow))/mStep; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVCameraPreview.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVCameraPreview.java new file mode 100644 index 0000000..fa89b71 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVCameraPreview.java
@@ -0,0 +1,136 @@ +/* + * Copyright (C) 2013 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; + +// ---------------------------------------------------------------------- + +import android.content.Context; +import android.hardware.Camera; +import android.util.AttributeSet; +import android.util.Log; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.ViewGroup; + +import java.io.IOException; + +/** Camera preview class */ +public class RVCVCameraPreview extends SurfaceView implements SurfaceHolder.Callback { + private static final String TAG = "RVCVCameraPreview"; + private static final boolean LOCAL_LOGD = true; + + private SurfaceHolder mHolder; + private Camera mCamera; + private float mAspect; + private int mRotation; + + /** + * Constructor + * @param context Activity context + */ + public RVCVCameraPreview(Context context) { + super(context); + mCamera = null; + initSurface(); + } + + /** + * Constructor + * @param context Activity context + * @param attrs + */ + public RVCVCameraPreview(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public void init(Camera camera, float aspectRatio, int rotation) { + this.mCamera = camera; + mAspect = aspectRatio; + mRotation = rotation; + initSurface(); + } + + private void initSurface() { + // Install a SurfaceHolder.Callback so we get notified when the + // underlying surface is created and destroyed. + mHolder = getHolder(); + mHolder.addCallback(this); + + // deprecated + // TODO: update this code to match new API level. + mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); + } + + /** + * SurfaceHolder.Callback + * Surface is created, it is OK to start the camera preview now. + */ + public void surfaceCreated(SurfaceHolder holder) { + // The Surface has been created, now tell the camera where to draw the preview. + + if (mCamera == null) { + // preview camera does not exist + return; + } + + try { + mCamera.setPreviewDisplay(holder); + mCamera.startPreview(); + int v_height = getHeight(); + int v_width = getWidth(); + ViewGroup.LayoutParams layout = getLayoutParams(); + if ( (float)v_height/v_width > + mAspect) { + layout.height = (int)(v_width * mAspect); + layout.width = v_width; + }else { + layout.width = (int)(v_height / mAspect); + layout.height = v_height; + } + Log.d(TAG, String.format("Layout (%d, %d) -> (%d, %d)", v_width, v_height, + layout.width, layout.height)); + setLayoutParams(layout); + } catch (IOException e) { + if (LOCAL_LOGD) Log.d(TAG, "Error when starting camera preview: " + e.getMessage()); + } + } + /** + * SurfaceHolder.Callback + */ + public void surfaceDestroyed(SurfaceHolder holder) { + // empty. Take care of releasing the Camera preview in your activity. + } + + /** + * SurfaceHolder.Callback + * Restart camera preview if surface changed + */ + public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { + + if (mHolder.getSurface() == null || mCamera == null){ + // preview surface or camera does not exist + return; + } + + // stop preview before making changes + mCamera.stopPreview(); + + mCamera.setDisplayOrientation(mRotation); + + //do the same as if it is created again + surfaceCreated(holder); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVRecordActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVRecordActivity.java new file mode 100644 index 0000000..be5ec52 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVRecordActivity.java
@@ -0,0 +1,993 @@ +/* + * Copyright (C) 2007 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; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.hardware.Camera; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.media.AudioManager; +import android.media.CamcorderProfile; +import android.media.MediaRecorder; +import android.media.SoundPool; +import android.net.Uri; +import android.os.Bundle; +import android.os.Environment; +import android.util.JsonWriter; +import android.util.Log; +import android.view.Window; +import android.widget.ImageView; +import android.widget.Toast; + +import com.android.cts.verifier.R; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + + +// ---------------------------------------------------------------------- + +/** + * An activity that does recording of the camera video and rotation vector data at the same time. + */ +public class RVCVRecordActivity extends Activity { + private static final String TAG = "RVCVRecordActivity"; + private static final boolean LOCAL_LOGV = false; + + private MotionIndicatorView mIndicatorView; + + private SoundPool mSoundPool; + private int [] mSoundPoolLookup; + + private File mRecordDir; + private RecordProcedureController mController; + private VideoRecorder mVideoRecorder; + private RVSensorLogger mRVSensorLogger; + private CoverageManager mCoverManager; + private CameraContext mCameraContext; + + public static final int AXIS_NONE = 0; + public static final int AXIS_ALL = SensorManager.AXIS_X + + SensorManager.AXIS_Y + + SensorManager.AXIS_Z; + + // For Rotation Vector algorithm research use + private final static boolean LOG_RAW_SENSORS = false; + private RawSensorLogger mRawSensorLogger; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Hide the window title. + requestWindowFeature(Window.FEATURE_NO_TITLE); + + // inflate xml + setContentView(R.layout.cam_preview_overlay); + + // locate views + mIndicatorView = (MotionIndicatorView) findViewById(R.id.cam_indicator); + + initStoragePath(); + } + + @Override + protected void onPause() { + super.onPause(); + mController.quit(); + + mCameraContext.end(); + endSoundPool(); + } + + @Override + protected void onResume() { + super.onResume(); + // delay the initialization as much as possible + init(); + } + + /** display toast message + * + * @param msg Message content + */ + private void message(String msg) { + + Context context = getApplicationContext(); + int duration = Toast.LENGTH_SHORT; + + Toast toast = Toast.makeText(context, msg, duration); + toast.show(); + } + + /** + * Initialize components + * + */ + private void init() { + mCameraContext = new CameraContext(); + mCameraContext.init(); + + mCoverManager = new CoverageManager(); + mIndicatorView.setDataProvider( + mCoverManager.getAxis(SensorManager.AXIS_X), + mCoverManager.getAxis(SensorManager.AXIS_Y), + mCoverManager.getAxis(SensorManager.AXIS_Z) ); + + initSoundPool(); + mRVSensorLogger = new RVSensorLogger(this); + + mVideoRecorder = new VideoRecorder(mCameraContext.getCamera(), mCameraContext.getProfile()); + + if (LOG_RAW_SENSORS) { + mRawSensorLogger = new RawSensorLogger(mRecordDir); + } + + mController = new RecordProcedureController(this); + } + + /** + * Notify recording is completed. This is the successful exit. + */ + public void notifyComplete() { + message("Capture completed!"); + + Uri resultUri = Uri.fromFile(mRecordDir); + Intent result = new Intent(); + result.setData(resultUri); + setResult(Activity.RESULT_OK, result); + + finish(); + } + + /** + * Notify the user what to do next in text + * + * @param axis SensorManager.AXIS_X or SensorManager.AXIS_Y or SensorManager.AXIS_Z + */ + private void notifyPrompt(int axis) { + // It is not XYZ because of earlier design have different definition of + // X and Y + final String axisName = "YXZ"; + + message("Manipulate the device in " + axisName.charAt(axis - 1) + + " axis (as illustrated) about the pattern."); + } + + /** + * Ask indicator view to redraw + */ + private void redrawIndicator() { + mIndicatorView.invalidate(); + } + + /** + * Switch to a different axis for display and logging + * @param axis + */ + private void switchAxis(int axis) { + ImageView imageView = (ImageView) findViewById(R.id.cam_overlay); + + final int [] prompts = {R.drawable.prompt_x, R.drawable.prompt_y, R.drawable.prompt_z}; + + if (axis >=SensorManager.AXIS_X && axis <=SensorManager.AXIS_Z) { + imageView.setImageResource(prompts[axis-1]); + mIndicatorView.enableAxis(axis); + mRVSensorLogger.updateRegister(mCoverManager.getAxis(axis), axis); + notifyPrompt(axis); + } else { + imageView.setImageDrawable(null); + mIndicatorView.enableAxis(AXIS_NONE); + } + redrawIndicator(); + } + + /** + * Asynchronized way to call switchAxis. Use this if caller is not on UI thread. + * @param axis @param axis SensorManager.AXIS_X or SensorManager.AXIS_Y or SensorManager.AXIS_Z + */ + public void switchAxisAsync(int axis) { + // intended to be called from a non-UI thread + final int fAxis = axis; + runOnUiThread(new Runnable() { + public void run() { + // UI code goes here + switchAxis(fAxis); + } + }); + } + + /** + * Initialize sound pool for user notification + */ + private void initSoundPool() { + final int MAX_STREAM = 10; + int i=0; + mSoundPool = new SoundPool(MAX_STREAM, AudioManager.STREAM_MUSIC, 0); + mSoundPoolLookup = new int[MAX_STREAM]; + + // TODO: add different sound into this + mSoundPoolLookup[i++] = mSoundPool.load(this, R.raw.next_axis, 1); + mSoundPoolLookup[i++] = mSoundPool.load(this, R.raw.next_axis, 1); + mSoundPoolLookup[i++] = mSoundPool.load(this, R.raw.next_axis, 1); + + } + private void endSoundPool() { + mSoundPool.release(); + } + + /** + * Play notify sound to user + * @param id ID of the sound to be played + */ + public void playNotifySound(int id) { + mSoundPool.play(mSoundPoolLookup[id], 1, 1, 0, 0, 1); + } + + /** + * Start the sensor recording + */ + public void startRecordSensor() { + runOnUiThread(new Runnable() { + public void run() { + mRVSensorLogger.init(); + if (LOG_RAW_SENSORS) { + mRawSensorLogger.init(); + } + } + }); + } + + /** + * Stop the sensor recording + */ + public void stopRecordSensor() { + runOnUiThread(new Runnable() { + public void run() { + mRVSensorLogger.end(); + if (LOG_RAW_SENSORS) { + mRawSensorLogger.end(); + } + } + }); + } + + /** + * Start video recording + */ + public void startRecordVideo() { + mVideoRecorder.init(); + } + + /** + * Stop video recording + */ + public void stopRecordVideo() { + mVideoRecorder.end(); + } + + /** + * Wait until a sensor recording for a certain axis is fully covered + * @param axis + */ + public void waitUntilCovered(int axis) { + mCoverManager.waitUntilCovered(axis); + } + + + /** + * + */ + private void initStoragePath() { + File rxcvRecDataDir = new File(Environment.getExternalStorageDirectory(),"RVCVRecData"); + + // Create the storage directory if it does not exist + if (! rxcvRecDataDir.exists()) { + if (! rxcvRecDataDir.mkdirs()) { + Log.e(TAG, "failed to create main data directory"); + } + } + + mRecordDir = new File(rxcvRecDataDir, new SimpleDateFormat("yyMMdd-hhmmss").format(new Date())); + + if (! mRecordDir.mkdirs()) { + Log.e(TAG, "failed to create rec data directory"); + } + } + + /** + * Get the sensor log file path + * @return Path of the sensor log file + */ + public String getSensorLogFilePath() { + return new File(mRecordDir, "sensor.log").getPath(); + } + + /** + * Get the video recording file path + * @return Path of the video recording file + */ + public String getVideoRecFilePath() { + return new File(mRecordDir, "video.mp4").getPath(); + } + + /** + * Write out important camera/video information to a JSON file + * @param width width of frame + * @param height height of frame + * @param frameRate frame rate in fps + * @param fovW field of view in width direction + * @param fovH field of view in height direction + */ + public void writeVideoMetaInfo(int width, int height, float frameRate, float fovW, float fovH) { + try { + JsonWriter writer = + new JsonWriter( + new OutputStreamWriter( + new FileOutputStream( + new File(mRecordDir, "videometa.json").getPath() + ) + ) + ); + writer.beginObject(); + writer.name("fovW").value(fovW); + writer.name("fovH").value(fovH); + writer.name("width").value(width); + writer.name("height").value(height); + writer.name("frameRate").value(frameRate); + writer.endObject(); + + writer.close(); + }catch (FileNotFoundException e) { + // Not very likely to happen + e.printStackTrace(); + }catch (IOException e) { + // do nothing + e.printStackTrace(); + Log.e(TAG, "Writing video meta data failed."); + } + } + + /** + * Camera preview control class + */ + class CameraContext { + private Camera mCamera; + private CamcorderProfile mProfile; + private Camera.CameraInfo mCameraInfo; + + private int [] mPreferredProfiles = { + CamcorderProfile.QUALITY_480P, // smaller -> faster + CamcorderProfile.QUALITY_720P, + CamcorderProfile.QUALITY_1080P, + CamcorderProfile.QUALITY_HIGH // existence guaranteed + }; + + CameraContext() { + try { + mCamera = Camera.open(); // attempt to get a default Camera instance (0) + mProfile = null; + if (mCamera != null) { + mCameraInfo = new Camera.CameraInfo(); + Camera.getCameraInfo(0, mCameraInfo); + setupCamera(); + } + } + catch (Exception e){ + // Camera is not available (in use or does not exist) + Log.e(TAG, "Cannot obtain Camera!"); + } + } + + /** + * Find a preferred camera profile and set preview and picture size property accordingly. + */ + void setupCamera() { + CamcorderProfile profile = null; + Camera.Parameters param = mCamera.getParameters(); + List<Camera.Size> pre_sz = param.getSupportedPreviewSizes(); + List<Camera.Size> pic_sz = param.getSupportedPictureSizes(); + + for (int i : mPreferredProfiles) { + if (CamcorderProfile.hasProfile(i)) { + profile = CamcorderProfile.get(i); + + int valid = 0; + for (Camera.Size j : pre_sz) { + if (j.width == profile.videoFrameWidth && + j.height == profile.videoFrameHeight) { + ++valid; + break; + } + } + for (Camera.Size j : pic_sz) { + if (j.width == profile.videoFrameWidth && + j.height == profile.videoFrameHeight) { + ++valid; + break; + } + } + if (valid == 2) { + param.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight); + param.setPictureSize(profile.videoFrameWidth, profile.videoFrameHeight); + mCamera.setParameters(param); + break; + } else { + profile = null; + } + } + } + if (profile != null) { + float fovW = param.getHorizontalViewAngle(); + float fovH = param.getVerticalViewAngle(); + writeVideoMetaInfo(profile.videoFrameWidth, profile.videoFrameHeight, + profile.videoFrameRate, fovW, fovH); + } else { + Log.e(TAG, "Cannot find a proper video profile"); + } + mProfile = profile; + + } + + + /** + * Get sensor information of the camera being used + */ + public Camera.CameraInfo getCameraInfo() { + return mCameraInfo; + } + + /** + * Get the camera to be previewed + * @return Reference to Camera used + */ + public Camera getCamera() { + return mCamera; + } + + /** + * Get the camera profile to be used + * @return Reference to Camera profile + */ + public CamcorderProfile getProfile() { + return mProfile; + } + + /** + * Setup the camera + */ + public void init() { + if (mCamera != null) { + double alpha = mCamera.getParameters().getHorizontalViewAngle()*Math.PI/180.0; + int width = mProfile.videoFrameWidth; + double fx = width/2/Math.tan(alpha/2.0); + + if (LOCAL_LOGV) Log.v(TAG, "View angle=" + + mCamera.getParameters().getHorizontalViewAngle() +" Estimated fx = "+fx); + + RVCVCameraPreview cameraPreview = + (RVCVCameraPreview) findViewById(R.id.cam_preview); + cameraPreview.init(mCamera, + (float)mProfile.videoFrameWidth/mProfile.videoFrameHeight, + mCameraInfo.orientation); + } else { + message("Cannot open camera!"); + finish(); + } + } + + /** + * End the camera preview + */ + public void end() { + if (mCamera != null) { + mCamera.release(); // release the camera for other applications + mCamera = null; + } + } + } + + /** + * Manage a set of RangeCoveredRegister objects + */ + class CoverageManager { + // settings + private final int MAX_TILT_ANGLE = 60; // +/- 60 + //private final int REQUIRED_TILT_ANGLE = 50; // +/- 50 + private final int TILT_ANGLE_STEP = 5; // 5 degree(s) per step + private final int YAW_ANGLE_STEP = 10; // 10 degree(s) per step + + RangeCoveredRegister[] mAxisCovered; + + CoverageManager() { + mAxisCovered = new RangeCoveredRegister[3]; + // X AXIS + mAxisCovered[0] = new RangeCoveredRegister(-MAX_TILT_ANGLE, +MAX_TILT_ANGLE, TILT_ANGLE_STEP); + // Y AXIS + mAxisCovered[1] = new RangeCoveredRegister(-MAX_TILT_ANGLE, +MAX_TILT_ANGLE, TILT_ANGLE_STEP); + // Z AXIS + mAxisCovered[2] = new RangeCoveredRegister(YAW_ANGLE_STEP); + } + + public RangeCoveredRegister getAxis(int axis) { + // SensorManager.AXIS_X = 1, need offset -1 for mAxisCovered array + return mAxisCovered[axis-1]; + } + + public void waitUntilCovered(int axis) { + // SensorManager.AXIS_X = 1, need offset -1 for mAxisCovered array + while(!mAxisCovered[axis-1].isFullyCovered()) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + if (LOCAL_LOGV) { + Log.v(TAG, "waitUntilCovered axis = "+ axis + " is interrupted"); + } + } + } + } + } + //////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * A class controls the video recording + */ + class VideoRecorder + { + private MediaRecorder mRecorder; + private CamcorderProfile mProfile; + private Camera mCamera; + private boolean mRunning = false; + + VideoRecorder(Camera camera, CamcorderProfile profile){ + mCamera = camera; + mProfile = profile; + } + + /** + * Initialize and start recording + */ + public void init() { + if (mCamera == null || mProfile ==null){ + return; + } + + mRecorder = new MediaRecorder(); + mCamera.unlock(); + mRecorder.setCamera(mCamera); + + mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); + mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); + + mRecorder.setProfile(mProfile); + + try { + mRecorder.setOutputFile(getVideoRecFilePath()); + mRecorder.prepare(); + } catch (IOException e) { + Log.e(TAG, "Preparation for recording failed."); + return; + } + + try { + mRecorder.start(); + } catch (RuntimeException e) { + Log.e(TAG, "Starting recording failed."); + mRecorder.reset(); + mRecorder.release(); + mCamera.lock(); + return; + } + mRunning = true; + } + + /** + * Stop recording + */ + public void end() { + if (mRunning) { + try { + mRecorder.stop(); + mRecorder.reset(); + mRecorder.release(); + mCamera.lock(); + } catch (RuntimeException e) { + e.printStackTrace(); + Log.e(TAG, "Runtime error in stopping recording."); + } + } + mRecorder = null; + } + + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Log all raw sensor readings, for Rotation Vector sensor algorithms research + */ + class RawSensorLogger implements SensorEventListener { + private final String TAG = "RawSensorLogger"; + + private final static int SENSOR_RATE = SensorManager.SENSOR_DELAY_FASTEST; + private File mRecPath; + + SensorManager mSensorManager; + Sensor mAccSensor, mGyroSensor, mMagSensor; + OutputStreamWriter mAccLogWriter, mGyroLogWriter, mMagLogWriter; + + private float[] mRTemp = new float[16]; + + RawSensorLogger(File recPath) { + mRecPath = recPath; + } + + /** + * Initialize and start recording + */ + public void init() { + mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + + mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED); + mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED); + + mSensorManager.registerListener(this, mAccSensor, SENSOR_RATE); + mSensorManager.registerListener(this, mGyroSensor, SENSOR_RATE); + mSensorManager.registerListener(this, mMagSensor, SENSOR_RATE); + + try { + mAccLogWriter= new OutputStreamWriter( + new FileOutputStream(new File(mRecPath, "raw_acc.log"))); + mGyroLogWriter= new OutputStreamWriter( + new FileOutputStream(new File(mRecPath, "raw_uncal_gyro.log"))); + mMagLogWriter= new OutputStreamWriter( + new FileOutputStream(new File(mRecPath, "raw_uncal_mag.log"))); + + } catch (FileNotFoundException e) { + Log.e(TAG, "Sensor log file open failed: " + e.toString()); + } + } + + /** + * Stop recording and clean up + */ + public void end() { + mSensorManager.flush(this); + mSensorManager.unregisterListener(this); + + try { + if (mAccLogWriter != null) { + OutputStreamWriter writer = mAccLogWriter; + mAccLogWriter = null; + writer.close(); + } + if (mGyroLogWriter != null) { + OutputStreamWriter writer = mGyroLogWriter; + mGyroLogWriter = null; + writer.close(); + } + if (mMagLogWriter != null) { + OutputStreamWriter writer = mMagLogWriter; + mMagLogWriter = null; + writer.close(); + } + + } catch (IOException e) { + Log.e(TAG, "Sensor log file close failed: " + e.toString()); + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int i) { + // do not care + } + + @Override + public void onSensorChanged(SensorEvent event) { + OutputStreamWriter writer=null; + switch(event.sensor.getType()) { + case Sensor.TYPE_ACCELEROMETER: + writer = mAccLogWriter; + break; + case Sensor.TYPE_GYROSCOPE_UNCALIBRATED: + writer = mGyroLogWriter; + break; + case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED: + writer = mMagLogWriter; + break; + + } + if (writer!=null) { + float[] data = event.values; + try { + if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { + writer.write(String.format("%d %f %f %f\r\n", + event.timestamp, data[0], data[1], data[2])); + }else // TYPE_GYROSCOPE_UNCALIBRATED and TYPE_MAGNETIC_FIELD_UNCALIBRATED + { + writer.write(String.format("%d %f %f %f %f %f %f\r\n", event.timestamp, + data[0], data[1], data[2], data[3], data[4], data[5])); + } + }catch (IOException e) + { + Log.e(TAG, "Write to raw sensor log file failed."); + } + + } + } + } + + /** + * Rotation sensor logger class + */ + class RVSensorLogger implements SensorEventListener { + private final String TAG = "RVSensorLogger"; + + private final static int SENSOR_RATE = SensorManager.SENSOR_DELAY_FASTEST; + RangeCoveredRegister mRegister; + int mAxis; + RVCVRecordActivity mActivity; + + SensorManager mSensorManager; + Sensor mRVSensor; + OutputStreamWriter mLogWriter; + + private float[] mRTemp = new float[16]; + + RVSensorLogger(RVCVRecordActivity activity) { + mActivity = activity; + } + + /** + * Initialize and start recording + */ + public void init() { + mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + if (mSensorManager == null) { + Log.e(TAG,"SensorManager is null!"); + } + mRVSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); + if (mRVSensor != null) { + if (LOCAL_LOGV) Log.v(TAG, "Got RV Sensor"); + }else { + Log.e(TAG, "Did not get RV sensor"); + } + if(mSensorManager.registerListener(this, mRVSensor, SENSOR_RATE)) { + if (LOCAL_LOGV) Log.v(TAG,"Register listener successfull"); + } else { + Log.e(TAG,"Register listener failed"); + } + + try { + mLogWriter= new OutputStreamWriter( + new FileOutputStream(mActivity.getSensorLogFilePath())); + } catch (FileNotFoundException e) { + Log.e(TAG, "Sensor log file open failed: " + e.toString()); + } + } + + /** + * Stop recording and clean up + */ + public void end() { + mSensorManager.flush(this); + mSensorManager.unregisterListener(this); + + try { + if (mLogWriter != null) { + OutputStreamWriter writer = mLogWriter; + mLogWriter = null; + writer.close(); + } + } catch (IOException e) { + Log.e(TAG, "Sensor log file close failed: " + e.toString()); + } + + updateRegister(null, AXIS_NONE); + } + + private void onNewData(float[] data, long timestamp) { + // LOG + try { + if (mLogWriter != null) { + mLogWriter.write(String.format("%d %f %f %f %f\r\n", timestamp, + data[3], data[0], data[1], data[2])); + } + } catch (IOException e) { + Log.e(TAG, "Sensor log file write failed: " + e.toString()); + } + + // Update UI + if (mRegister != null) { + int d = 0; + int dx, dy, dz; + boolean valid = false; + SensorManager.getRotationMatrixFromVector(mRTemp, data); + + dx = (int)(Math.asin(mRTemp[8])*(180.0/Math.PI)); + dy = (int)(Math.asin(mRTemp[9])*(180.0/Math.PI)); + dz = (int)((Math.atan2(mRTemp[4], mRTemp[0])+Math.PI)*(180.0/Math.PI)); + + switch(mAxis) { + case SensorManager.AXIS_X: + d = dx; + valid = (Math.abs(dy) < 30); + break; + case SensorManager.AXIS_Y: + d = dy; + valid = (Math.abs(dx) < 30); + break; + case SensorManager.AXIS_Z: + d = dz; + valid = (Math.abs(dx) < 20 && Math.abs(dy) < 20); + break; + } + + if (valid) { + mRegister.update(d); + mActivity.redrawIndicator(); + } + } + + } + + public void updateRegister(RangeCoveredRegister reg, int axis) { + mRegister = reg; + mAxis = axis; + } + + + @Override + public void onAccuracyChanged(Sensor sensor, int i) { + // do not care + } + + @Override + public void onSensorChanged(SensorEvent event) { + if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) { + onNewData(event.values, event.timestamp); + } + } + } + + + //////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Controls the over all logic of record procedure: first x-direction, then y-direction and + * then z-direction. + */ + class RecordProcedureController implements Runnable { + private static final boolean LOCAL_LOGV = false; + + private final RVCVRecordActivity mActivity; + private Thread mThread = null; + + RecordProcedureController(RVCVRecordActivity activity) { + mActivity = activity; + mThread = new Thread(this); + mThread.start(); + } + + /** + * Run the record procedure + */ + public void run() { + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread Started."); + //start recording & logging + delay(2000); + + init(); + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread init() finished."); + + // test 3 axis + // It is in YXZ order because UI element design use opposite definition + // of XY axis. To ensure the user see X Y Z, it is flipped here. + recordAxis(SensorManager.AXIS_Y); + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread axis 0 finished."); + + recordAxis(SensorManager.AXIS_X); + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread axis 1 finished."); + + recordAxis(SensorManager.AXIS_Z); + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread axis 2 finished."); + + delay(1000); + end(); + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread End."); + } + + private void delay(int milli) { + try{ + Thread.sleep(milli); + } catch(InterruptedException e) { + if (LOCAL_LOGV) Log.v(TAG, "Controller Thread Interrupted."); + } + } + private void init() { + // start video recording + mActivity.startRecordVideo(); + + // start sensor logging & listening + mActivity.startRecordSensor(); + } + + private void end() { + // stop video recording + mActivity.stopRecordVideo(); + + // stop sensor logging + mActivity.stopRecordSensor(); + + // notify ui complete + runOnUiThread(new Runnable(){ + public void run() { + mActivity.notifyComplete(); + } + }); + } + + private void recordAxis(int axis) { + // delay 2 seconds? + delay(1000); + + // change ui + mActivity.switchAxisAsync(axis); + + // play start sound + mActivity.playNotifySound(0); + + // wait until axis covered + mActivity.waitUntilCovered(axis); + + // play stop sound + mActivity.playNotifySound(1); + } + + /** + * Force quit + */ + public void quit() { + mThread.interrupt(); + try { + if (LOCAL_LOGV) Log.v(TAG, "Wait for controller to end"); + + // stop video recording + mActivity.stopRecordVideo(); + + // stop sensor logging + mActivity.stopRecordSensor(); + + } catch (Exception e) + { + e.printStackTrace(); + } + } + } + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckAnalyzer.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckAnalyzer.java new file mode 100644 index 0000000..3dc7270 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckAnalyzer.java
@@ -0,0 +1,1322 @@ +package com.android.cts.verifier.sensors; + +/* + * 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. + */ +import android.media.MediaCodec; +import android.media.MediaExtractor; +import android.media.MediaFormat; +import android.os.Debug; +import android.os.Environment; +import android.os.PowerManager; +import android.util.JsonWriter; +import android.util.Log; + +import org.opencv.core.Mat; +import org.opencv.core.CvType; +import org.opencv.core.MatOfDouble; +import org.opencv.core.MatOfFloat; +import org.opencv.core.MatOfPoint2f; +import org.opencv.core.MatOfPoint3f; +import org.opencv.core.Size; +import org.opencv.highgui.Highgui; +import org.opencv.imgproc.Imgproc; +import org.opencv.calib3d.Calib3d; +import org.opencv.core.Core; + +import org.json.JSONObject; +import org.json.JSONException; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.ByteBuffer; +import java.util.ArrayList; + +import android.opengl.GLES20; +import javax.microedition.khronos.opengles.GL10; + +/** + * This class does analysis on the recorded RVCVCXCheck data sets. + */ +public class RVCVXCheckAnalyzer { + private static final String TAG = "RVCVXAnalysis"; + private static final boolean LOCAL_LOGV = false; + private static final boolean LOCAL_LOGD = true; + private final String mPath; + + private static final boolean OUTPUT_DEBUG_IMAGE = false; + private static final double VALID_FRAME_THRESHOLD = 0.8; + private static final double REPROJECTION_THREASHOLD = 4.0; + private static final boolean FORCE_CV_ANALYSIS = false; + private static final boolean TRACE_VIDEO_ANALYSIS = false; + private static final double DECIMATION_FPS_TARGET = 15.0; + + RVCVXCheckAnalyzer(String path) + { + mPath = path; + } + + /** + * A class that contains the analysis results + * + */ + class AnalyzeReport { + public boolean error=true; + public String reason = "incomplete"; + + // roll pitch yaw RMS error ( \sqrt{\frac{1}{n} \sum e_i^2 }) + // unit in rad + public double roll_rms_error; + public double pitch_rms_error; + public double yaw_rms_error; + + // roll pitch yaw max error + // unit in rad + public double roll_max_error; + public double pitch_max_error; + public double yaw_max_error; + + // optimal t delta between sensor and camera data set to make best match + public double optimal_delta_t; + // the associate yaw offset based on initial values + public double yaw_offset; + + public int n_of_frame; + public int n_of_valid_frame; + + // both data below are in [sec] + public double sensor_period_avg; + public double sensor_period_stdev; + + /** + * write Json format serialization to a file in case future processing need the data + */ + public void writeToFile(File file) { + try { + writeJSONToStream(new FileOutputStream(file)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot create analyze report file."); + } + } + + /** + * Get the JSON format serialization + *@return Json format serialization as String + */ + @Override + public String toString() { + ByteArrayOutputStream s = new ByteArrayOutputStream(); + writeJSONToStream(s); + return new String(s.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); + } + + private void writeJSONToStream(OutputStream s) { + try{ + JsonWriter writer = + new JsonWriter( + new OutputStreamWriter( s ) + ); + writer.beginObject(); + writer.setLenient(true); + + writer.name("roll_rms_error").value(roll_rms_error); + writer.name("pitch_rms_error").value(pitch_rms_error); + writer.name("yaw_rms_error").value(yaw_rms_error); + writer.name("roll_max_error").value(roll_max_error); + writer.name("pitch_max_error").value(pitch_max_error); + writer.name("yaw_max_error").value(yaw_max_error); + writer.name("optimal_delta_t").value(optimal_delta_t); + writer.name("yaw_offset").value(yaw_offset); + writer.name("n_of_frame").value(n_of_frame); + writer.name("n_of_valid_frame").value(n_of_valid_frame); + writer.name("sensor_period_avg").value(sensor_period_avg); + writer.name("sensor_period_stdev").value(sensor_period_stdev); + + writer.endObject(); + + writer.close(); + } catch (IOException e) { + // do nothing + Log.e(TAG, "Error in serialize analyze report to JSON"); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + Log.e(TAG, "Invalid parameter to write into JSON format"); + } + } + } + + /** + * Process data set stored in the path specified in constructor + * and return an analyze report to caller + * + * @return An AnalyzeReport that contains detailed information about analysis + */ + public AnalyzeReport processDataSet() { + int nframe;// number of frames in video + int nslog; // number of sensor log + int nvlog; // number of video generated log + + + AnalyzeReport report = new AnalyzeReport(); + + ArrayList<AttitudeRec> srecs = new ArrayList<>(); + ArrayList<AttitudeRec> vrecs = new ArrayList<>(); + ArrayList<AttitudeRec> srecs2 = new ArrayList<>(); + + + final boolean use_solved = new File(mPath, "vision_rpy.log").exists() && !FORCE_CV_ANALYSIS; + + if (use_solved) { + nframe = nvlog = loadAttitudeRecs(new File(mPath, "vision_rpy.log"), vrecs); + nslog = loadAttitudeRecs(new File(mPath, "sensor_rpy.log"),srecs); + }else { + nframe = analyzeVideo(vrecs); + nvlog = vrecs.size(); + + if (LOCAL_LOGV) { + Log.v(TAG, "Post video analysis nvlog = " + nvlog + " nframe=" + nframe); + } + if (nvlog <= 0 || nframe <= 0) { + // invalid results + report.reason = "Unable to to load recorded video."; + return report; + } + if ((double) nvlog / nframe < VALID_FRAME_THRESHOLD) { + // too many invalid frames + Log.w(TAG, "Too many invalid frames, n valid frame = " + nvlog + + ", n total frame = " + nframe); + report.reason = "Too many invalid frames."; + return report; + } + + fixFlippedAxis(vrecs); + + nslog = loadSensorLog(srecs); + } + + // Gradient descent will have faster performance than this simple search, + // but the performance is dominated by the vision part, so it is not very necessary. + double delta_t; + double min_rms = Double.MAX_VALUE; + double min_delta_t =0.; + double min_yaw_offset =0.; + + // pre-allocation + for (AttitudeRec i: vrecs) { + srecs2.add(new AttitudeRec(0,0,0,0)); + } + + // find optimal offset + for (delta_t = -2.0; delta_t<2.0; delta_t +=0.01) { + double rms; + resampleSensorLog(srecs, vrecs, delta_t, 0.0, srecs2); + rms = Math.sqrt(calcSqrErr(vrecs, srecs2, 0)+ calcSqrErr(vrecs, srecs2, 1)); + if (rms < min_rms) { + min_rms = rms; + min_delta_t = delta_t; + min_yaw_offset = vrecs.get(0).yaw - srecs2.get(0).yaw; + } + } + // sample at optimal offset + resampleSensorLog(srecs, vrecs, min_delta_t, min_yaw_offset, srecs2); + + if (!use_solved) { + dumpAttitudeRecs(new File(mPath, "vision_rpy.log"), vrecs); + dumpAttitudeRecs(new File(mPath, "sensor_rpy.log"), srecs); + } + dumpAttitudeRecs(new File(mPath, "sensor_rpy_resampled.log"), srecs2); + dumpAttitudeError(new File(mPath, "attitude_error.log"), vrecs, srecs2); + + // fill report fields + report.roll_rms_error = Math.sqrt(calcSqrErr(vrecs, srecs2, 0)); + report.pitch_rms_error = Math.sqrt(calcSqrErr(vrecs, srecs2, 1)); + report.yaw_rms_error = Math.sqrt(calcSqrErr(vrecs, srecs2, 2)); + + report.roll_max_error = calcMaxErr(vrecs, srecs2, 0); + report.pitch_max_error = calcMaxErr(vrecs, srecs2, 1); + report.yaw_max_error = calcMaxErr(vrecs, srecs2, 2); + + report.optimal_delta_t = min_delta_t; + report.yaw_offset = (min_yaw_offset); + + report.n_of_frame = nframe; + report.n_of_valid_frame = nvlog; + + double [] sensor_period_stat = calcSensorPeriodStat(srecs); + report.sensor_period_avg = sensor_period_stat[0]; + report.sensor_period_stdev = sensor_period_stat[1]; + + // output report to file and log in JSON format as well + report.writeToFile(new File(mPath, "report.json")); + if (LOCAL_LOGV) Log.v(TAG, "Report in JSON:" + report.toString()); + + report.reason = "Completed"; + report.error = false; + return report; + } + + /** + * Generate pattern geometry like this one + * http://docs.opencv.org/trunk/_downloads/acircles_pattern.png + * + * @return Array of 3D points + */ + private MatOfPoint3f asymmetricalCircleGrid(Size size) { + final int cn = 3; + + int n = (int)(size.width * size.height); + float positions[] = new float[n * cn]; + float unit=0.02f; + MatOfPoint3f grid = new MatOfPoint3f(); + + for (int i = 0; i < size.height; i++) { + for (int j = 0; j < size.width * cn; j += cn) { + positions[(int) (i * size.width * cn + j + 0)] = + (2 * (j / cn) + i % 2) * (float) unit; + positions[(int) (i * size.width * cn + j + 1)] = + i * unit; + positions[(int) (i * size.width * cn + j + 2)] = 0; + } + } + grid.create(n, 1, CvType.CV_32FC3); + grid.put(0, 0, positions); + return grid; + } + + /** + * Create a camera intrinsic matrix using input parameters + * + * The camera intrinsic matrix will be like: + * + * +- -+ + * | f 0 center.width | + * A = | 0 f center.height | + * | 0 0 1 | + * +- -+ + * + * @return An approximated (not actually calibrated) camera matrix + */ + private static Mat cameraMatrix(float f, Size center) { + final double [] data = {f, 0, center.width, 0, f, center.height, 0, 0, 1f}; + Mat m = new Mat(3,3, CvType.CV_64F); + m.put(0, 0, data); + return m; + } + + /** + * Attitude record in time roll pitch yaw format. + * + */ + private class AttitudeRec { + public double time; + public double roll; + public double pitch; + public double yaw; + + // ctor + AttitudeRec(double atime, double aroll, double apitch, double ayaw) { + time = atime; + roll = aroll; + pitch = apitch; + yaw = ayaw; + } + + // ctor + AttitudeRec(double atime, double [] rpy) { + time = atime; + roll = rpy[0]; + pitch = rpy[1]; + yaw = rpy[2]; + } + + // copy value of another to this + void assign(AttitudeRec rec) { + time = rec.time; + roll = rec.time; + pitch = rec.pitch; + yaw = rec.yaw; + } + + // copy roll-pitch-yaw value but leave the time specified by atime + void assign(AttitudeRec rec, double atime) { + time = atime; + roll = rec.time; + pitch = rec.pitch; + yaw = rec.yaw; + } + + // set each field separately + void set(double atime, double aroll, double apitch, double ayaw) { + time = atime; + roll = aroll; + pitch = apitch; + yaw = ayaw; + } + } + + + /** + * Load the sensor log in (time Roll-pitch-yaw) format to a ArrayList<AttitudeRec> + * + * @return the number of sensor log items + */ + private int loadSensorLog(ArrayList<AttitudeRec> recs) { + //ArrayList<AttitudeRec> recs = new ArrayList<AttitudeRec>(); + File csvFile = new File(mPath, "sensor.log"); + BufferedReader br=null; + String line; + + // preallocate and reuse + double [] quat = new double[4]; + double [] rpy = new double[3]; + + double t0 = -1; + + try { + br = new BufferedReader(new FileReader(csvFile)); + while ((line = br.readLine()) != null) { + //space separator + String[] items = line.split(" "); + + if (items.length != 5) { + recs.clear(); + return -1; + } + + quat[0] = Double.parseDouble(items[1]); + quat[1] = Double.parseDouble(items[2]); + quat[2] = Double.parseDouble(items[3]); + quat[3] = Double.parseDouble(items[4]); + + // + quat2rpy(quat, rpy); + + if (t0 < 0) { + t0 = Long.parseLong(items[0])/1e9; + } + recs.add(new AttitudeRec(Long.parseLong(items[0])/1e9-t0, rpy)); + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot find sensor logging data"); + } catch (IOException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot read sensor logging data"); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return recs.size(); + } + + /** + * Read video meta info + */ + private class VideoMetaInfo { + public double fps; + public int frameWidth; + public int frameHeight; + public double fovWidth; + public double fovHeight; + public boolean valid = false; + + VideoMetaInfo(File file) { + + BufferedReader br=null; + String line; + String content=""; + try { + br = new BufferedReader(new FileReader(file)); + while ((line = br.readLine()) != null) { + content = content +line; + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot find video meta info file"); + } catch (IOException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot read video meta info file"); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + if (content.isEmpty()) { + return; + } + + try { + JSONObject json = new JSONObject(content); + frameWidth = json.getInt("width"); + frameHeight = json.getInt("height"); + fps = json.getDouble("frameRate"); + fovWidth = json.getDouble("fovW")*Math.PI/180.0; + fovHeight = json.getDouble("fovH")*Math.PI/180.0; + } catch (JSONException e) { + return; + } + + valid = true; + + } + } + + + + /** + * Debugging helper function, load ArrayList<AttitudeRec> from a file dumped out by + * dumpAttitudeRecs + */ + private int loadAttitudeRecs(File file, ArrayList<AttitudeRec> recs) { + BufferedReader br=null; + String line; + double time; + double [] rpy = new double[3]; + + try { + br = new BufferedReader(new FileReader(file)); + while ((line = br.readLine()) != null) { + //space separator + String[] items = line.split(" "); + + if (items.length != 4) { + recs.clear(); + return -1; + } + + time = Double.parseDouble(items[0]); + rpy[0] = Double.parseDouble(items[1]); + rpy[1] = Double.parseDouble(items[2]); + rpy[2] = Double.parseDouble(items[3]); + + recs.add(new AttitudeRec(time, rpy)); + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot find AttitudeRecs file specified."); + } catch (IOException e) { + e.printStackTrace(); + Log.e(TAG, "Read AttitudeRecs file failure"); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return recs.size(); + } + /** + * Debugging helper function, Dump an ArrayList<AttitudeRec> to a file + */ + private void dumpAttitudeRecs(File file, ArrayList<AttitudeRec> recs) { + OutputStreamWriter w=null; + try { + w = new OutputStreamWriter(new FileOutputStream(file)); + + for (AttitudeRec r : recs) { + w.write(String.format("%f %f %f %f\r\n", r.time, r.roll, r.pitch, r.yaw)); + } + w.close(); + } catch(FileNotFoundException e) { + e.printStackTrace(); + Log.e(TAG, "Cannot create AttitudeRecs file."); + } catch (IOException e) { + Log.e(TAG, "Write AttitudeRecs file failure"); + } finally { + if (w!=null) { + try { + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * Read the sensor log in ArrayList<AttitudeRec> format and find out the sensor sample time + * statistics: mean and standard deviation. + * + * @return The returned value will be a double array with exact 2 items, first [0] will be + * mean and the second [1] will be the standard deviation. + * + */ + private double [] calcSensorPeriodStat(ArrayList<AttitudeRec> srec) { + double tp = srec.get(0).time; + int i; + double sum = 0.0; + double sumsq = 0.0; + for(i=1; i<srec.size(); ++i) { + double dt; + dt = srec.get(i).time - tp; + sum += dt; + sumsq += dt*dt; + tp += dt; + } + double [] ret = new double[2]; + ret[0] = sum/srec.size(); + ret[1] = Math.sqrt(sumsq/srec.size() - ret[0]*ret[0]); + return ret; + } + + /** + * Flipping the axis as the image are flipped upside down in OpenGL frames + */ + private void fixFlippedAxis(ArrayList<AttitudeRec> vrecs) { + for (AttitudeRec i: vrecs) { + i.yaw = -i.yaw; + } + } + + /** + * Calculate the maximum error on the specified axis between two time aligned (resampled) + * ArrayList<AttitudeRec>. Yaw axis needs special treatment as 0 and 2pi error are same thing + * + * @param ra one ArrayList of AttitudeRec + * @param rb the other ArrayList of AttitudeRec + * @param axis axis id for the comparison (0 = roll, 1 = pitch, 2 = yaw) + * @return Maximum error + */ + private double calcMaxErr(ArrayList<AttitudeRec> ra, ArrayList<AttitudeRec> rb, int axis) { + // check if they are valid and comparable data + if (ra.size() != rb.size()) { + throw new ArrayIndexOutOfBoundsException("Two array has to be the same"); + } + // check input parameter validity + if (axis<0 || axis > 2) { + throw new IllegalArgumentException("Invalid data axis."); + } + + int i; + double max = 0.0; + double diff = 0.0; + for(i=0; i<ra.size(); ++i) { + // make sure they are aligned data + if (ra.get(i).time != rb.get(i).time) { + throw new IllegalArgumentException("Element "+i+ + " of two inputs has different time."); + } + switch(axis) { + case 0: + diff = ra.get(i).roll - rb.get(i).roll; // they always opposite of each other.. + break; + case 1: + diff = ra.get(i).pitch - rb.get(i).pitch; + break; + case 2: + diff = Math.abs(((4*Math.PI + ra.get(i).yaw - rb.get(i).yaw)%(2*Math.PI)) + -Math.PI)-Math.PI; + break; + } + diff = Math.abs(diff); + if (diff>max) { + max = diff; + } + } + return max; + } + + /** + * Calculate the RMS error on the specified axis between two time aligned (resampled) + * ArrayList<AttitudeRec>. Yaw axis needs special treatment as 0 and 2pi error are same thing + * + * @param ra one ArrayList of AttitudeRec + * @param rb the other ArrayList of AttitudeRec + * @param axis axis id for the comparison (0 = roll, 1 = pitch, 2 = yaw) + * @return Mean square error + */ + private double calcSqrErr(ArrayList<AttitudeRec> ra, ArrayList<AttitudeRec> rb, int axis) { + // check if they are valid and comparable data + if (ra.size() != rb.size()) { + throw new ArrayIndexOutOfBoundsException("Two array has to be the same"); + } + // check input parameter validity + if (axis<0 || axis > 2) { + throw new IllegalArgumentException("Invalid data axis."); + } + + int i; + double sum = 0.0; + double diff = 0.0; + for(i=0; i<ra.size(); ++i) { + // check input data validity + if (ra.get(i).time != rb.get(i).time) { + throw new IllegalArgumentException("Element "+i+ + " of two inputs has different time."); + } + + switch(axis) { + case 0: + diff = ra.get(i).roll - rb.get(i).roll; + break; + case 1: + diff = ra.get(i).pitch - rb.get(i).pitch; + break; + case 2: + diff = Math.abs(((4*Math.PI + ra.get(i).yaw - rb.get(i).yaw)%(2*Math.PI))- + Math.PI)-Math.PI; + break; + } + + sum += diff*diff; + } + return sum/ra.size(); + } + + /** + * Debugging helper function. Dump the error between two time aligned ArrayList<AttitudeRec>'s + * + * @param file File to write to + * @param ra one ArrayList of AttitudeRec + * @param rb the other ArrayList of AttitudeRec + */ + private void dumpAttitudeError(File file, ArrayList<AttitudeRec> ra, ArrayList<AttitudeRec> rb){ + if (ra.size() != rb.size()) { + throw new ArrayIndexOutOfBoundsException("Two array has to be the same"); + } + + int i; + + ArrayList<AttitudeRec> rerr = new ArrayList<>(); + for(i=0; i<ra.size(); ++i) { + if (ra.get(i).time != rb.get(i).time) { + throw new IllegalArgumentException("Element "+ i + + " of two inputs has different time."); + } + + rerr.add(new AttitudeRec(ra.get(i).time, ra.get(i).roll - rb.get(i).roll, + ra.get(i).pitch - rb.get(i).pitch, + (Math.abs(((4*Math.PI + ra.get(i).yaw - rb.get(i).yaw)%(2*Math.PI)) + -Math.PI)-Math.PI))); + + } + dumpAttitudeRecs(file, rerr); + } + + /** + * Resample one ArrayList<AttitudeRec> with respect to another ArrayList<AttitudeRec> + * + * @param rec the ArrayList of AttitudeRec to be sampled + * @param timebase the other ArrayList of AttitudeRec that serves as time base + * @param delta_t offset in time before resample + * @param yaw_offset offset in yaw axis + * @param resampled output ArrayList of AttitudeRec + */ + + private void resampleSensorLog(ArrayList<AttitudeRec> rec, ArrayList<AttitudeRec> timebase, + double delta_t, double yaw_offset, ArrayList<AttitudeRec> resampled) { + int i; + int j = -1; + for(i=0; i<timebase.size(); i++) { + double time = timebase.get(i).time + delta_t; + + while(j<rec.size()-1 && rec.get(j+1).time < time) j++; + + if (j == -1) { + //use first + resampled.get(i).assign(rec.get(0), timebase.get(i).time); + } else if (j == rec.size()-1) { + // use last + resampled.get(i).assign(rec.get(j), timebase.get(i).time); + } else { + // do linear resample + double alpha = (time - rec.get(j).time)/((rec.get(j+1).time - rec.get(j).time)); + double roll = (1-alpha) * rec.get(j).roll + alpha * rec.get(j+1).roll; + double pitch = (1-alpha) * rec.get(j).pitch + alpha * rec.get(j+1).pitch; + double yaw = (1-alpha) * rec.get(j).yaw + alpha * rec.get(j+1).yaw + yaw_offset; + resampled.get(i).set(timebase.get(i).time, roll, pitch, yaw); + } + } + } + + /** + * Analyze video frames using computer vision approach and generate a ArrayList<AttitudeRec> + * + * @param recs output ArrayList of AttitudeRec + * @return total number of frame of the video + */ + private int analyzeVideo(ArrayList<AttitudeRec> recs) { + VideoMetaInfo meta = new VideoMetaInfo(new File(mPath, "videometa.json")); + + int decimation = 1; + boolean use_timestamp = true; + + // roughly determine if decimation is necessary + if (meta.fps > DECIMATION_FPS_TARGET) { + decimation = (int)(meta.fps / DECIMATION_FPS_TARGET); + meta.fps /=decimation; + } + + VideoDecoderForOpenCV videoDecoder = new VideoDecoderForOpenCV( + new File(mPath, "video.mp4"), decimation); + + + Mat frame; + Mat gray = new Mat(); + int i = -1; + + Size frameSize = videoDecoder.getSize(); + + if (frameSize.width != meta.frameWidth || frameSize.height != meta.frameHeight) { + // this is very unlikely + return -1; + } + + if (TRACE_VIDEO_ANALYSIS) { + Debug.startMethodTracing("cvprocess"); + } + + Size patternSize = new Size(4,11); + + float fc = (float)(meta.frameWidth/2.0/Math.tan(meta.fovWidth/2.0)); + Mat camMat = cameraMatrix(fc, new Size(frameSize.width/2, frameSize.height/2)); + MatOfDouble coeff = new MatOfDouble(); // dummy + + MatOfPoint2f centers = new MatOfPoint2f(); + MatOfPoint3f grid = asymmetricalCircleGrid(patternSize); + Mat rvec = new MatOfFloat(); + Mat tvec = new MatOfFloat(); + + MatOfPoint2f reprojCenters = new MatOfPoint2f(); + + if (LOCAL_LOGV) { + Log.v(TAG, "Camera Mat = \n" + camMat.dump()); + } + + long startTime = System.nanoTime(); + long [] ts = new long[1]; + + while ((frame = videoDecoder.getFrame(ts)) !=null) { + if (LOCAL_LOGV) { + Log.v(TAG, "got a frame " + i); + } + + if (use_timestamp && ts[0] == -1) { + use_timestamp = false; + } + + // has to be in front, as there are cases where execution + // will skip the later part of this while + i++; + + // convert to gray manually as by default findCirclesGridDefault uses COLOR_BGR2GRAY + Imgproc.cvtColor(frame, gray, Imgproc.COLOR_RGB2GRAY); + + boolean foundPattern = Calib3d.findCirclesGridDefault( + gray, patternSize, centers, Calib3d.CALIB_CB_ASYMMETRIC_GRID); + + if (!foundPattern) { + // skip to next frame + continue; + } + + if (OUTPUT_DEBUG_IMAGE) { + Calib3d.drawChessboardCorners(frame, patternSize, centers, true); + } + + // figure out the extrinsic parameters using real ground truth 3D points and the pixel + // position of blobs found in findCircleGrid, an estimated camera matrix and + // no-distortion are assumed. + boolean foundSolution = + Calib3d.solvePnP(grid, centers, camMat, coeff, rvec, tvec, + false, Calib3d.CV_ITERATIVE); + + if (!foundSolution) { + // skip to next frame + if (LOCAL_LOGV) { + Log.v(TAG, "cannot find pnp solution in frame " + i + ", skipped."); + } + continue; + } + + // reproject points to for evaluation of result accuracy of solvePnP + Calib3d.projectPoints(grid, rvec, tvec, camMat, coeff, reprojCenters); + + // error is evaluated in norm2, which is real error in pixel distance / sqrt(2) + double error = Core.norm(centers, reprojCenters, Core.NORM_L2); + + if (LOCAL_LOGV) { + Log.v(TAG, "Found attitude, re-projection error = " + error); + } + + // if error is reasonable, add it into the results + if (error < REPROJECTION_THREASHOLD) { + double [] rv = new double[3]; + double timestamp; + + rvec.get(0,0, rv); + if (use_timestamp) { + timestamp = (double)ts[0] / 1e6; + } else { + timestamp = (double) i / meta.fps; + } + if (LOCAL_LOGV) Log.v(TAG, String.format("Added frame %d ts = %f", i, timestamp)); + recs.add(new AttitudeRec(timestamp, rodr2rpy(rv))); + } + + if (OUTPUT_DEBUG_IMAGE) { + Calib3d.drawChessboardCorners(frame, patternSize, reprojCenters, true); + Highgui.imwrite(Environment.getExternalStorageDirectory().getPath() + + "/RVCVRecData/DebugCV/img" + i + ".png", frame); + } + } + + if (LOCAL_LOGV) { + Log.v(TAG, "Finished decoding"); + } + + if (TRACE_VIDEO_ANALYSIS) { + Debug.stopMethodTracing(); + } + + if (LOCAL_LOGV) { + // time analysis + double totalTime = (System.nanoTime()-startTime)/1e9; + Log.i(TAG, "Total time: "+totalTime +"s, Per frame time: "+totalTime/i ); + } + return i; + } + + /** + * OpenCV for Android have not support the VideoCapture from file + * This is a make shift solution before it is supported. + * One issue right now is that the glReadPixels is quite slow .. around 6.5ms for a 720p frame + */ + private class VideoDecoderForOpenCV implements Runnable { + static final String TAG = "VideoDecoderForOpenCV"; + + private MediaExtractor extractor=null; + private MediaCodec decoder=null; + private CtsMediaOutputSurface surface=null; + + private MatBuffer mMatBuffer; + + private final File mVideoFile; + + private boolean valid; + private Object setupSignal; + + private Thread mThread; + private int mDecimation; + + /** + * Constructor + * @param file video file + * @param decimation process every "decimation" number of frame + */ + VideoDecoderForOpenCV(File file, int decimation) { + mVideoFile = file; + mDecimation = decimation; + valid = false; + + start(); + } + + /** + * Constructor + * @param file video file + */ + VideoDecoderForOpenCV(File file) { + this(file, 1); + } + + /** + * Test if video decoder is in valid states ready to output video. + * @return true of force. + */ + public boolean isValid() { + return valid; + } + + private void start() { + setupSignal = new Object(); + mThread = new Thread(this); + mThread.start(); + + synchronized (setupSignal) { + try { + setupSignal.wait(); + } catch (InterruptedException e) { + Log.e(TAG, "Interrupted when waiting for video decoder setup ready"); + } + } + } + private void stop() { + if (mThread != null) { + mThread.interrupt(); + try { + mThread.join(); + } catch (InterruptedException e) { + Log.e(TAG, "Interrupted when waiting for video decoder thread to stop"); + } + try { + decoder.stop(); + }catch (IllegalStateException e) { + Log.e(TAG, "Video decoder is not in a state that can be stopped"); + } + } + mThread = null; + } + + void teardown() { + if (decoder!=null) { + decoder.release(); + decoder = null; + } + if (surface!=null) { + surface.release(); + surface = null; + } + if (extractor!=null) { + extractor.release(); + extractor = null; + } + } + + void setup() { + int width=0, height=0; + + extractor = new MediaExtractor(); + + try { + extractor.setDataSource(mVideoFile.getPath()); + } catch (IOException e) { + return; + } + + for (int i = 0; i < extractor.getTrackCount(); i++) { + MediaFormat format = extractor.getTrackFormat(i); + String mime = format.getString(MediaFormat.KEY_MIME); + width = format.getInteger(MediaFormat.KEY_WIDTH); + height = format.getInteger(MediaFormat.KEY_HEIGHT); + + if (mime.startsWith("video/")) { + extractor.selectTrack(i); + try { + decoder = MediaCodec.createDecoderByType(mime); + }catch (IOException e) { + continue; + } + // Decode to surface + //decoder.configure(format, surface, null, 0); + + // Decode to offscreen surface + surface = new CtsMediaOutputSurface(width, height); + mMatBuffer = new MatBuffer(width, height); + + decoder.configure(format, surface.getSurface(), null, 0); + break; + } + } + + if (decoder == null) { + Log.e(TAG, "Can't find video info!"); + return; + } + valid = true; + } + + @Override + public void run() { + setup(); + + synchronized (setupSignal) { + setupSignal.notify(); + } + + if (!valid) { + return; + } + + decoder.start(); + + ByteBuffer[] inputBuffers = decoder.getInputBuffers(); + ByteBuffer[] outputBuffers = decoder.getOutputBuffers(); + MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); + + boolean isEOS = false; + long startMs = System.currentTimeMillis(); + long timeoutUs = 10000; + + int iframe = 0; + long frameTimestamp = 0; + + while (!Thread.interrupted()) { + if (!isEOS) { + int inIndex = decoder.dequeueInputBuffer(10000); + if (inIndex >= 0) { + ByteBuffer buffer = inputBuffers[inIndex]; + int sampleSize = extractor.readSampleData(buffer, 0); + if (sampleSize < 0) { + if (LOCAL_LOGD) { + Log.d("VideoDecoderForOpenCV", + "InputBuffer BUFFER_FLAG_END_OF_STREAM"); + } + decoder.queueInputBuffer(inIndex, 0, 0, 0, + MediaCodec.BUFFER_FLAG_END_OF_STREAM); + isEOS = true; + } else { + frameTimestamp = extractor.getSampleTime(); + decoder.queueInputBuffer(inIndex, 0, sampleSize, frameTimestamp, 0); + if (LOCAL_LOGD) { + Log.d(TAG, String.format("Frame %d sample time %f s", + iframe, (double)frameTimestamp/1e6)); + } + extractor.advance(); + } + } + } + + int outIndex = decoder.dequeueOutputBuffer(info, 10000); + MediaFormat outFormat; + switch (outIndex) { + case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED: + if (LOCAL_LOGD) { + Log.d(TAG, "INFO_OUTPUT_BUFFERS_CHANGED"); + } + outputBuffers = decoder.getOutputBuffers(); + break; + case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED: + outFormat = decoder.getOutputFormat(); + if (LOCAL_LOGD) { + Log.d(TAG, "New format " + outFormat); + } + break; + case MediaCodec.INFO_TRY_AGAIN_LATER: + if (LOCAL_LOGD) { + Log.d(TAG, "dequeueOutputBuffer timed out!"); + } + break; + default: + + ByteBuffer buffer = outputBuffers[outIndex]; + boolean doRender = (info.size != 0); + + // As soon as we call releaseOutputBuffer, the buffer will be forwarded + // to SurfaceTexture to convert to a texture. The API doesn't + // guarantee that the texture will be available before the call + // returns, so we need to wait for the onFrameAvailable callback to + // fire. If we don't wait, we risk rendering from the previous frame. + decoder.releaseOutputBuffer(outIndex, doRender); + + if (doRender) { + surface.awaitNewImage(); + surface.drawImage(); + if (LOCAL_LOGV) { + Log.v(TAG, "Finish drawing a frame!"); + } + if ((iframe++ % mDecimation) == 0) { + //Send the frame for processing + mMatBuffer.put(frameTimestamp); + } + } + break; + } + + if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { + if (LOCAL_LOGD) { + Log.d("VideoDecoderForOpenCV", "OutputBuffer BUFFER_FLAG_END_OF_STREAM"); + } + break; + } + } + mMatBuffer.invalidate(); + + decoder.stop(); + + teardown(); + mThread = null; + } + + + /** + * Get next valid frame + * @return Frame in OpenCV mat + */ + public Mat getFrame(long ts[]) { + return mMatBuffer.get(ts); + } + + /** + * Get the size of the frame + * @return size of the frame + */ + Size getSize() { + return mMatBuffer.getSize(); + } + + /** + * A synchronized buffer + */ + class MatBuffer { + private Mat mat; + private byte[] bytes; + private ByteBuffer buf; + private long timestamp; + private boolean full; + + private int mWidth, mHeight; + private boolean mValid = false; + + MatBuffer(int width, int height) { + mWidth = width; + mHeight = height; + + mat = new Mat(height, width, CvType.CV_8UC4); //RGBA + buf = ByteBuffer.allocateDirect(width*height*4); + bytes = new byte[width*height*4]; + timestamp = -1; + + mValid = true; + full = false; + } + + public synchronized void invalidate() { + mValid = false; + notifyAll(); + } + + public synchronized Mat get(long ts[]) { + + if (!mValid) return null; + while (full == false) { + try { + wait(); + if (!mValid) return null; + } catch (InterruptedException e) { + return null; + } + } + mat.put(0,0, bytes); + full = false; + notifyAll(); + ts[0] = timestamp; + return mat; + } + + public synchronized void put(long ts) { + while (full) { + try { + wait(); + } catch (InterruptedException e) { + Log.e(TAG, "Interrupted when waiting for space in buffer"); + } + } + GLES20.glReadPixels(0, 0, mWidth, mHeight, GL10.GL_RGBA, + GL10.GL_UNSIGNED_BYTE, buf); + buf.get(bytes); + buf.rewind(); + + timestamp = ts; + full = true; + notifyAll(); + } + + public Size getSize() { + if (valid) { + return mat.size(); + } + return new Size(); + } + } + } + + + /* a small set of math functions */ + private static double [] quat2rpy( double [] q) { + double [] rpy = {Math.atan2(2*(q[0]*q[1]+q[2]*q[3]), 1-2*(q[1]*q[1]+q[2]*q[2])), + Math.asin(2*(q[0]*q[2] - q[3]*q[1])), + Math.atan2(2*(q[0]*q[3]+q[1]*q[2]), 1-2*(q[2]*q[2]+q[3]*q[3]))}; + return rpy; + } + + private static void quat2rpy( double [] q, double[] rpy) { + rpy[0] = Math.atan2(2*(q[0]*q[1]+q[2]*q[3]), 1-2*(q[1]*q[1]+q[2]*q[2])); + rpy[1] = Math.asin(2*(q[0]*q[2] - q[3]*q[1])); + rpy[2] = Math.atan2(2*(q[0]*q[3]+q[1]*q[2]), 1-2*(q[2]*q[2]+q[3]*q[3])); + } + + private static Mat quat2rpy(Mat quat) { + double [] q = new double[4]; + quat.get(0,0,q); + + double [] rpy = {Math.atan2(2*(q[0]*q[1]+q[2]*q[3]), 1-2*(q[1]*q[1]+q[2]*q[2])), + Math.asin(2*(q[0]*q[2] - q[3]*q[1])), + Math.atan2(2*(q[0]*q[3]+q[1]*q[2]), 1-2*(q[2]*q[2]+q[3]*q[3]))}; + + Mat rpym = new Mat(3,1, CvType.CV_64F); + rpym.put(0,0, rpy); + return rpym; + } + + private static double [] rodr2quat( double [] r) { + double t = Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); + double [] quat = {Math.cos(t/2), Math.sin(t/2)*r[0]/t,Math.sin(t/2)*r[1]/t, + Math.sin(t/2)*r[2]/t}; + return quat; + } + + private static void rodr2quat( double [] r, double [] quat) { + double t = Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); + quat[0] = Math.cos(t/2); + quat[1] = Math.sin(t/2)*r[0]/t; + quat[2] = Math.sin(t/2)*r[1]/t; + quat[3] = Math.sin(t/2)*r[2]/t; + } + + private static Mat rodr2quat(Mat rodr) { + double t = Core.norm(rodr); + double [] r = new double[3]; + rodr.get(0,0,r); + + double [] quat = {Math.cos(t/2), Math.sin(t/2)*r[0]/t,Math.sin(t/2)*r[1]/t, + Math.sin(t/2)*r[2]/t}; + Mat quatm = new Mat(4,1, CvType.CV_64F); + quatm.put(0, 0, quat); + return quatm; + } + + private static double [] rodr2rpy( double [] r) { + return quat2rpy(rodr2quat(r)); + } + ////////////////// + +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckTestActivity.java new file mode 100644 index 0000000..35c4d56 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/RVCVXCheckTestActivity.java
@@ -0,0 +1,346 @@ +/* + * 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; + +import android.content.Context; +import android.hardware.cts.helpers.SensorTestStateNotSupportedException; +import android.os.Bundle; +import android.os.PowerManager; + +import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity; +import com.android.cts.verifier.sensors.helpers.OpenCVLibrary; + +import junit.framework.Assert; + +import android.content.Intent; + +import java.util.concurrent.CountDownLatch; + +/** + * This test (Rotation Vector - Computer Vision Cross Check, or RXCVXCheck for short) verifies that + * mobile device can detect the orientation of itself in a relatively accurate manner. + * + * Currently only ROTATION_VECTOR sensor is used. + * + */ +public class RVCVXCheckTestActivity + extends SensorCtsVerifierTestActivity { + public RVCVXCheckTestActivity() { + super(RVCVXCheckTestActivity.class); + } + + CountDownLatch mRecordActivityFinishedSignal = null; + + private static final int REQ_CODE_TXCVRECORD = 0x012345678; + private static final boolean TEST_USING_DEBUGGING_DATA = false; + private static final String PATH_DEBUGGING_DATA = "/sdcard/RXCVRecData/150313-014443/"; + + private String mRecPath; + + RVCVXCheckAnalyzer.AnalyzeReport mReport = null; + + private boolean mRecordSuccessful = false; + private boolean mOpenCVLoadSuccessful = false; + + private static class Criterion { + public static final float roll_rms_error = 0.15f; + public static final float pitch_rms_error = 0.15f; + public static final float yaw_rms_error = 0.25f; + + public static final float roll_max_error = 0.30f; + public static final float pitch_max_error = 0.30f; + public static final float yaw_max_error = 0.45f; + + public static final float sensor_period_stdev = 0.25e-3f; + }; + + + /** + * The activity setup collects all the required data for test cases. + * This approach allows to test all sensors at once. + */ + @Override + protected void activitySetUp() throws InterruptedException { + + mRecPath = ""; + + showUserMessage("Loading OpenCV Library..."); + int retry = 10; + + while(retry-->0) { + try { + Thread.sleep(250); + } catch (InterruptedException e) { + // + } + if (OpenCVLibrary.isLoaded()) { + break; + } + } + if (!OpenCVLibrary.isLoaded()) { + // failed requirement test + clearText(); + return; + } + showUserMessage("OpenCV Library Successfully Loaded"); + + mOpenCVLoadSuccessful = true; + + if (TEST_USING_DEBUGGING_DATA) { + mRecPath = PATH_DEBUGGING_DATA; + + // assume the data is there already + mRecordSuccessful = true; + } else { + showUserMessage("Take the test as instructed below:\n" + + "1. Print out the test pattern and place it on a "+ + "horizontal surface.\n" + + "2. Start the test and align the yellow square on the screen "+ + "roughly to the yellow sqaure.\n" + + "3. Follow the prompt to rotate the phone while keeping the "+ + "entire test pattern inside view of camera. This requires " + + "orbiting the phone around and aiming the "+ + "camera at the test pattern at the same time.\n" + + "4. Wait patiently for the analysis to finish.\n"); + + waitForUserToContinue(); + + // prepare sync signal + mRecordActivityFinishedSignal = new CountDownLatch(1); + + // record both sensor and camera + Intent intent = new Intent(this, RVCVRecordActivity.class); + startActivityForResult(intent, REQ_CODE_TXCVRECORD); + + // wait for record finish + mRecordActivityFinishedSignal.await(); + + if ("".equals(mRecPath)) { + showUserMessage("Recording failed or exited prematurely."); + waitForUserToContinue(); + } else { + showUserMessage("Recording is done!"); + showUserMessage("Result are in path: " + mRecPath); + mRecordSuccessful = true; + } + } + + + if (mRecordSuccessful) { + showUserMessage("Please wait for the analysis ... \n"+ + "It may take a few minutes, you will be noted when "+ + "its finished by sound and vibration. "); + + // Analysis of recorded video and sensor data using RVCXAnalyzer + RVCVXCheckAnalyzer analyzer = new RVCVXCheckAnalyzer(mRecPath); + + // acquire a partial wake lock just in case CPU fall asleep + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "RVCVXCheckAnalyzer"); + + wl.acquire(); + mReport = analyzer.processDataSet(); + wl.release(); + + playSound(); + vibrate(500); + + if (mReport == null) { + showUserMessage("Analysis failed due to unknown reason!"); + } else { + if (mReport.error) { + showUserMessage("Analysis failed: " + mReport.reason); + } else { + showUserMessage(String.format("Analysis finished!\n" + + "Roll error (Rms, max) = %4.3f, %4.3f rad\n" + + "Pitch error (Rms, max) = %4.3f, %4.3f rad\n" + + "Yaw error (Rms, max) = %4.3f, %4.3f rad\n" + + "N of Frame (valid, total) = %d, %d\n" + + "Sensor period (mean, stdev) = %4.3f, %4.3f ms\n" + + "Time offset: %4.3f s \n" + + "Yaw offset: %4.3f rad \n\n", + mReport.roll_rms_error, mReport.roll_max_error, + mReport.pitch_rms_error, mReport.pitch_max_error, + mReport.yaw_rms_error, mReport.yaw_max_error, + mReport.n_of_valid_frame, mReport.n_of_frame, + mReport.sensor_period_avg * 1000.0, mReport.sensor_period_stdev*1000.0, + mReport.optimal_delta_t, mReport.yaw_offset)); + showUserMessage("Please click next after details reviewed."); + waitForUserToContinue(); + } + } + } + clearText(); + } + + /** + Receiving the results from the RVCVRecordActivity, which is a patch where the recorded + video and sensor data is stored. + */ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // Check which request we're responding to + if (requestCode == REQ_CODE_TXCVRECORD) { + // Make sure the request was successful + + if (resultCode == RESULT_OK) { + mRecPath = data.getData().getPath(); + } + + // notify it is finished + mRecordActivityFinishedSignal.countDown(); + } + super.onActivityResult(requestCode, resultCode, data); + } + + /** + * Test cases. + */ + + public String test00OpenCV() throws Throwable { + + String message = "OpenCV is loaded"; + Assert.assertTrue("OpenCV library cannot be loaded.", mOpenCVLoadSuccessful); + return message; + } + + + public String test01Recording() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + + String message = "Record is successful."; + Assert.assertTrue("Record is not successful.", mRecordSuccessful); + return message; + } + + public String test02Analysis() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + recordSuccessfulOrSkip(); + + String message = "Analysis result: " + mReport.reason; + Assert.assertTrue(message, (mReport!=null && !mReport.error)); + return message; + } + + public String test1RollAxis() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + recordSuccessfulOrSkip(); + analyzeSuccessfulOrSkip(); + + String message = "Test Roll Axis Accuracy"; + + Assert.assertEquals("Roll RMS error", 0.0, mReport.roll_rms_error, + Criterion.roll_rms_error); + Assert.assertEquals("Roll max error", 0.0, mReport.roll_max_error, + Criterion.roll_max_error); + return message; + } + + public String test2PitchAxis() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + recordSuccessfulOrSkip(); + analyzeSuccessfulOrSkip(); + + String message = "Test Pitch Axis Accuracy"; + + Assert.assertEquals("Pitch RMS error", 0.0, mReport.pitch_rms_error, + Criterion.pitch_rms_error); + Assert.assertEquals("Pitch max error", 0.0, mReport.pitch_max_error, + Criterion.pitch_max_error); + return message; + } + + public String test3YawAxis() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + recordSuccessfulOrSkip(); + analyzeSuccessfulOrSkip(); + + String message = "Test Yaw Axis Accuracy"; + + Assert.assertEquals("Yaw RMS error", 0.0, mReport.yaw_rms_error, + Criterion.yaw_rms_error); + Assert.assertEquals("Yaw max error", 0.0, mReport.yaw_max_error, + Criterion.yaw_max_error); + return message; + } + + public String test4SensorPeriod() throws Throwable { + + loadOpenCVSuccessfulOrSkip(); + recordSuccessfulOrSkip(); + analyzeSuccessfulOrSkip(); + + String message = "Test Sensor Period"; + + // we do not know what the maximum frequency can be, so just test the stdev value + Assert.assertEquals("Sensor sample period stdev.", 0.0, mReport.sensor_period_stdev, + Criterion.sensor_period_stdev); + return message; + } + + private void loadOpenCVSuccessfulOrSkip() throws SensorTestStateNotSupportedException { + if (!mOpenCVLoadSuccessful) + throw new SensorTestStateNotSupportedException("Skipped due to OpenCV cannot be loaded"); + } + + private void recordSuccessfulOrSkip() throws SensorTestStateNotSupportedException { + if (!mRecordSuccessful) + throw new SensorTestStateNotSupportedException("Skipped due to record failure."); + } + + private void analyzeSuccessfulOrSkip() throws SensorTestStateNotSupportedException { + if (mReport == null || mReport.error) + throw new SensorTestStateNotSupportedException("Skipped due to CV Analysis failure."); + } + + /* + * This function serves as a proxy as showUserMessage is marked to be deprecated. + * When appendText is removed, this function will have a different implementation. + * + */ + void showUserMessage(String s) { + appendText(s); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + + super.onCreate(savedInstanceState); + + // GlSurfaceView is not necessary for this test + closeGlSurfaceView(); + + OpenCVLibrary.loadAsync(this); + } + + @Override + protected void onPause() { + super.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java index faba445..2dfc7c8 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
@@ -16,22 +16,36 @@ package com.android.cts.verifier.sensors; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + import com.android.cts.verifier.R; import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity; +import com.android.cts.verifier.sensors.helpers.SensorTestScreenManipulator; -import junit.framework.Assert; - +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; import android.hardware.Sensor; import android.hardware.SensorManager; import android.hardware.TriggerEvent; import android.hardware.TriggerEventListener; import android.hardware.cts.helpers.SensorNotSupportedException; import android.hardware.cts.helpers.TestSensorEnvironment; +import android.hardware.cts.helpers.SuspendStateMonitor; +import android.os.Handler; +import android.os.Looper; +import android.os.PowerManager; import android.os.SystemClock; +import android.support.v4.content.LocalBroadcastManager; +import android.util.Log; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import junit.framework.Assert; /** * Test cases for Significant Motion sensor. @@ -46,20 +60,30 @@ private static final long MAX_ACCEPTABLE_EVENT_TIME_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(500); + // acceptable time difference between event time and AP wake up time. + private static final long MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS = + TimeUnit.MILLISECONDS.toNanos(2000); + + // time to wait for SMD after the device has gone into suspend. Even after + // 45 secs if SMD does not trigger, the test will fail. + private static final long ALARM_WAKE_TIME_DELAY_MS = TimeUnit.SECONDS.toMillis(45); + // time for the test to wait for a trigger private static final int TRIGGER_MAX_DELAY_SECONDS = 30; private static final int VIBRATE_DURATION_MILLIS = 10000; private static final int EVENT_VALUES_LENGTH = 1; private static final float EXPECTED_EVENT_VALUE = 1.0f; + private static String ACTION_ALARM = "SignificantMotionTestActivity.ACTION_ALARM"; private SensorManager mSensorManager; private Sensor mSensorSignificantMotion; + private TriggerVerifier mVerifier; + private SensorTestScreenManipulator mScreenManipulator; /** * Test cases. */ - @SuppressWarnings("unused") public String testTrigger() throws Throwable { return runTest( @@ -131,6 +155,69 @@ return result; } + public static class AlarmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + Intent alarm_intent = new Intent(context, SignificantMotionTestActivity.class); + alarm_intent.setAction(SignificantMotionTestActivity.ACTION_ALARM); + LocalBroadcastManager.getInstance(context).sendBroadcastSync(alarm_intent); + } + } + + public BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + mVerifier.releaseLatch(); + mScreenManipulator.turnScreenOn(); + try { + playSound(); + } catch (InterruptedException e) { + // Ignore ... + } + } + }; + + @SuppressWarnings("unused") + public String testAPWakeUpOnSMDTrigger() throws Throwable { + SensorTestLogger logger = getTestLogger(); + logger.logInstructions(R.string.snsr_significant_motion_ap_suspend); + waitForUserToBegin(); + mVerifier = new TriggerVerifier(); + mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion); + long testStartTimeNs = SystemClock.elapsedRealtimeNanos(); + Handler handler = new Handler(Looper.getMainLooper()); + SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor(); + + Intent intent = new Intent(this, AlarmReceiver.class); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + + AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); + am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS, pendingIntent); + try { + // Wait for the first event to trigger. Device is expected to go into suspend here. + mVerifier.verifyEventTriggered(); + long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent(); + long endTimeNs = SystemClock.elapsedRealtimeNanos(); + long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos( + suspendStateMonitor.getLastWakeUpTime()); + Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend), + testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs); + long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs); + Assert.assertTrue( + String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger), + TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs), + TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)), + timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS); + } finally { + am.cancel(pendingIntent); + suspendStateMonitor.cancel(); + mScreenManipulator.turnScreenOn(); + playSound(); + } + return null; + } + /** * @param instructionsResId Instruction to be shown to testers * @param isMotionExpected Should the device detect significant motion event @@ -187,6 +274,29 @@ if (mSensorSignificantMotion == null) { throw new SensorNotSupportedException(Sensor.TYPE_SIGNIFICANT_MOTION); } + + mScreenManipulator = new SensorTestScreenManipulator(this); + try { + mScreenManipulator.initialize(this); + } catch (InterruptedException e) { + } + PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); + LocalBroadcastManager.getInstance(this).registerReceiver(myBroadCastReceiver, + new IntentFilter(ACTION_ALARM)); + } + + @Override + protected void activityCleanUp() { + if (mScreenManipulator != null) { + mScreenManipulator.turnScreenOff(); + } + LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadCastReceiver); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mScreenManipulator.close(); } /** @@ -196,6 +306,7 @@ private class TriggerVerifier extends TriggerEventListener { private volatile CountDownLatch mCountDownLatch; private volatile TriggerEventRegistry mEventRegistry; + private volatile long mTimestampForTriggeredEvent = 0; // TODO: refactor out if needed private class TriggerEventRegistry { @@ -214,6 +325,16 @@ mCountDownLatch.countDown(); } + public void releaseLatch() { + if (mCountDownLatch != null) { + mCountDownLatch.countDown(); + } + } + + public long getTimeStampForTriggerEvent() { + return mTimestampForTriggeredEvent; + } + public String verifyEventTriggered() throws Throwable { TriggerEventRegistry registry = awaitForEvent(); @@ -269,10 +390,14 @@ private TriggerEventRegistry awaitForEvent() throws InterruptedException { mCountDownLatch = new CountDownLatch(1); mCountDownLatch.await(TRIGGER_MAX_DELAY_SECONDS, TimeUnit.SECONDS); - TriggerEventRegistry registry = mEventRegistry; - mEventRegistry = null; + // Save the last timestamp when the event triggered. + if (mEventRegistry != null && mEventRegistry.triggerEvent != null) { + mTimestampForTriggeredEvent = mEventRegistry.triggerEvent.timestamp; + } + + mEventRegistry = null; playSound(); return registry != null ? registry : new TriggerEventRegistry(null, 0); }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/OpenCVLibrary.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/OpenCVLibrary.java new file mode 100644 index 0000000..2f5c873 --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/OpenCVLibrary.java
@@ -0,0 +1,71 @@ +/* + * Copyright (C) 2013 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.helpers; + +import android.content.Context; +import android.os.Looper; +import android.util.Log; + +import org.opencv.android.BaseLoaderCallback; +import org.opencv.android.LoaderCallbackInterface; +import org.opencv.android.OpenCVLoader; + +import java.util.concurrent.CountDownLatch; + +/** + * OpenCV library loader class + */ +public class OpenCVLibrary { + + private static String TAG = "OpenCVLibraryProbe"; + private static boolean mLoaded = false; + + /** + * Load OpenCV Library in async mode + * @param context Activity context + */ + public static void loadAsync(Context context) { + // only need to load once + if (isLoaded()) return; + + // Load the library through loader + OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, context, + new BaseLoaderCallback(context) { + @Override + public void onManagerConnected(int status) { + Log.v(TAG, "New Loading status: "+status); + switch (status) { + case LoaderCallbackInterface.SUCCESS: { + mLoaded = true; + } + break; + default: { + super.onManagerConnected(status); + } + break; + } + } + }); + } + + /** + * Test if the library is loaded + * @return a boolean indicates whether the OpenCV library is loaded. + */ + public static boolean isLoaded() { + return mLoaded; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/AppLinkTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/AppLinkTestActivity.java new file mode 100644 index 0000000..43f293a --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/AppLinkTestActivity.java
@@ -0,0 +1,113 @@ +/* + * Copyright (C) 2015 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.tv; + +import android.content.Intent; +import android.database.Cursor; +import android.graphics.drawable.Drawable; +import android.media.tv.TvContract; +import android.text.TextUtils; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import com.android.cts.verifier.R; + +/** + * Tests for verifying TV app behavior for TV app-link. + */ +public class AppLinkTestActivity extends TvAppVerifierActivity implements View.OnClickListener { + private static final long TIMEOUT_MS = 5l * 60l * 1000l; // 5 mins. + + private boolean mSelectAppLinkItemPassed; + private View mSelectAppLinkItem; + private View mVerifyAppLinkIntentItem; + private View mVerifyAppLinkCardItem; + + Runnable mSelectAppLinkFailCallback; + + @Override + public void onClick(View v) { + final View postTarget = getPostTarget(); + + if (containsButton(mSelectAppLinkItem, v)) { + Intent tvAppIntent = null; + String[] projection = { TvContract.Channels._ID }; + try (Cursor cursor = getContentResolver().query( + TvContract.buildChannelsUriForInput(MockTvInputService.getInputId(this)), + projection, null, null, null)) { + if (cursor != null && cursor.moveToNext()) { + tvAppIntent = new Intent(Intent.ACTION_VIEW, + TvContract.buildChannelUri(cursor.getLong(0))); + } + } + if (tvAppIntent == null) { + Toast.makeText(this, R.string.tv_channel_not_found, Toast.LENGTH_SHORT).show(); + return; + } + + mSelectAppLinkFailCallback = new Runnable() { + @Override + public void run() { + mSelectAppLinkItemPassed = false; + setPassState(mSelectAppLinkItem, false); + setPassState(mVerifyAppLinkIntentItem, false); + } + }; + postTarget.postDelayed(mSelectAppLinkFailCallback, TIMEOUT_MS); + mSelectAppLinkItemPassed = true; + setPassState(mSelectAppLinkItem, true); + + startActivity(tvAppIntent); + } else if (containsButton(mVerifyAppLinkCardItem, v)) { + setPassState(mVerifyAppLinkCardItem, true); + getPassButton().setEnabled(true); + } + } + + @Override + protected void onNewIntent(Intent intent) { + if (mSelectAppLinkItemPassed + && TextUtils.equals(MockTvInputSetupActivity.APP_LINK_TEST_VALUE, + intent.getStringExtra(MockTvInputSetupActivity.APP_LINK_TEST_KEY))) { + getPostTarget().removeCallbacks(mSelectAppLinkFailCallback); + setPassState(mVerifyAppLinkIntentItem, true); + setButtonEnabled(mVerifyAppLinkCardItem, true); + } + } + + @Override + protected void createTestItems() { + mSelectAppLinkItem = createUserItem(R.string.tv_app_link_test_select_app_link, + R.string.tv_launch_tv_app, this); + setButtonEnabled(mSelectAppLinkItem, true); + mVerifyAppLinkIntentItem = createAutoItem( + R.string.tv_app_link_test_verify_link_clicked); + mVerifyAppLinkCardItem = createUserItem(R.string.tv_input_link_test_verify_link_interface, + android.R.string.yes, this); + TextView instructions = (TextView) mVerifyAppLinkCardItem.findViewById(R.id.instructions); + Drawable image = getDrawable(R.drawable.app_link_img); + image.setBounds(0, 0, 317, 241); + instructions.setCompoundDrawablePadding(10); + instructions.setCompoundDrawables(image, null, null, null); + } + + @Override + protected void setInfoResources() { + setInfoResources(R.string.tv_app_link_test, R.string.tv_app_link_test_info, -1); + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputService.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputService.java index e7d1d79..f875684 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputService.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputService.java
@@ -16,9 +16,9 @@ package com.android.cts.verifier.tv; -import com.android.cts.verifier.R; - +import android.annotation.SuppressLint; import android.content.BroadcastReceiver; +import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; @@ -27,20 +27,29 @@ import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; +import android.media.PlaybackParams; import android.media.tv.TvContentRating; +import android.media.tv.TvContract; import android.media.tv.TvInputManager; import android.media.tv.TvInputService; import android.media.tv.TvTrackInfo; import android.net.Uri; import android.os.Bundle; -import android.view.Surface; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.util.Log; import android.view.LayoutInflater; +import android.view.Surface; import android.view.View; import android.widget.TextView; +import com.android.cts.verifier.R; + import java.util.ArrayList; import java.util.List; +@SuppressLint("NewApi") public class MockTvInputService extends TvInputService { private static final String TAG = "MockTvInputService"; @@ -48,6 +57,7 @@ private static final String SELECT_TRACK_TYPE = "type"; private static final String SELECT_TRACK_ID = "id"; private static final String CAPTION_ENABLED = "enabled"; + private static final String PAUSE_CALLED = "pause_called"; private static Object sLock = new Object(); private static Callback sTuneCallback = null; @@ -56,6 +66,14 @@ private static Callback sUnblockContentCallback = null; private static Callback sSelectTrackCallback = null; private static Callback sSetCaptionEnabledCallback = null; + // Callbacks for time shift. + private static Callback sResumeAfterPauseCallback = null; + private static Callback sPositionTrackingCallback = null; + private static Callback sRewindCallback = null; + private static Callback sFastForwardCallback = null; + private static Callback sSeekToPreviousCallback = null; + private static Callback sSeekToNextCallback = null; + private static TvContentRating sRating = null; static final TvTrackInfo sEngAudioTrack = @@ -142,6 +160,47 @@ } } + static void expectResumeAfterPause(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sResumeAfterPauseCallback = new Callback(postTarget, successCallback); + } + } + + static void expectPositionTracking(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sPositionTrackingCallback = new Callback(postTarget, successCallback); + } + } + + static void expectRewind(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sRewindCallback = new Callback(postTarget, successCallback); + } + } + + static void expectFastForward(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sFastForwardCallback = new Callback(postTarget, successCallback); + } + } + + static void expectSeekToPrevious(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sSeekToPreviousCallback = new Callback(postTarget, successCallback); + } + } + + static void expectSeekToNext(View postTarget, Runnable successCallback) { + synchronized (sLock) { + sSeekToNextCallback = new Callback(postTarget, successCallback); + } + } + + static String getInputId(Context context) { + return TvContract.buildInputId(new ComponentName(context, + MockTvInputService.class.getName())); + } + @Override public void onCreate() { super.onCreate(); @@ -165,10 +224,45 @@ } private static class MockSessionImpl extends Session { + private static final int MSG_SEEK = 1000; + private static final int SEEK_DELAY_MS = 300; + private final Context mContext; private Surface mSurface = null; private List<TvTrackInfo> mTracks = new ArrayList<>(); + private long mRecordStartTimeMs; + private long mPausedTimeMs; + // The time in milliseconds when the current position is lastly updated. + private long mLastCurrentPositionUpdateTimeMs; + // The current playback position. + private long mCurrentPositionMs; + // The current playback speed rate. + private float mSpeed; + + private final Handler mHandler = new Handler(Looper.getMainLooper()) { + @Override + public void handleMessage(Message msg) { + if (msg.what == MSG_SEEK) { + // Actually, this input doesn't play any videos, it just shows the image. + // So we should simulate the playback here by changing the current playback + // position periodically in order to test the time shift. + // If the playback is paused, the current playback position doesn't need to be + // changed. + if (mPausedTimeMs == 0) { + long currentTimeMs = System.currentTimeMillis(); + mCurrentPositionMs += (long) ((currentTimeMs + - mLastCurrentPositionUpdateTimeMs) * mSpeed); + mCurrentPositionMs = Math.max(mRecordStartTimeMs, + Math.min(mCurrentPositionMs, currentTimeMs)); + mLastCurrentPositionUpdateTimeMs = currentTimeMs; + } + sendEmptyMessageDelayed(MSG_SEEK, SEEK_DELAY_MS); + } + super.handleMessage(msg); + } + }; + private MockSessionImpl(Context context) { super(context); mContext = context; @@ -256,6 +350,12 @@ notifyTracksChanged(mTracks); notifyTrackSelected(TvTrackInfo.TYPE_AUDIO, sEngAudioTrack.getId()); notifyTrackSelected(TvTrackInfo.TYPE_SUBTITLE, null); + notifyTimeShiftStatusChanged(TvInputManager.TIME_SHIFT_STATUS_AVAILABLE); + mRecordStartTimeMs = mCurrentPositionMs = mLastCurrentPositionUpdateTimeMs + = System.currentTimeMillis(); + mPausedTimeMs = 0; + mHandler.sendEmptyMessageDelayed(MSG_SEEK, SEEK_DELAY_MS); + mSpeed = 1; return true; } @@ -298,6 +398,88 @@ } } } + + @Override + public long onTimeShiftGetCurrentPosition() { + synchronized (sLock) { + if (sPositionTrackingCallback != null) { + sPositionTrackingCallback.post(); + sPositionTrackingCallback = null; + } + } + Log.d(TAG, "currentPositionMs=" + mCurrentPositionMs); + return mCurrentPositionMs; + } + + @Override + public long onTimeShiftGetStartPosition() { + return mRecordStartTimeMs; + } + + @Override + public void onTimeShiftPause() { + synchronized (sLock) { + if (sResumeAfterPauseCallback != null) { + sResumeAfterPauseCallback.mBundle.putBoolean(PAUSE_CALLED, true); + } + } + mCurrentPositionMs = mPausedTimeMs = mLastCurrentPositionUpdateTimeMs + = System.currentTimeMillis(); + } + + @Override + public void onTimeShiftResume() { + synchronized (sLock) { + if (sResumeAfterPauseCallback != null + && sResumeAfterPauseCallback.mBundle.getBoolean(PAUSE_CALLED)) { + sResumeAfterPauseCallback.post(); + sResumeAfterPauseCallback = null; + } + } + mSpeed = 1; + mPausedTimeMs = 0; + mLastCurrentPositionUpdateTimeMs = System.currentTimeMillis(); + } + + @Override + public void onTimeShiftSeekTo(long timeMs) { + synchronized (sLock) { + if (mCurrentPositionMs > timeMs) { + if (sSeekToPreviousCallback != null) { + sSeekToPreviousCallback.post(); + sSeekToPreviousCallback = null; + } + } else if (mCurrentPositionMs < timeMs) { + if (sSeekToNextCallback != null) { + sSeekToNextCallback.post(); + sSeekToNextCallback = null; + } + } + } + mLastCurrentPositionUpdateTimeMs = System.currentTimeMillis(); + mCurrentPositionMs = Math.max(mRecordStartTimeMs, + Math.min(timeMs, mLastCurrentPositionUpdateTimeMs)); + } + + @Override + public void onTimeShiftSetPlaybackParams(PlaybackParams params) { + synchronized(sLock) { + if (params != null) { + if (params.getSpeed() > 1) { + if (sFastForwardCallback != null) { + sFastForwardCallback.post(); + sFastForwardCallback = null; + } + } else if (params.getSpeed() < 1) { + if (sRewindCallback != null) { + sRewindCallback.post(); + sRewindCallback = null; + } + } + } + } + mSpeed = params.getSpeed(); + } } private static class Callback {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSettingsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSettingsActivity.java deleted file mode 100644 index 4231db7..0000000 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSettingsActivity.java +++ /dev/null
@@ -1,23 +0,0 @@ -/* - * 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.tv; - -import android.preference.PreferenceActivity; - -public class MockTvInputSettingsActivity extends PreferenceActivity { - -}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSetupActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSetupActivity.java index c05b753..43ed7da 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSetupActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MockTvInputSetupActivity.java
@@ -17,9 +17,12 @@ package com.android.cts.verifier.tv; import android.app.Activity; +import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; +import android.content.Intent; import android.database.Cursor; +import android.graphics.Color; import android.media.tv.TvContract; import android.media.tv.TvContract.Programs; import android.media.tv.TvInputInfo; @@ -28,6 +31,8 @@ import android.util.Pair; import android.view.View; +import com.android.cts.verifier.R; + import java.util.ArrayList; public class MockTvInputSetupActivity extends Activity { @@ -38,6 +43,10 @@ /* package-private */ static final String PROGRAM_TITLE = "Dummy Program"; /* package-private */ static final String PROGRAM_DESCRIPTION = "Dummy Program Description"; + + /* package-private */ static final String APP_LINK_TEST_KEY = "app_link_test_key"; + /* package-private */ static final String APP_LINK_TEST_VALUE = "app_link_test_value"; + private static final String APP_LINK_TEXT = "Cts App-Link Text"; private static final long PROGRAM_LENGTH_MILLIS = 60 * 60 * 1000; private static final int PROGRAM_COUNT = 24; @@ -69,6 +78,18 @@ values.put(TvContract.Channels.COLUMN_INPUT_ID, inputId); values.put(TvContract.Channels.COLUMN_DISPLAY_NUMBER, CHANNEL_NUMBER); values.put(TvContract.Channels.COLUMN_DISPLAY_NAME, CHANNEL_NAME); + values.put(TvContract.Channels.COLUMN_APP_LINK_TEXT, APP_LINK_TEXT); + values.put(TvContract.Channels.COLUMN_APP_LINK_COLOR, Color.RED); + values.put(TvContract.Channels.COLUMN_APP_LINK_ICON_URI, + "android.resource://" + getPackageName() + "/" + R.drawable.icon); + values.put(TvContract.Channels.COLUMN_APP_LINK_POSTER_ART_URI, + "android.resource://" + getPackageName() + "/" + R.raw.sns_texture); + Intent appLinkIntentUri = new Intent(this, AppLinkTestActivity.class); + appLinkIntentUri.putExtra(APP_LINK_TEST_KEY, APP_LINK_TEST_VALUE); + appLinkIntentUri.setFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); + values.put(TvContract.Channels.COLUMN_APP_LINK_INTENT_URI, + appLinkIntentUri.toUri(Intent.URI_INTENT_SCHEME)); + Uri channelUri = getContentResolver().insert(uri, values); // If the channel's ID happens to be zero, we add another and delete the one. if (ContentUris.parseId(channelUri) == 0) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MultipleTracksTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MultipleTracksTestActivity.java index 66af4c6..a912cc6 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MultipleTracksTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MultipleTracksTestActivity.java
@@ -17,7 +17,7 @@ package com.android.cts.verifier.tv; import com.android.cts.verifier.R; - +import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; import android.media.tv.TvContentRating; @@ -36,6 +36,7 @@ /** * Tests for verifying TV app behavior on multiple tracks and subtitle. */ +@SuppressLint("NewApi") public class MultipleTracksTestActivity extends TvAppVerifierActivity implements View.OnClickListener { private static final String TAG = "MultipleTracksTestActivity"; @@ -113,7 +114,8 @@ } if (mTvAppIntent == null) { String[] projection = { TvContract.Channels._ID }; - try (Cursor cursor = getContentResolver().query(TvContract.Channels.CONTENT_URI, + try (Cursor cursor = getContentResolver().query( + TvContract.buildChannelsUriForInput(MockTvInputService.getInputId(this)), projection, null, null, null)) { if (cursor != null && cursor.moveToNext()) { mTvAppIntent = new Intent(Intent.ACTION_VIEW,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/ParentalControlTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/ParentalControlTestActivity.java index 284b485..c99da46 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/ParentalControlTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/ParentalControlTestActivity.java
@@ -17,7 +17,7 @@ package com.android.cts.verifier.tv; import com.android.cts.verifier.R; - +import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; import android.media.tv.TvContentRating; @@ -35,6 +35,7 @@ /** * Tests for verifying TV app behavior on parental control. */ +@SuppressLint("NewApi") public class ParentalControlTestActivity extends TvAppVerifierActivity implements View.OnClickListener { private static final String TAG = "ParentalControlTestActivity"; @@ -110,7 +111,8 @@ } if (mTvAppIntent == null) { String[] projection = { TvContract.Channels._ID }; - try (Cursor cursor = getContentResolver().query(TvContract.Channels.CONTENT_URI, + try (Cursor cursor = getContentResolver().query( + TvContract.buildChannelsUriForInput(MockTvInputService.getInputId(this)), projection, null, null, null)) { if (cursor != null && cursor.moveToNext()) { mTvAppIntent = new Intent(Intent.ACTION_VIEW,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TimeShiftTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TimeShiftTestActivity.java new file mode 100644 index 0000000..5e4036c --- /dev/null +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TimeShiftTestActivity.java
@@ -0,0 +1,222 @@ +/* + * Copyright (C) 2015 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.tv; + +import android.content.Intent; +import android.database.Cursor; +import android.media.tv.TvContract; +import android.view.View; +import android.widget.Toast; + +import com.android.cts.verifier.R; + +import java.util.concurrent.TimeUnit; + +/** + * Tests for verifying TV app behavior on time shift. + */ +public class TimeShiftTestActivity extends TvAppVerifierActivity + implements View.OnClickListener { + private static final long TIMEOUT_MS = TimeUnit.MINUTES.toMillis(5); + private static final boolean NOT_PASSED = false; + private static final boolean PASSED = true; + + private View mPauseResumeItem; + private View mVerifyResumeAfterPauseItem; + private View mVerifyPositionTrackingItem; + + private View mSetPlaybackParamsItem; + private View mVerifyRewindItem; + private View mVerifyFastForwardItem; + + private View mSeekToItem; + private View mVerifySeekToPreviousItem; + private View mVerifySeekToNextItem; + + private Intent mTvAppIntent = null; + + @Override + public void onClick(View v) { + final View postTarget = getPostTarget(); + + if (containsButton(mPauseResumeItem, v)) { + mVerifyResumeAfterPauseItem.setTag(NOT_PASSED); + mVerifyPositionTrackingItem.setTag(NOT_PASSED); + + final Runnable failCallback = new Runnable() { + @Override + public void run() { + setPassState(mVerifyResumeAfterPauseItem, false); + setPassState(mVerifyPositionTrackingItem, false); + } + }; + postTarget.postDelayed(failCallback, TIMEOUT_MS); + MockTvInputService.expectResumeAfterPause(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mPauseResumeItem, true); + setPassState(mVerifyResumeAfterPauseItem, true); + mVerifyResumeAfterPauseItem.setTag(PASSED); + if (isPassedState(mVerifyResumeAfterPauseItem) + && isPassedState(mVerifyPositionTrackingItem)) { + setButtonEnabled(mSetPlaybackParamsItem, true); + } + } + }); + MockTvInputService.expectPositionTracking(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mPauseResumeItem, true); + setPassState(mVerifyPositionTrackingItem, true); + mVerifyPositionTrackingItem.setTag(PASSED); + if (isPassedState(mVerifyResumeAfterPauseItem) + && isPassedState(mVerifyPositionTrackingItem)) { + setButtonEnabled(mSetPlaybackParamsItem, true); + } + } + }); + } else if (containsButton(mSetPlaybackParamsItem, v)) { + mVerifyRewindItem.setTag(NOT_PASSED); + mVerifyFastForwardItem.setTag(NOT_PASSED); + + final Runnable failCallback = new Runnable() { + @Override + public void run() { + setPassState(mVerifyRewindItem, false); + setPassState(mVerifyFastForwardItem, false); + } + }; + postTarget.postDelayed(failCallback, TIMEOUT_MS); + MockTvInputService.expectRewind(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mSetPlaybackParamsItem, true); + setPassState(mVerifyRewindItem, true); + mVerifyRewindItem.setTag(PASSED); + if (isPassedState(mVerifyRewindItem) && isPassedState(mVerifyFastForwardItem)) { + setButtonEnabled(mSeekToItem, true); + } + } + }); + MockTvInputService.expectFastForward(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mSetPlaybackParamsItem, true); + setPassState(mVerifyFastForwardItem, true); + mVerifyFastForwardItem.setTag(PASSED); + if (isPassedState(mVerifyRewindItem) && isPassedState(mVerifyFastForwardItem)) { + setButtonEnabled(mSeekToItem, true); + } + } + }); + } else if (containsButton(mSeekToItem, v)) { + mVerifySeekToPreviousItem.setTag(NOT_PASSED); + mVerifySeekToNextItem.setTag(NOT_PASSED); + + final Runnable failCallback = new Runnable() { + @Override + public void run() { + setPassState(mVerifySeekToPreviousItem, false); + setPassState(mVerifySeekToNextItem, false); + } + }; + postTarget.postDelayed(failCallback, TIMEOUT_MS); + MockTvInputService.expectSeekToPrevious(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mSeekToItem, true); + setPassState(mVerifySeekToPreviousItem, true); + mVerifySeekToPreviousItem.setTag(PASSED); + if (isPassedState(mVerifySeekToPreviousItem) + && isPassedState(mVerifySeekToNextItem)) { + getPassButton().setEnabled(true); + } + } + }); + MockTvInputService.expectSeekToNext(postTarget, new Runnable() { + @Override + public void run() { + postTarget.removeCallbacks(failCallback); + setPassState(mSeekToItem, true); + setPassState(mVerifySeekToNextItem, true); + mVerifySeekToNextItem.setTag(PASSED); + if (isPassedState(mVerifySeekToPreviousItem) + && isPassedState(mVerifySeekToNextItem)) { + getPassButton().setEnabled(true); + } + } + }); + } + if (mTvAppIntent == null) { + String[] projection = { TvContract.Channels._ID }; + try (Cursor cursor = getContentResolver().query( + TvContract.buildChannelsUriForInput(MockTvInputService.getInputId(this)), + projection, null, null, null)) { + if (cursor != null && cursor.moveToNext()) { + mTvAppIntent = new Intent(Intent.ACTION_VIEW, + TvContract.buildChannelUri(cursor.getLong(0))); + } + } + if (mTvAppIntent == null) { + Toast.makeText(this, R.string.tv_channel_not_found, Toast.LENGTH_SHORT).show(); + return; + } + } + startActivity(mTvAppIntent); + } + + @Override + protected void createTestItems() { + mPauseResumeItem = createUserItem( + R.string.tv_time_shift_test_pause_resume, + R.string.tv_launch_tv_app, this); + setButtonEnabled(mPauseResumeItem, true); + mVerifyResumeAfterPauseItem = createAutoItem( + R.string.tv_time_shift_test_verify_resume_after_pause); + mVerifyPositionTrackingItem = createAutoItem( + R.string.tv_time_shift_test_verify_position_tracking); + mSetPlaybackParamsItem = createUserItem( + R.string.tv_time_shift_test_speed_rate, + R.string.tv_launch_tv_app, this); + mVerifyRewindItem = createAutoItem( + R.string.tv_time_shift_test_verify_rewind); + mVerifyFastForwardItem = createAutoItem( + R.string.tv_time_shift_test_verify_fast_forward); + mSeekToItem = createUserItem( + R.string.tv_time_shift_test_seek, + R.string.tv_launch_tv_app, this); + mVerifySeekToPreviousItem = createAutoItem( + R.string.tv_time_shift_test_verify_seek_to_previous); + mVerifySeekToNextItem = createAutoItem( + R.string.tv_time_shift_test_verify_seek_to_next); + } + + @Override + protected void setInfoResources() { + setInfoResources(R.string.tv_time_shift_test, + R.string.tv_time_shift_test_info, -1); + } + + private boolean isPassedState(View view) { + return ((Boolean) view.getTag()) == PASSED; + } +}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java index 12e9652..acab18e 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java
@@ -35,8 +35,6 @@ public abstract class TvAppVerifierActivity extends PassFailButtons.Activity { private static final String TAG = "TvAppVerifierActivity"; - private static final long TIMEOUT_MS = 5l * 60l * 1000l; // 5 mins. - private LayoutInflater mInflater; private ViewGroup mItemList; private View mPostTarget;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvInputDiscoveryTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvInputDiscoveryTestActivity.java index 06f4f6f..e8e2cee 100644 --- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvInputDiscoveryTestActivity.java +++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvInputDiscoveryTestActivity.java
@@ -25,8 +25,6 @@ import com.android.cts.verifier.R; -import java.util.List; - /** * Tests for verifying TV app behavior for third-party TV input apps. */ @@ -131,7 +129,7 @@ mGoToEpgItem = createUserItem(R.string.tv_input_discover_test_go_to_epg, R.string.tv_launch_epg, this); mVerifyEpgItem = createUserItem(R.string.tv_input_discover_test_verify_epg, - R.string.tv_input_discover_test_yes, this); + android.R.string.yes, this); } @Override
diff --git a/apps/PermissionApp/Android.mk b/apps/PermissionApp/Android.mk new file mode 100644 index 0000000..57950da --- /dev/null +++ b/apps/PermissionApp/Android.mk
@@ -0,0 +1,31 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# Don't include this package in any target. +LOCAL_MODULE_TAGS := optional + +# When built, explicitly put it in the data partition. +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsPermissionApp + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/apps/PermissionApp/AndroidManifest.xml b/apps/PermissionApp/AndroidManifest.xml new file mode 100644 index 0000000..82e3617 --- /dev/null +++ b/apps/PermissionApp/AndroidManifest.xml
@@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.permissionapp"> + + <uses-sdk android:minSdkVersion="23"/> + + <uses-permission android:name="android.permission.READ_CONTACTS"/> + + <application android:label="CtsPermissionApp" + android:icon="@drawable/ic_permissionapp"> + <activity android:name=".PermissionActivity" > + <intent-filter> + <action android:name="com.android.cts.permission.action.CHECK_HAS_PERMISSION" /> + <action android:name="com.android.cts.permission.action.REQUEST_PERMISSION" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> + +</manifest> +
diff --git a/apps/PermissionApp/res/drawable-hdpi/ic_permissionapp.png b/apps/PermissionApp/res/drawable-hdpi/ic_permissionapp.png new file mode 100644 index 0000000..6fe4112 --- /dev/null +++ b/apps/PermissionApp/res/drawable-hdpi/ic_permissionapp.png Binary files differ
diff --git a/apps/PermissionApp/res/drawable-mdpi/ic_permissionapp.png b/apps/PermissionApp/res/drawable-mdpi/ic_permissionapp.png new file mode 100644 index 0000000..a7a5666 --- /dev/null +++ b/apps/PermissionApp/res/drawable-mdpi/ic_permissionapp.png Binary files differ
diff --git a/apps/PermissionApp/res/drawable-xhdpi/ic_permissionapp.png b/apps/PermissionApp/res/drawable-xhdpi/ic_permissionapp.png new file mode 100644 index 0000000..1e47732 --- /dev/null +++ b/apps/PermissionApp/res/drawable-xhdpi/ic_permissionapp.png Binary files differ
diff --git a/apps/PermissionApp/res/drawable-xxhdpi/ic_permissionapp.png b/apps/PermissionApp/res/drawable-xxhdpi/ic_permissionapp.png new file mode 100644 index 0000000..0e849b3 --- /dev/null +++ b/apps/PermissionApp/res/drawable-xxhdpi/ic_permissionapp.png Binary files differ
diff --git a/apps/PermissionApp/res/drawable-xxxhdpi/ic_permissionapp.png b/apps/PermissionApp/res/drawable-xxxhdpi/ic_permissionapp.png new file mode 100644 index 0000000..242a6b1 --- /dev/null +++ b/apps/PermissionApp/res/drawable-xxxhdpi/ic_permissionapp.png Binary files differ
diff --git a/apps/PermissionApp/src/com/android/cts/permission/permissionapp/PermissionActivity.java b/apps/PermissionApp/src/com/android/cts/permission/permissionapp/PermissionActivity.java new file mode 100644 index 0000000..01b60d3 --- /dev/null +++ b/apps/PermissionApp/src/com/android/cts/permission/permissionapp/PermissionActivity.java
@@ -0,0 +1,89 @@ +/* + * Copyright (C) 2015 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.permissionapp; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; + +import java.lang.Override; + +/** + * A simple activity that requests permissions and returns the result. + */ +public class PermissionActivity extends Activity { + private static final String TAG = "PermissionActivity"; + + private static final String ACTION_CHECK_HAS_PERMISSION + = "com.android.cts.permission.action.CHECK_HAS_PERMISSION"; + private static final String ACTION_REQUEST_PERMISSION + = "com.android.cts.permission.action.REQUEST_PERMISSION"; + private static final String ACTION_PERMISSION_RESULT + = "com.android.cts.permission.action.PERMISSION_RESULT"; + private static final String EXTRA_PERMISSION + = "com.android.cts.permission.extra.PERMISSION"; + private static final String EXTRA_GRANT_STATE + = "com.android.cts.permission.extra.GRANT_STATE"; + private static final int PERMISSION_ERROR = -2; + private static final int PERMISSIONS_REQUEST_CODE = 100; + + private String mPermission; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + final Intent received = getIntent(); + Log.d(TAG, "Started with " + received); + + final String action = received.getAction(); + mPermission = received.getStringExtra(EXTRA_PERMISSION); + if (ACTION_REQUEST_PERMISSION.equals(action)) { + Log.d(TAG, "Requesting permission " + mPermission); + requestPermissions(new String[] {mPermission}, PERMISSIONS_REQUEST_CODE); + } else if (ACTION_CHECK_HAS_PERMISSION.equals(action)) { + Log.d(TAG, "Checking permission " + mPermission); + sendResultBroadcast(checkSelfPermission(mPermission)); + } else { + Log.w(TAG, "Unknown intent received: " + received); + finish(); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, + int[] grantResults) { + if (requestCode != PERMISSIONS_REQUEST_CODE || + permissions.length != 1 || + !permissions[0].equals(mPermission)) { + Log.d(TAG, "Received wrong permissions result"); + sendResultBroadcast(PERMISSION_ERROR); + } else { + Log.d(TAG, "Received valid permission result: " + grantResults[0]); + sendResultBroadcast(grantResults[0]); + } + } + + private void sendResultBroadcast(int result) { + Log.d(TAG, "Sending result broadcast: " + result); + Intent broadcast = new Intent(ACTION_PERMISSION_RESULT); + broadcast.putExtra(EXTRA_GRANT_STATE, result); + sendBroadcast(broadcast); + finish(); + } +}
diff --git a/apps/cts-usb-accessory/Android.mk b/apps/cts-usb-accessory/Android.mk index 8d18da3..f3a7ebd 100644 --- a/apps/cts-usb-accessory/Android.mk +++ b/apps/cts-usb-accessory/Android.mk
@@ -33,6 +33,7 @@ LOCAL_STATIC_LIBRARIES := libusbhost libcutils LOCAL_LDLIBS += -lpthread LOCAL_CFLAGS := -g -O0 +LOCAL_CXX_STL := none include $(BUILD_HOST_EXECUTABLE)
diff --git a/build/config.mk b/build/config.mk index a836f92..56d4ae6 100644 --- a/build/config.mk +++ b/build/config.mk
@@ -14,7 +14,7 @@ # Test XMLs, native executables, and packages will be placed in this # directory before creating the final CTS distribution. -CTS_TESTCASES_OUT := $(HOST_OUT)/cts-testcases +CTS_TESTCASES_OUT := $(HOST_OUT)/cts/android-cts/repository/testcases # Scanners of source files for tests which are then inputed into # the XML generator to produce test XMLs. @@ -34,6 +34,9 @@ # Holds the target architecture to build for. CTS_TARGET_ARCH := $(TARGET_ARCH) +# default module config filename +CTS_MODULE_TEST_CONFIG := AndroidTest.xml + # CTS build rules BUILD_CTS_EXECUTABLE := cts/build/test_executable.mk BUILD_CTS_PACKAGE := cts/build/test_package.mk @@ -42,3 +45,6 @@ BUILD_CTS_TARGET_JAVA_LIBRARY := cts/build/test_target_java_library.mk BUILD_CTS_UI_JAVA_LIBRARY := cts/build/test_uiautomator.mk BUILD_CTS_DEQP_PACKAGE := cts/build/test_deqp_package.mk +BUILD_CTS_SUPPORT_PACKAGE := cts/build/support_package.mk +BUILD_CTS_MODULE_TEST_CONFIG := cts/build/module_test_config.mk +BUILD_CTS_DEVICE_INFO_PACKAGE := cts/build/device_info_package.mk
diff --git a/build/device_info_package.mk b/build/device_info_package.mk new file mode 100644 index 0000000..0aaa8aa --- /dev/null +++ b/build/device_info_package.mk
@@ -0,0 +1,67 @@ +# Copyright (C) 2015 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. + +# +# Builds a package which can be instrumented to retrieve information about the device under test. +# + +DEVICE_INFO_PACKAGE := com.android.compatibility.common.deviceinfo +DEVICE_INFO_INSTRUMENT := com.android.compatibility.common.deviceinfo.DeviceInfoInstrument +DEVICE_INFO_PERMISSIONS += android.permission.WRITE_EXTERNAL_STORAGE +DEVICE_INFO_ACTIVITIES += $(DEVICE_INFO_PACKAGE).GenericDeviceInfo $(DEVICE_INFO_PACKAGE).PackageDeviceInfo + +# Add the base device info +LOCAL_STATIC_JAVA_LIBRARIES += compatibility-device-info + +# Generator of APK manifests. +MANIFEST_GENERATOR_JAR := $(HOST_OUT_JAVA_LIBRARIES)/compatibility-manifest-generator.jar +MANIFEST_GENERATOR := java -jar $(MANIFEST_GENERATOR_JAR) + +# Generate the manifest +manifest_xml := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/AndroidManifest.xml +$(manifest_xml): PRIVATE_INFO_PERMISSIONS := $(foreach permission, $(DEVICE_INFO_PERMISSIONS),-r $(permission)) +$(manifest_xml): PRIVATE_INFO_ACTIVITIES := $(foreach activity,$(DEVICE_INFO_ACTIVITIES),-a $(activity)) +$(manifest_xml): PRIVATE_PACKAGE := $(DEVICE_INFO_PACKAGE) +$(manifest_xml): PRIVATE_INSTRUMENT := $(DEVICE_INFO_INSTRUMENT) + +# Regenerate manifest.xml if the generator jar, */cts-device-info/Android.mk, or this file is changed. +$(manifest_xml): $(MANIFEST_GENERATOR_JAR) $(LOCAL_PATH)/Android.mk cts/build/device_info_package.mk + $(hide) echo Generating manifest for $(PRIVATE_NAME) + $(hide) mkdir -p $(dir $@) + $(hide) $(MANIFEST_GENERATOR) \ + $(PRIVATE_INFO_PERMISSIONS) \ + $(PRIVATE_INFO_ACTIVITIES) \ + -p $(PRIVATE_PACKAGE) \ + -i $(PRIVATE_INSTRUMENT) \ + -o $@ + +# Reset variables +DEVICE_INFO_PACKAGE := +DEVICE_INFO_INSTRUMENT := +DEVICE_INFO_PERMISSIONS := +DEVICE_INFO_ACTIVITIES := + +LOCAL_FULL_MANIFEST_FILE := $(manifest_xml) +# Disable by default +LOCAL_DEX_PREOPT := false +LOCAL_PROGUARD_ENABLED := disabled + +# Don't include this package in any target +LOCAL_MODULE_TAGS := optional +# And when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/build/module_test_config.mk b/build/module_test_config.mk new file mode 100644 index 0000000..6584ef2 --- /dev/null +++ b/build/module_test_config.mk
@@ -0,0 +1,21 @@ +# Copyright (C) 2015 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. + +cts_module_test_config := $(if $(wildcard \ + $(LOCAL_PATH)/$(CTS_MODULE_TEST_CONFIG)), \ + $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).config) +ifneq ($(cts_module_test_config),) +$(cts_module_test_config): $(LOCAL_PATH)/$(CTS_MODULE_TEST_CONFIG) | $(ACP) + $(call copy-file-to-target) +endif
diff --git a/build/support_package.mk b/build/support_package.mk new file mode 100644 index 0000000..16a254e --- /dev/null +++ b/build/support_package.mk
@@ -0,0 +1,36 @@ +# Copyright (C) 2015 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. + +# +# Builds a package which is needed by a test package and copies it to CTS +# +# Replace "include $(BUILD_PACKAGE)" with "include $(BUILD_CTS_SUPPORT_PACKAGE)" +# + +# Disable by default so "m cts" will work in emulator builds +LOCAL_DEX_PREOPT := false +LOCAL_PROGUARD_ENABLED := disabled + +include $(BUILD_PACKAGE) + +cts_support_apks := +$(foreach fp, $(ALL_MODULES.$(LOCAL_PACKAGE_NAME).BUILT_INSTALLED),\ + $(eval pair := $(subst :,$(space),$(fp)))\ + $(eval built := $(word 1,$(pair)))\ + $(eval installed := $(CTS_TESTCASES_OUT)/$(notdir $(word 2,$(pair))))\ + $(eval $(call copy-one-file, $(built), $(installed)))\ + $(eval cts_support_apks += $(installed))) + +# Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. +$(my_register_name) : $(cts_support_apks)
diff --git a/build/test_deqp_package.mk b/build/test_deqp_package.mk index b07876d..8fbae26 100644 --- a/build/test_deqp_package.mk +++ b/build/test_deqp_package.mk
@@ -19,15 +19,14 @@ CTS_DEQP_CONFIG_PATH := $(call my-dir) cts_library_xml := $(CTS_TESTCASES_OUT)/com.drawelements.deqp.$(DEQP_API).xml - -$(cts_library_xml): MUSTPASS_XML_FILE := external/deqp/android/cts/com.drawelements.deqp.$(DEQP_API).xml +$(cts_library_xml): MUSTPASS_XML_FILE := external/deqp/android/cts/master/com.drawelements.deqp.$(DEQP_API).xml $(cts_library_xml): PRIVATE_TEST_NAME := $(DEQP_TEST_NAME) $(cts_library_xml): PRIVATE_TEST_PACKAGE := com.drawelements.deqp.$(DEQP_API) $(cts_library_xml): PRIVATE_DUMMY_CASELIST := $(CTS_DEQP_CONFIG_PATH)/deqp_dummy_test_list -$(cts_library_xml): $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/package.apk external/deqp/android/cts/com.drawelements.deqp.$(DEQP_API).xml $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_XML_GENERATOR) +$(cts_library_xml): external/deqp/android/cts/master/com.drawelements.deqp.$(DEQP_API).xml $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for $(PRIVATE_TEST_NAME) $(hide) mkdir -p $(CTS_TESTCASES_OUT) - + # Query build ABIs by routing a dummy test list through xml generator and parse result $(hide) $(eval supported_abi_attr := $(shell $(CTS_XML_GENERATOR) -t dummyTest \ -n dummyName \ @@ -37,8 +36,8 @@ -a $(CTS_TARGET_ARCH) \ < $(PRIVATE_DUMMY_CASELIST) \ | grep --only-matching -e " abis=\"[^\"]*\"")) - + # Patch xml caselist with supported abi - $(hide) $(SED_EXTENDED) -e 's:^<Test (.*)/>$$:<Test \1 $(supported_abi_attr) />:' \ + $(hide) $(SED_EXTENDED) -e 's:^(\s*)<Test ((.[^/]|[^/])*)(/?)>$$:\1<Test \2 $(supported_abi_attr)\4>:' \ < $(MUSTPASS_XML_FILE) \ > $@
diff --git a/build/test_executable.mk b/build/test_executable.mk index 3cabdf3..979f59e 100644 --- a/build/test_executable.mk +++ b/build/test_executable.mk
@@ -25,14 +25,22 @@ LOCAL_CXX_STL := libc++ include $(BUILD_EXECUTABLE) +include $(BUILD_CTS_MODULE_TEST_CONFIG) + +cts_executable_bin := +$(foreach fp, $(ALL_MODULES.$(LOCAL_MODULE).BUILT) $(ALL_MODULES.$(LOCAL_MODULE)$(TARGET_2ND_ARCH_MODULE_SUFFIX).BUILT),\ + $(eval installed := $(CTS_TESTCASES_OUT)/$(notdir $(fp)))\ + $(eval $(call copy-one-file, $(fp), $(installed)))\ + $(eval cts_executable_bin += $(installed))) cts_executable_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml - $(cts_executable_xml): PRIVATE_TEST_PACKAGE := $(LOCAL_CTS_TEST_PACKAGE) $(cts_executable_xml): PRIVATE_EXECUTABLE := $(LOCAL_MODULE) $(cts_executable_xml): PRIVATE_LIST_EXECUTABLE := $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)_list $(cts_executable_xml): $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)_list -$(cts_executable_xml): $(addprefix $(LOCAL_PATH)/,$(LOCAL_SRC_FILES)) $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_NATIVE_TEST_SCANNER) $(CTS_XML_GENERATOR) $(cts_list_executable) +$(cts_executable_xml): $(cts_executable_bin) +$(cts_executable_xml): $(cts_module_test_config) +$(cts_executable_xml): $(addprefix $(LOCAL_PATH)/,$(LOCAL_SRC_FILES)) $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_NATIVE_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for native package $(PRIVATE_TEST_PACKAGE) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) $(PRIVATE_LIST_EXECUTABLE) --gtest_list_tests | \ @@ -46,4 +54,4 @@ -o $@ # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_executable_xml) +$(my_register_name) : $(cts_executable_bin) $(cts_executable_xml) $(cts_module_test_config)
diff --git a/build/test_gtest_package.mk b/build/test_gtest_package.mk index dd1269b..6f71830 100644 --- a/build/test_gtest_package.mk +++ b/build/test_gtest_package.mk
@@ -23,23 +23,19 @@ LOCAL_DEX_PREOPT := false LOCAL_PROGUARD_ENABLED := disabled -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) +include $(BUILD_CTS_MODULE_TEST_CONFIG) -cts_package_apk := $(CTS_TESTCASES_OUT)/$(LOCAL_PACKAGE_NAME).apk cts_package_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_PACKAGE_NAME).xml -cts_test_list := $(LOCAL_PATH)/$(LOCAL_MODULE)_list.txt - -$(cts_package_apk): PRIVATE_PACKAGE := $(LOCAL_PACKAGE_NAME) -$(cts_package_apk): $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/package.apk | $(ACP) - $(hide) mkdir -p $(CTS_TESTCASES_OUT) - $(hide) $(ACP) -fp $(call intermediates-dir-for,APPS,$(PRIVATE_PACKAGE))/package.apk $@ - $(cts_package_xml): PRIVATE_PATH := $(LOCAL_PATH) $(cts_package_xml): PRIVATE_TEST_PACKAGE := android.$(notdir $(LOCAL_PATH)) $(cts_package_xml): PRIVATE_EXECUTABLE := $(LOCAL_MODULE) $(cts_package_xml): PRIVATE_MANIFEST := $(LOCAL_PATH)/AndroidManifest.xml -$(cts_package_xml): PRIVATE_TEST_LIST := $(cts_test_list) -$(cts_package_xml): $(addprefix $(LOCAL_PATH)/,$(LOCAL_SRC_FILES)) $(CTS_NATIVE_TEST_SCANNER) $(CTS_XML_GENERATOR) $(cts_test_list) +$(cts_package_xml): PRIVATE_TEST_LIST := $(LOCAL_PATH)/$(LOCAL_MODULE)_list.txt +$(cts_package_xml): $(LOCAL_PATH)/$(LOCAL_MODULE)_list.txt +$(cts_package_xml): $(cts_support_apks) +$(cts_package_xml): $(cts_module_test_config) +$(cts_package_xml): $(addprefix $(LOCAL_PATH)/,$(LOCAL_SRC_FILES)) $(CTS_NATIVE_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for wrapped native package $(PRIVATE_EXECUTABLE) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) cat $(PRIVATE_TEST_LIST) | \ @@ -54,4 +50,4 @@ -o $@ # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_package_apk) $(cts_package_xml) +$(my_register_name) : $(cts_package_xml) $(cts_module_test_config)
diff --git a/build/test_host_java_library.mk b/build/test_host_java_library.mk index 8ed5670..7fdefb5 100644 --- a/build/test_host_java_library.mk +++ b/build/test_host_java_library.mk
@@ -18,18 +18,24 @@ # include $(BUILD_HOST_JAVA_LIBRARY) +include $(BUILD_CTS_MODULE_TEST_CONFIG) -cts_library_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml +cts_library_jar := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).jar +$(cts_library_jar): $(LOCAL_BUILT_MODULE) + $(copy-file-to-target) cts_src_dirs := $(LOCAL_PATH)/src cts_src_dirs += $(sort $(dir $(LOCAL_GENERATED_SOURCES))) cts_src_dirs := $(addprefix -s , $(cts_src_dirs)) +cts_library_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml $(cts_library_xml): PRIVATE_SRC_DIRS := $(cts_src_dirs) $(cts_library_xml): PRIVATE_TEST_PACKAGE := $(LOCAL_CTS_TEST_PACKAGE) $(cts_library_xml): PRIVATE_LIBRARY := $(LOCAL_MODULE) $(cts_library_xml): PRIVATE_JAR_PATH := $(LOCAL_MODULE).jar -$(cts_library_xml): $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE).jar $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) +$(cts_library_xml): $(cts_library_jar) +$(cts_library_xml): $(cts_module_test_config) +$(cts_library_xml): $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for host library $(PRIVATE_LIBRARY) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) $(CTS_JAVA_TEST_SCANNER) $(PRIVATE_SRC_DIRS) \ @@ -44,4 +50,4 @@ -o $@ # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_library_xml) +$(my_register_name) : $(cts_library_jar) $(cts_library_xml) $(cts_module_test_config)
diff --git a/build/test_package.mk b/build/test_package.mk index 7589787..c6b0865 100644 --- a/build/test_package.mk +++ b/build/test_package.mk
@@ -23,20 +23,14 @@ LOCAL_DEX_PREOPT := false LOCAL_PROGUARD_ENABLED := disabled -include $(BUILD_PACKAGE) - -cts_package_apk := $(CTS_TESTCASES_OUT)/$(LOCAL_PACKAGE_NAME).apk -cts_package_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_PACKAGE_NAME).xml +include $(BUILD_CTS_SUPPORT_PACKAGE) +include $(BUILD_CTS_MODULE_TEST_CONFIG) cts_src_dirs := $(LOCAL_PATH) cts_src_dirs += $(sort $(dir $(LOCAL_GENERATED_SOURCES))) cts_src_dirs := $(addprefix -s , $(cts_src_dirs)) -$(cts_package_apk): PRIVATE_PACKAGE := $(LOCAL_PACKAGE_NAME) -$(cts_package_apk): $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/package.apk | $(ACP) - $(hide) mkdir -p $(CTS_TESTCASES_OUT) - $(hide) $(ACP) -fp $(call intermediates-dir-for,APPS,$(PRIVATE_PACKAGE))/package.apk $@ - +cts_package_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_PACKAGE_NAME).xml $(cts_package_xml): PRIVATE_SRC_DIRS := $(cts_src_dirs) $(cts_package_xml): PRIVATE_INSTRUMENTATION := $(LOCAL_INSTRUMENTATION_FOR) $(cts_package_xml): PRIVATE_PACKAGE := $(LOCAL_PACKAGE_NAME) @@ -48,7 +42,9 @@ $(cts_package_xml): PRIVATE_TEST_PACKAGE := $(PRIVATE_CTS_TEST_PACKAGE_NAME_) $(cts_package_xml): PRIVATE_MANIFEST := $(LOCAL_PATH)/AndroidManifest.xml $(cts_package_xml): PRIVATE_TEST_TYPE := $(if $(LOCAL_CTS_TEST_RUNNER),$(LOCAL_CTS_TEST_RUNNER),'') -$(cts_package_xml): $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/package.apk $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) +$(cts_package_xml): $(cts_support_apks) +$(cts_package_xml): $(cts_module_test_config) +$(cts_package_xml): $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for java package $(PRIVATE_PACKAGE) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) $(CTS_JAVA_TEST_SCANNER) \ @@ -64,6 +60,5 @@ -b $(CTS_UNSUPPORTED_ABIS) \ -a $(CTS_TARGET_ARCH) \ -o $@ - # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_package_apk) $(cts_package_xml) +$(my_register_name) : $(cts_package_xml) $(cts_module_test_config)
diff --git a/build/test_target_java_library.mk b/build/test_target_java_library.mk index 04fffb9..fe1000a 100644 --- a/build/test_target_java_library.mk +++ b/build/test_target_java_library.mk
@@ -19,8 +19,10 @@ # Disable by default so "m cts" will work in emulator builds LOCAL_DEX_PREOPT := false include $(BUILD_JAVA_LIBRARY) +include $(BUILD_CTS_MODULE_TEST_CONFIG) + cts_library_jar := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).jar -$(cts_library_jar): $(LOCAL_BUILT_MODULE) | $(ACP) +$(cts_library_jar): $(LOCAL_BUILT_MODULE) $(copy-file-to-target) cts_library_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml @@ -30,7 +32,9 @@ $(cts_library_xml): PRIVATE_LIBRARY := $(LOCAL_MODULE) $(cts_library_xml): PRIVATE_JAR_PATH := $(LOCAL_MODULE).jar $(cts_library_xml): PRIVATE_RUNTIME_ARGS := $(LOCAL_CTS_TARGET_RUNTIME_ARGS) -$(cts_library_xml): $(TARGET_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE).jar $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) +$(cts_library_xml): $(cts_library_jar) +$(cts_library_xml): $(cts_module_test_config) +$(cts_library_xml): $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for target library $(PRIVATE_LIBRARY) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) $(CTS_JAVA_TEST_SCANNER) -s $(PRIVATE_PATH) \ @@ -46,4 +50,4 @@ -o $@ # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_library_jar) $(cts_library_xml) +$(my_register_name) : $(cts_library_jar) $(cts_library_xml $(cts_module_test_config))
diff --git a/build/test_uiautomator.mk b/build/test_uiautomator.mk index cad6e4f..a191d72 100644 --- a/build/test_uiautomator.mk +++ b/build/test_uiautomator.mk
@@ -20,26 +20,26 @@ LOCAL_DEX_PREOPT := false include $(BUILD_JAVA_LIBRARY) +include $(BUILD_CTS_MODULE_TEST_CONFIG) -cts_library_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml cts_library_jar := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).jar +$(cts_library_jar): $(LOCAL_BUILT_MODULE) + $(call copy-file-to-target) cts_src_dirs := $(LOCAL_PATH)/src cts_src_dirs += $(sort $(dir $(LOCAL_GENERATED_SOURCES))) cts_src_dirs := $(addprefix -s , $(cts_src_dirs)) -$(cts_library_jar): PRIVATE_MODULE := $(LOCAL_MODULE) -$(cts_library_jar): $(call intermediates-dir-for,JAVA_LIBRARIES,$(LOCAL_MODULE))/javalib.jar | $(ACP) - $(hide) mkdir -p $(CTS_TESTCASES_OUT) - $(hide) $(ACP) -fp $(call intermediates-dir-for,JAVA_LIBRARIES,$(PRIVATE_MODULE))/javalib.jar $@ - +cts_library_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml $(cts_library_xml): PRIVATE_SRC_DIRS := $(cts_src_dirs) $(cts_library_xml): PRIVATE_TEST_APP_PACKAGE := $(LOCAL_CTS_TEST_APP_PACKAGE) $(cts_library_xml): PRIVATE_TEST_PACKAGE := $(LOCAL_CTS_TEST_PACKAGE) $(cts_library_xml): PRIVATE_TEST_APK := $(LOCAL_CTS_TEST_APK) $(cts_library_xml): PRIVATE_LIBRARY := $(LOCAL_MODULE) $(cts_library_xml): PRIVATE_JAR_PATH := $(LOCAL_MODULE).jar -$(cts_library_xml): $(call intermediates-dir-for,JAVA_LIBRARIES,$(LOCAL_MODULE))/javalib.jar $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) +$(cts_library_xml): $(cts_library_jar) +$(cts_library_xml): $(cts_module_test_config) +$(cts_library_xml): $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_JAVA_TEST_SCANNER_DOCLET) $(CTS_JAVA_TEST_SCANNER) $(CTS_XML_GENERATOR) $(hide) echo Generating test description for uiautomator library $(PRIVATE_LIBRARY) $(hide) mkdir -p $(CTS_TESTCASES_OUT) $(hide) $(CTS_JAVA_TEST_SCANNER) $(PRIVATE_SRC_DIRS) \ @@ -57,4 +57,4 @@ -o $@ # Have the module name depend on the cts files; so the cts files get generated when you run mm/mmm/mma/mmma. -$(my_register_name) : $(cts_library_jar) $(cts_library_xml) +$(my_register_name) : $(cts_library_jar) $(cts_library_xml) $(cts_module_test_config)
diff --git a/common/device-side/device-info/Android.mk b/common/device-side/device-info/Android.mk new file mode 100644 index 0000000..8c5052b --- /dev/null +++ b/common/device-side/device-info/Android.mk
@@ -0,0 +1,29 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE := compatibility-device-info + +LOCAL_SDK_VERSION := current + +include $(BUILD_STATIC_JAVA_LIBRARY) + +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivity.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivity.java new file mode 100644 index 0000000..f9de6eb --- /dev/null +++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivity.java
@@ -0,0 +1,450 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Environment; +import android.text.TextUtils; +import android.util.JsonWriter; +import android.util.Log; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.concurrent.CountDownLatch; + +/** + * Collect device information on target device and write to a JSON file. + */ +public abstract class DeviceInfoActivity extends Activity { + + /** Device info result code: collector failed to complete. */ + private static final int DEVICE_INFO_RESULT_FAILED = -2; + /** Device info result code: collector completed with error. */ + private static final int DEVICE_INFO_RESULT_ERROR = -1; + /** Device info result code: collector has started but not completed. */ + private static final int DEVICE_INFO_RESULT_STARTED = 0; + /** Device info result code: collector completed success. */ + private static final int DEVICE_INFO_RESULT_OK = 1; + + private static final int MAX_STRING_VALUE_LENGTH = 1000; + private static final int MAX_ARRAY_LENGTH = 1000; + + private static final String LOG_TAG = "DeviceInfoActivity"; + + private CountDownLatch mDone = new CountDownLatch(1); + private JsonWriter mJsonWriter = null; + private String mResultFilePath = null; + private String mErrorMessage = "Collector has started."; + private int mResultCode = DEVICE_INFO_RESULT_STARTED; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (createFilePath()) { + createJsonWriter(); + startJsonWriter(); + collectDeviceInfo(); + closeJsonWriter(); + + if (mResultCode == DEVICE_INFO_RESULT_STARTED) { + mResultCode = DEVICE_INFO_RESULT_OK; + } + } + + Intent data = new Intent(); + if (mResultCode == DEVICE_INFO_RESULT_OK) { + data.setData(Uri.parse(mResultFilePath)); + setResult(RESULT_OK, data); + } else { + data.setData(Uri.parse(mErrorMessage)); + setResult(RESULT_CANCELED, data); + } + + mDone.countDown(); + finish(); + } + + /** + * Method to collect device information. + */ + protected abstract void collectDeviceInfo(); + + void waitForActivityToFinish() { + try { + mDone.await(); + } catch (Exception e) { + failed("Exception while waiting for activity to finish: " + e.getMessage()); + } + } + + /** + * Returns the error message if collector did not complete successfully. + */ + String getErrorMessage() { + if (mResultCode == DEVICE_INFO_RESULT_OK) { + return null; + } + return mErrorMessage; + } + + /** + * Returns the path to the json file if collector completed successfully. + */ + String getResultFilePath() { + if (mResultCode == DEVICE_INFO_RESULT_OK) { + return mResultFilePath; + } + return null; + } + + private void error(String message) { + mResultCode = DEVICE_INFO_RESULT_ERROR; + mErrorMessage = message; + Log.e(LOG_TAG, message); + } + + private void failed(String message) { + mResultCode = DEVICE_INFO_RESULT_FAILED; + mErrorMessage = message; + Log.e(LOG_TAG, message); + } + + private boolean createFilePath() { + if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + failed("External storage is not mounted"); + return false; + } + final File dir = new File(Environment.getExternalStorageDirectory(), "device-info-files"); + if (!dir.mkdirs() && !dir.isDirectory()) { + failed("Cannot create directory for device info files"); + return false; + } + + // Create file at /sdcard/device-info-files/<class_name>.deviceinfo.json + final File jsonFile = new File(dir, getClass().getSimpleName() + ".deviceinfo.json"); + try { + jsonFile.createNewFile(); + } catch (Exception e) { + failed("Cannot create file to collect device info"); + return false; + } + mResultFilePath = jsonFile.getAbsolutePath(); + return true; + } + + private void createJsonWriter() { + try { + FileOutputStream out = new FileOutputStream(mResultFilePath); + mJsonWriter = new JsonWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); + // TODO(agathaman): remove to make json output less pretty + mJsonWriter.setIndent(" "); + } catch (Exception e) { + failed("Failed to create JSON writer: " + e.getMessage()); + } + } + + private void startJsonWriter() { + try { + mJsonWriter.beginObject(); + } catch (Exception e) { + failed("Failed to begin JSON object: " + e.getMessage()); + } + } + + private void closeJsonWriter() { + try { + mJsonWriter.endObject(); + mJsonWriter.close(); + } catch (Exception e) { + failed("Failed to close JSON object: " + e.getMessage()); + } + } + + /** + * Start a new group of result. + */ + public void startGroup() { + try { + mJsonWriter.beginObject(); + } catch (Exception e) { + error("Failed to begin JSON group: " + e.getMessage()); + } + } + + /** + * Start a new group of result with specified name. + */ + public void startGroup(String name) { + try { + mJsonWriter.name(name); + mJsonWriter.beginObject(); + } catch (Exception e) { + error("Failed to begin JSON group: " + e.getMessage()); + } + } + + /** + * Complete adding result to the last started group. + */ + public void endGroup() { + try { + mJsonWriter.endObject(); + } catch (Exception e) { + error("Failed to end JSON group: " + e.getMessage()); + } + } + + /** + * Start a new array of result. + */ + public void startArray() { + try { + mJsonWriter.beginArray(); + } catch (Exception e) { + error("Failed to begin JSON array: " + e.getMessage()); + } + } + + /** + * Start a new array of result with specified name. + */ + public void startArray(String name) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + } catch (Exception e) { + error("Failed to begin JSON array: " + e.getMessage()); + } + } + + /** + * Complete adding result to the last started array. + */ + public void endArray() { + try { + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to end JSON group: " + e.getMessage()); + } + } + + /** + * Add a double value result. + */ + public void addResult(String name, double value) { + checkName(name); + try { + mJsonWriter.name(name).value(value); + } catch (Exception e) { + error("Failed to add result for type double: " + e.getMessage()); + } + } + + /** + * Add a long value result. + */ + public void addResult(String name, long value) { + checkName(name); + try { + mJsonWriter.name(name).value(value); + } catch (Exception e) { + error("Failed to add result for type long: " + e.getMessage()); + } + } + + /** + * Add an int value result. + */ + public void addResult(String name, int value) { + checkName(name); + try { + mJsonWriter.name(name).value((Number) value); + } catch (Exception e) { + error("Failed to add result for type int: " + e.getMessage()); + } + } + + /** + * Add a boolean value result. + */ + public void addResult(String name, boolean value) { + checkName(name); + try { + mJsonWriter.name(name).value(value); + } catch (Exception e) { + error("Failed to add result for type boolean: " + e.getMessage()); + } + } + + /** + * Add a String value result. + */ + public void addResult(String name, String value) { + checkName(name); + try { + mJsonWriter.name(name).value(checkString(value)); + } catch (Exception e) { + error("Failed to add result for type String: " + e.getMessage()); + } + } + + /** + * Add a double array result. + */ + public void addArray(String name, double[] list) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + for (double value : checkArray(list)) { + mJsonWriter.value(value); + } + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to add result array for type double: " + e.getMessage()); + } + } + + /** + * Add a long array result. + */ + public void addArray(String name, long[] list) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + for (long value : checkArray(list)) { + mJsonWriter.value(value); + } + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to add result array for type long: " + e.getMessage()); + } + } + + /** + * Add an int array result. + */ + public void addArray(String name, int[] list) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + for (int value : checkArray(list)) { + mJsonWriter.value((Number) value); + } + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to add result array for type int: " + e.getMessage()); + } + } + + /** + * Add a boolean array result. + */ + public void addArray(String name, boolean[] list) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + for (boolean value : checkArray(list)) { + mJsonWriter.value(value); + } + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to add result array for type boolean: " + e.getMessage()); + } + } + + /** + * Add a String array result. + */ + public void addArray(String name, String[] list) { + checkName(name); + try { + mJsonWriter.name(name); + mJsonWriter.beginArray(); + for (String value : checkArray(list)) { + mJsonWriter.value(checkString(value)); + } + mJsonWriter.endArray(); + } catch (Exception e) { + error("Failed to add result array for type Sting: " + e.getMessage()); + } + } + + private static boolean[] checkArray(boolean[] values) { + if (values.length > MAX_ARRAY_LENGTH) { + return Arrays.copyOf(values, MAX_ARRAY_LENGTH); + } else { + return values; + } + } + + private static double[] checkArray(double[] values) { + if (values.length > MAX_ARRAY_LENGTH) { + return Arrays.copyOf(values, MAX_ARRAY_LENGTH); + } else { + return values; + } + } + + private static int[] checkArray(int[] values) { + if (values.length > MAX_ARRAY_LENGTH) { + return Arrays.copyOf(values, MAX_ARRAY_LENGTH); + } else { + return values; + } + } + + private static long[] checkArray(long[] values) { + if (values.length > MAX_ARRAY_LENGTH) { + return Arrays.copyOf(values, MAX_ARRAY_LENGTH); + } else { + return values; + } + } + + private static String[] checkArray(String[] values) { + if (values.length > MAX_ARRAY_LENGTH) { + return Arrays.copyOf(values, MAX_ARRAY_LENGTH); + } else { + return values; + } + } + + private static String checkString(String value) { + if (value.length() > MAX_STRING_VALUE_LENGTH) { + return value.substring(0, MAX_STRING_VALUE_LENGTH); + } + return value; + } + + private static String checkName(String value) { + if (TextUtils.isEmpty(value)) { + throw new NullPointerException(); + } + return value; + } +} +
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoInstrument.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoInstrument.java new file mode 100644 index 0000000..2f80911 --- /dev/null +++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfoInstrument.java
@@ -0,0 +1,133 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.app.Activity; +import android.app.Instrumentation; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * An instrumentation that runs all activities that extends DeviceInfoActivity. + */ +public class DeviceInfoInstrument extends Instrumentation { + + private static final String LOG_TAG = "ExtendedDeviceInfo"; + private static final String COLLECTOR = "collector"; + + // List of collectors to run. If null or empty, all collectors will run. + private Set<String> mCollectorSet = new HashSet<String>(); + + // Results sent to the caller when this istrumentation completes. + private Bundle mBundle = new Bundle(); + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (savedInstanceState != null) { + String collectorList = savedInstanceState.getString(COLLECTOR); + if (!TextUtils.isEmpty(collectorList)) { + for (String collector : TextUtils.split(collectorList, ",")) { + if (!TextUtils.isEmpty(collector)) { + mCollectorSet.add(collector); + } + } + } + } + start(); + } + + @Override + public void onStart() { + try { + Context context = getContext(); + ActivityInfo[] activities = context.getPackageManager().getPackageInfo( + context.getPackageName(), PackageManager.GET_ACTIVITIES).activities; + for (ActivityInfo activityInfo : activities) { + runActivity(activityInfo.name); + } + } catch (Exception e) { + Log.e(LOG_TAG, "Exception occurred while running activities.", e); + // Returns INSTRUMENTATION_CODE: 0 + finish(Activity.RESULT_CANCELED, mBundle); + } + // Returns INSTRUMENTATION_CODE: -1 + finish(Activity.RESULT_OK, mBundle); + } + + /** + * Returns true if the activity meets the criteria to run; otherwise, false. + */ + private boolean isActivityRunnable(Class activityClass) { + // Don't run the base DeviceInfoActivity class. + if (DeviceInfoActivity.class == activityClass) { + return false; + } + // Don't run anything that doesn't extends DeviceInfoActivity. + if (!DeviceInfoActivity.class.isAssignableFrom(activityClass)) { + return false; + } + // Only run activity if mCollectorSet is empty or contains it. + if (mCollectorSet != null && mCollectorSet.size() > 0) { + return mCollectorSet.contains(activityClass.getName()); + } + // Run anything that makes it here. + return true; + } + + /** + * Runs a device info activity and return the file path where the results are written to. + */ + private void runActivity(String activityName) throws Exception { + Class activityClass = null; + try { + activityClass = Class.forName(activityName); + } catch (ClassNotFoundException e) { + return; + } + + if (activityClass == null || !isActivityRunnable(activityClass)) { + return; + } + + Intent intent = new Intent(); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setClassName(this.getContext(), activityName); + + DeviceInfoActivity activity = (DeviceInfoActivity) startActivitySync(intent); + waitForIdleSync(); + activity.waitForActivityToFinish(); + + String className = activityClass.getSimpleName(); + String errorMessage = activity.getErrorMessage(); + if (TextUtils.isEmpty(errorMessage)) { + mBundle.putString(className, activity.getResultFilePath()); + } else { + mBundle.putString(className, errorMessage); + throw new Exception(errorMessage); + } + } +} +
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/GenericDeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/GenericDeviceInfo.java new file mode 100644 index 0000000..f6e7c57 --- /dev/null +++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/GenericDeviceInfo.java
@@ -0,0 +1,97 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.app.Activity; +import android.app.Instrumentation; +import android.content.Context; +import android.content.Intent; +import android.content.pm.FeatureInfo; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.os.UserManager; +import android.telephony.TelephonyManager; +import android.text.TextUtils; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.Display; +import android.view.WindowManager; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Scanner; +import java.util.Set; + +import com.android.compatibility.common.deviceinfo.DeviceInfoActivity; + +/** + * Generic device info collector. + */ +public class GenericDeviceInfo extends DeviceInfoActivity { + + public static final String BUILD_ID = "build_id"; + public static final String BUILD_PRODUCT = "build_product"; + public static final String BUILD_DEVICE = "build_device"; + public static final String BUILD_BOARD = "build_board"; + public static final String BUILD_MANUFACTURER = "build_manufacturer"; + public static final String BUILD_BRAND = "build_brand"; + public static final String BUILD_MODEL = "build_model"; + public static final String BUILD_TYPE = "build_type"; + public static final String BUILD_FINGERPRINT = "build_fingerprint"; + public static final String BUILD_ABI = "build_abi"; + public static final String BUILD_ABI2 = "build_abi2"; + public static final String BUILD_ABIS = "build_abis"; + public static final String BUILD_ABIS_32 = "build_abis_32"; + public static final String BUILD_ABIS_64 = "build_abis_64"; + public static final String BUILD_SERIAL = "build_serial"; + public static final String BUILD_VERSION_RELEASE = "build_version_release"; + public static final String BUILD_VERSION_SDK = "build_version_sdk"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + protected void collectDeviceInfo() { + addResult(BUILD_ID, Build.ID); + addResult(BUILD_PRODUCT, Build.PRODUCT); + addResult(BUILD_DEVICE, Build.DEVICE); + addResult(BUILD_BOARD, Build.BOARD); + addResult(BUILD_MANUFACTURER, Build.MANUFACTURER); + addResult(BUILD_BRAND, Build.BRAND); + addResult(BUILD_MODEL, Build.MODEL); + addResult(BUILD_TYPE, Build.TYPE); + addResult(BUILD_FINGERPRINT, Build.FINGERPRINT); + addResult(BUILD_ABI, Build.CPU_ABI); + addResult(BUILD_ABI2, Build.CPU_ABI2); + addResult(BUILD_ABIS, TextUtils.join(",", Build.SUPPORTED_ABIS)); + addResult(BUILD_ABIS_32, TextUtils.join(",", Build.SUPPORTED_32_BIT_ABIS)); + addResult(BUILD_ABIS_64, TextUtils.join(",", Build.SUPPORTED_64_BIT_ABIS)); + addResult(BUILD_SERIAL, Build.SERIAL); + addResult(BUILD_VERSION_RELEASE, Build.VERSION.RELEASE); + addResult(BUILD_VERSION_SDK, Build.VERSION.SDK); + } +} \ No newline at end of file
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java new file mode 100644 index 0000000..4d9ad46 --- /dev/null +++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java
@@ -0,0 +1,50 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; + +import com.android.compatibility.common.deviceinfo.DeviceInfoActivity; + +/** + * PackageDeviceInfo collector. + */ +public class PackageDeviceInfo extends DeviceInfoActivity { + + private static final String PACKAGE = "package"; + private static final String NAME = "name"; + private static final String VERSION_NAME = "version_name"; + private static final String SYSTEM_PRIV = "system_priv"; + private static final String PRIV_APP_DIR = "/system/priv-app"; + + @Override + protected void collectDeviceInfo() { + PackageManager pm = this.getPackageManager(); + startArray(PACKAGE); + for (PackageInfo pkg : pm.getInstalledPackages(0)) { + startGroup(); + addResult(NAME, pkg.packageName); + addResult(VERSION_NAME, pkg.versionName); + + String dir = pkg.applicationInfo.sourceDir; + addResult(SYSTEM_PRIV, dir != null && dir.startsWith(PRIV_APP_DIR)); + endGroup(); + } + endArray(); // Package + } +}
diff --git a/common/device-side/device-info/tests/Android.mk b/common/device-side/device-info/tests/Android.mk new file mode 100644 index 0000000..e24c5c1 --- /dev/null +++ b/common/device-side/device-info/tests/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-info + +LOCAL_JAVA_LIBRARIES := android.test.runner + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE := compatibility-device-info-tests + +include $(BUILD_STATIC_JAVA_LIBRARY) +
diff --git a/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivityTest.java b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivityTest.java new file mode 100644 index 0000000..d092f4e --- /dev/null +++ b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/DeviceInfoActivityTest.java
@@ -0,0 +1,79 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.test.ActivityInstrumentationTestCase2; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * Test for {@link DeviceInfoActivity}. + */ +public class DeviceInfoActivityTest extends ActivityInstrumentationTestCase2<TestDeviceInfo> { + + private static final String EXPECTED_FILE_PATH = + "/storage/emulated/0/device-info-files/TestDeviceInfo.deviceinfo.json"; + + private TestDeviceInfo mActivity; + + public DeviceInfoActivityTest() { + super(TestDeviceInfo.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + // Start the activity and get a reference to it. + mActivity = getActivity(); + // Wait for the activity to finish. + mActivity.waitForActivityToFinish(); + } + + @Override + protected void tearDown() throws Exception { + mActivity = null; + super.tearDown(); + } + + public void testJsonFile() throws IOException { + String resultFilePath = mActivity.getResultFilePath(); + // Check file path exist + assertNotNull("Expected a non-null resultFilePath", resultFilePath); + // Check file path location + assertEquals("Incorrect file path", EXPECTED_FILE_PATH, resultFilePath); + // Check json file content + String jsonContent = readFile(resultFilePath); + assertEquals("Incorrect json output", ExampleObjects.testDeviceInfoJson(), jsonContent); + } + + private String readFile(String filePath) throws IOException { + InputStreamReader inputStreamReader = new InputStreamReader( + new FileInputStream(filePath), "UTF-8"); + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String line; + while((line = bufferedReader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append('\n'); + } + bufferedReader.close(); + return stringBuilder.toString(); + } +} +
diff --git a/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/ExampleObjects.java b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/ExampleObjects.java new file mode 100644 index 0000000..570bdd5 --- /dev/null +++ b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/ExampleObjects.java
@@ -0,0 +1,92 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +/** + * Example Objects for {@link DeviceInfoActivity} test package. + */ +public final class ExampleObjects { + + // Must match DeviceInfoActivity.MAX_STRING_VALUE_LENGTH and + // DeviceInfoActivity.MAX_ARRAY_LENGTH + private static final int MAX_LENGTH = 1000; + + private static final String TEST_DEVICE_INFO_JSON = "{\n" + + " \"test_boolean\": true,\n" + + " \"test_double\": 1.23456789,\n" + + " \"test_int\": 123456789,\n" + + " \"test_long\": 9223372036854775807,\n" + + " \"test_string\": \"test string\",\n" + + " \"test_strings\": [\n" + + " \"test string 1\",\n" + + " \"test string 2\",\n" + + " \"test string 3\"\n" + + " ],\n" + + " \"test_group\": {\n" + + " \"test_boolean\": false,\n" + + " \"test_double\": 9.87654321,\n" + + " \"test_int\": 987654321,\n" + + " \"test_long\": 9223372036854775807,\n" + + " \"test_string\": \"test group string\",\n" + + " \"test_strings\": [\n" + + " \"test group string 1\",\n" + + " \"test group string 2\",\n" + + " \"test group string 3\"\n" + + " ]\n" + + " },\n" + + " \"test_groups\": [\n" + + " {\n" + + " \"test_string\": \"test groups string 1\",\n" + + " \"test_strings\": [\n" + + " \"test groups string 1-1\",\n" + + " \"test groups string 1-2\",\n" + + " \"test groups string 1-3\"\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"test_string\": \"test groups string 2\",\n" + + " \"test_strings\": [\n" + + " \"test groups string 2-1\",\n" + + " \"test groups string 2-2\",\n" + + " \"test groups string 2-3\"\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"test_string\": \"test groups string 3\",\n" + + " \"test_strings\": [\n" + + " \"test groups string 3-1\",\n" + + " \"test groups string 3-2\",\n" + + " \"test groups string 3-3\"\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"max_length_string\": \"%s\",\n" + + " \"max_num_ints\": [\n%s" + + " ]\n" + + "}\n"; + + public static String testDeviceInfoJson() { + StringBuilder longStringSb = new StringBuilder(); + StringBuilder longArraySb = new StringBuilder(); + int lastNum = MAX_LENGTH - 1; + for (int i = 0; i < MAX_LENGTH; i++) { + longStringSb.append("a"); + longArraySb.append(String.format(" %d%s\n", i, ((i == lastNum)? "" : ","))); + } + return String.format(TEST_DEVICE_INFO_JSON, + longStringSb.toString(), longArraySb.toString()); + } +} \ No newline at end of file
diff --git a/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/SampleDeviceInfo.java b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/SampleDeviceInfo.java new file mode 100644 index 0000000..7da9951 --- /dev/null +++ b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/SampleDeviceInfo.java
@@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.os.Bundle; + +import java.lang.StringBuilder; + +/** + * Sample device info collector. + */ +public class SampleDeviceInfo extends DeviceInfoActivity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + protected void collectDeviceInfo() { + boolean[] booleans = {Boolean.TRUE, Boolean.FALSE}; + double[] doubles = {Double.MAX_VALUE, Double.MIN_VALUE}; + int[] ints = {Integer.MAX_VALUE, Integer.MIN_VALUE}; + long[] longs = {Long.MAX_VALUE, Long.MIN_VALUE}; + + // Group Foo + startGroup("foo"); + addResult("foo_boolean", Boolean.TRUE); + + // Group Bar + startGroup("bar"); + addArray("bar_string", new String[] { + "bar-string-1", + "bar-string-2", + "bar-string-3"}); + + addArray("bar_boolean", booleans); + addArray("bar_double", doubles); + addArray("bar_int", ints); + addArray("bar_long", longs); + endGroup(); // bar + + addResult("foo_double", Double.MAX_VALUE); + addResult("foo_int", Integer.MAX_VALUE); + addResult("foo_long", Long.MAX_VALUE); + addResult("foo_string", "foo-string"); + + StringBuilder sb = new StringBuilder(); + int[] arr = new int[1001]; + for (int i = 0; i < 1001; i++) { + sb.append("a"); + arr[i] = i; + } + addResult("long_string", sb.toString()); + addArray("long_int_array", arr); + + endGroup(); // foo + } +} +
diff --git a/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/TestDeviceInfo.java b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/TestDeviceInfo.java new file mode 100644 index 0000000..7f82942 --- /dev/null +++ b/common/device-side/device-info/tests/src/com/android/compatibility/common/deviceinfo/TestDeviceInfo.java
@@ -0,0 +1,85 @@ +/* + * Copyright (C) 2015 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.compatibility.common.deviceinfo; + +import android.os.Bundle; + +import java.lang.StringBuilder; + +/** + * Collector for testing DeviceInfoActivity + */ +public class TestDeviceInfo extends DeviceInfoActivity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + protected void collectDeviceInfo() { + + // Test primitive results + addResult("test_boolean", true); + addResult("test_double", 1.23456789); + addResult("test_int", 123456789); + addResult("test_long", Long.MAX_VALUE); + addResult("test_string", "test string"); + addArray("test_strings", new String[] { + "test string 1", + "test string 2", + "test string 3", + }); + + // Test group + startGroup("test_group"); + addResult("test_boolean", false); + addResult("test_double", 9.87654321); + addResult("test_int", 987654321); + addResult("test_long", Long.MAX_VALUE); + addResult("test_string", "test group string"); + addArray("test_strings", new String[] { + "test group string 1", + "test group string 2", + "test group string 3" + }); + endGroup(); // test_group + + // Test array of groups + startArray("test_groups"); + for (int i = 1; i < 4; i++) { + startGroup(); + addResult("test_string", "test groups string " + i); + addArray("test_strings", new String[] { + "test groups string " + i + "-1", + "test groups string " + i + "-2", + "test groups string " + i + "-3" + }); + endGroup(); + } + endArray(); // test_groups + + // Test max + StringBuilder sb = new StringBuilder(); + int[] arr = new int[1001]; + for (int i = 0; i < 1001; i++) { + sb.append("a"); + arr[i] = i; + } + addResult("max_length_string", sb.toString()); + addArray("max_num_ints", arr); + } +}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java b/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java new file mode 100644 index 0000000..d01978a --- /dev/null +++ b/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java
@@ -0,0 +1,182 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +import android.content.Context; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.text.TextUtils; +import android.util.Log; + +import java.util.List; + +/** + * A simple activity to create and manage wifi configurations. + */ +public class WifiConfigCreator { + public static final String ACTION_CREATE_WIFI_CONFIG = + "com.android.compatibility.common.util.CREATE_WIFI_CONFIG"; + public static final String ACTION_UPDATE_WIFI_CONFIG = + "com.android.compatibility.common.util.UPDATE_WIFI_CONFIG"; + public static final String ACTION_REMOVE_WIFI_CONFIG = + "com.android.compatibility.common.util.REMOVE_WIFI_CONFIG"; + public static final String EXTRA_NETID = "extra-netid"; + public static final String EXTRA_SSID = "extra-ssid"; + public static final String EXTRA_SECURITY_TYPE = "extra-security-type"; + public static final String EXTRA_PASSWORD = "extra-password"; + + public static final int SECURITY_TYPE_NONE = 1; + public static final int SECURITY_TYPE_WPA = 2; + public static final int SECURITY_TYPE_WEP = 3; + + private static final String TAG = "WifiConfigCreator"; + + private final WifiManager mWifiManager; + + public WifiConfigCreator(Context context) { + mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); + } + + /** + * Adds a new WiFi network. + * @return network id or -1 in case of error + */ + public int addNetwork(String ssid, boolean hidden, int securityType, + String password) throws SecurityException { + if (!mWifiManager.isWifiEnabled()) { + mWifiManager.setWifiEnabled(true); + } + + WifiConfiguration wifiConf = createConfig(ssid, hidden, securityType, password); + + int netId = mWifiManager.addNetwork(wifiConf); + + if (netId != -1) { + mWifiManager.enableNetwork(netId, true); + } else { + Log.w(TAG, "Unable to add SSID '" + ssid + "': netId = " + netId); + } + return netId; + } + + /** + * Updates a new WiFi network. + * @return network id (may differ from original) or -1 in case of error + */ + public int updateNetwork(WifiConfiguration wifiConf, String ssid, boolean hidden, + int securityType, String password) throws SecurityException { + if (!mWifiManager.isWifiEnabled()) { + mWifiManager.setWifiEnabled(true); + } + if (wifiConf == null) { + return -1; + } + + WifiConfiguration conf = createConfig(ssid, hidden, securityType, password); + conf.networkId = wifiConf.networkId; + + int newNetId = mWifiManager.updateNetwork(conf); + + if (newNetId != -1) { + mWifiManager.saveConfiguration(); + mWifiManager.enableNetwork(newNetId, true); + } else { + Log.w(TAG, "Unable to update SSID '" + ssid + "': netId = " + newNetId); + } + return newNetId; + } + + /** + * Updates a new WiFi network. + * @return network id (may differ from original) or -1 in case of error + */ + public int updateNetwork(int netId, String ssid, boolean hidden, + int securityType, String password) throws SecurityException { + if (!mWifiManager.isWifiEnabled()) { + mWifiManager.setWifiEnabled(true); + } + + WifiConfiguration wifiConf = null; + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + for (WifiConfiguration config : configs) { + if (config.networkId == netId) { + wifiConf = config; + break; + } + } + return updateNetwork(wifiConf, ssid, hidden, securityType, password); + } + + public boolean removeNetwork(int netId) { + return mWifiManager.removeNetwork(netId); + } + + /** + * Creates a WifiConfiguration set up according to given parameters + * @param ssid SSID of the network + * @param hidden Is SSID not broadcast? + * @param securityType One of {@link #SECURITY_TYPE_NONE}, {@link #SECURITY_TYPE_WPA} or + * {@link #SECURITY_TYPE_WEP} + * @param password Password for WPA or WEP + * @return Created configuration object + */ + private WifiConfiguration createConfig(String ssid, boolean hidden, int securityType, + String password) { + WifiConfiguration wifiConf = new WifiConfiguration(); + if (!TextUtils.isEmpty(ssid)) { + wifiConf.SSID = '"' + ssid + '"'; + } + wifiConf.status = WifiConfiguration.Status.ENABLED; + wifiConf.hiddenSSID = hidden; + switch (securityType) { + case SECURITY_TYPE_NONE: + wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + break; + case SECURITY_TYPE_WPA: + updateForWPAConfiguration(wifiConf, password); + break; + case SECURITY_TYPE_WEP: + updateForWEPConfiguration(wifiConf, password); + break; + } + return wifiConf; + } + + private void updateForWPAConfiguration(WifiConfiguration wifiConf, String wifiPassword) { + wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); + if (!TextUtils.isEmpty(wifiPassword)) { + wifiConf.preSharedKey = '"' + wifiPassword + '"'; + } + } + + private void updateForWEPConfiguration(WifiConfiguration wifiConf, String password) { + wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + wifiConf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); + wifiConf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); + if (!TextUtils.isEmpty(password)) { + int length = password.length(); + if ((length == 10 || length == 26 + || length == 58) && password.matches("[0-9A-Fa-f]*")) { + wifiConf.wepKeys[0] = password; + } else { + wifiConf.wepKeys[0] = '"' + password + '"'; + } + wifiConf.wepTxKeyIndex = 0; + } + } +} +
diff --git a/common/host-side/manifest-generator/Android.mk b/common/host-side/manifest-generator/Android.mk new file mode 100644 index 0000000..ca08928 --- /dev/null +++ b/common/host-side/manifest-generator/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_STATIC_JAVA_LIBRARIES := kxml2-2.3.0 + +LOCAL_JAR_MANIFEST := MANIFEST.mf + +LOCAL_CLASSPATH := $(HOST_JDK_TOOLS_JAR) + +LOCAL_MODULE := compatibility-manifest-generator + +LOCAL_MODULE_TAGS := optional + +include $(BUILD_HOST_JAVA_LIBRARY) + +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/common/host-side/manifest-generator/MANIFEST.mf b/common/host-side/manifest-generator/MANIFEST.mf new file mode 100644 index 0000000..4f62631 --- /dev/null +++ b/common/host-side/manifest-generator/MANIFEST.mf
@@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: com.android.compatibility.common.generator.ManifestGenerator
diff --git a/common/host-side/manifest-generator/src/com/android/compatibility/common/generator/ManifestGenerator.java b/common/host-side/manifest-generator/src/com/android/compatibility/common/generator/ManifestGenerator.java new file mode 100644 index 0000000..e23e254 --- /dev/null +++ b/common/host-side/manifest-generator/src/com/android/compatibility/common/generator/ManifestGenerator.java
@@ -0,0 +1,126 @@ +/* + * Copyright (C) 2015 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.compatibility.common.generator; + +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import org.kxml2.io.KXmlSerializer; + +public class ManifestGenerator { + + private static final String USAGE = "Usage: " + + "manifest-generator -n NAME -p PACKAGE_NAME -o OUTPUT_FILE -i INSTRUMENT_NAME " + + "[-r PERMISSION]+ [-a ACTIVITY]+"; + private static final String MANIFEST = "manifest"; + private static final String USES_SDK = "uses-sdk"; + private static final String USES_PERMISSION = "uses-permission"; + private static final String APPLICATION = "application"; + private static final String INSTRUMENTATION = "instrumentation"; + private static final String ACTIVITY = "activity"; + + public static void main(String[] args) { + String pkgName = null; + String instrumentName = null; + List<String> permissions = new ArrayList<>(); + List<String> activities = new ArrayList<>(); + String output = null; + + for (int i = 0; i < args.length - 1; i++) { + if (args[i].equals("-p")) { + pkgName = args[++i]; + } else if (args[i].equals("-a")) { + activities.add(args[++i]); + } else if (args[i].equals("-o")) { + output = args[++i]; + } else if (args[i].equals("-i")) { + instrumentName = args[++i]; + } else if (args[i].equals("-r")) { + permissions.add(args[++i]); + } + } + + if (pkgName == null) { + error("Missing package name"); + } else if (instrumentName == null) { + error("Missing instrumentation name"); + } else if (activities.isEmpty()) { + error("No activities"); + } else if (output == null) { + error("Missing output file"); + } + + FileOutputStream out = null; + try { + out = new FileOutputStream(output); + generate(out, pkgName, instrumentName, permissions, activities); + } catch (Exception e) { + System.err.println("Couldn't create manifest file"); + } finally { + if (out != null) { + try { + out.close(); + } catch (Exception e) { + // Ignore + } + } + } + } + + /*package*/ static void generate(OutputStream out, String pkgName, String instrumentName, + List<String> permissions, List<String> activities) throws Exception { + final String ns = null; + KXmlSerializer serializer = new KXmlSerializer(); + serializer.setOutput(out, "UTF-8"); + serializer.startDocument("UTF-8", true); + serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); + serializer.startTag(ns, MANIFEST); + serializer.attribute(ns, "xmlns:android", "http://schemas.android.com/apk/res/android"); + serializer.attribute(ns, "package", pkgName); + serializer.startTag(ns, USES_SDK); + serializer.attribute(ns, "android:minSdkVersion", "8"); + serializer.endTag(ns, USES_SDK); + for (String permission : permissions) { + serializer.startTag(ns, USES_PERMISSION); + serializer.attribute(ns, "android:name", permission); + serializer.endTag(ns, USES_PERMISSION); + } + serializer.startTag(ns, APPLICATION); + for (String activity : activities) { + serializer.startTag(ns, ACTIVITY); + serializer.attribute(ns, "android:name", activity); + serializer.endTag(ns, ACTIVITY); + } + serializer.endTag(ns, APPLICATION); + serializer.startTag(ns, INSTRUMENTATION); + serializer.attribute(ns, "android:name", instrumentName); + serializer.attribute(ns, "android:targetPackage", pkgName); + serializer.endTag(ns, INSTRUMENTATION); + serializer.endTag(ns, MANIFEST); + serializer.endDocument(); + out.flush(); + } + + private static void error(String message) { + System.err.println(message); + System.err.println(USAGE); + System.exit(1); + } + +}
diff --git a/common/host-side/manifest-generator/tests/Android.mk b/common/host-side/manifest-generator/tests/Android.mk new file mode 100644 index 0000000..2eb5d2f --- /dev/null +++ b/common/host-side/manifest-generator/tests/Android.mk
@@ -0,0 +1,27 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := compatibility-manifest-generator junit + +LOCAL_MODULE := compatibility-manifest-generator-tests + +LOCAL_MODULE_TAGS := optional + +include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/common/host-side/manifest-generator/tests/src/com/android/compatibility/common/generator/ManifestGeneratorTest.java b/common/host-side/manifest-generator/tests/src/com/android/compatibility/common/generator/ManifestGeneratorTest.java new file mode 100644 index 0000000..457bbb8 --- /dev/null +++ b/common/host-side/manifest-generator/tests/src/com/android/compatibility/common/generator/ManifestGeneratorTest.java
@@ -0,0 +1,78 @@ +/* + * Copyright (C) 2015 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.compatibility.common.generator; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +/** Unit tests for {@link ManifestGenerator}. */ +public class ManifestGeneratorTest extends TestCase { + + private static final String PACKAGE = "test.package"; + private static final String INSTRUMENT = "test.package.TestInstrument"; + private static final String MANIFEST = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\r\n" + + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" " + + "package=\"test.package\">\r\n" + + " <uses-sdk android:minSdkVersion=\"8\" />\r\n" + + "%s" + + " <application>\r\n" + + "%s" + + " </application>\r\n" + + " <instrumentation android:name=\"test.package.TestInstrument\" " + + "android:targetPackage=\"test.package\" />\r\n" + + "</manifest>"; + private static final String PERMISSION = " <uses-permission android:name=\"%s\" />\r\n"; + private static final String PERMISSION_A = "android.permission.PermissionA"; + private static final String PERMISSION_B = "android.permission.PermissionB"; + private static final String ACTIVITY = " <activity android:name=\"%s\" />\r\n"; + private static final String ACTIVITY_A = "test.package.ActivityA"; + private static final String ACTIVITY_B = "test.package.ActivityB"; + + public void testManifest() throws Exception { + List<String> permissions = new ArrayList<>(); + permissions.add(PERMISSION_A); + permissions.add(PERMISSION_B); + List<String> activities = new ArrayList<>(); + activities.add(ACTIVITY_A); + activities.add(ACTIVITY_B); + OutputStream output = new OutputStream() { + private StringBuilder string = new StringBuilder(); + @Override + public void write(int b) throws IOException { + this.string.append((char) b); + } + + @Override + public String toString(){ + return this.string.toString(); + } + }; + ManifestGenerator.generate(output, PACKAGE, INSTRUMENT, permissions, activities); + String permissionXml = String.format(PERMISSION, PERMISSION_A) + + String.format(PERMISSION, PERMISSION_B); + String activityXml = String.format(ACTIVITY, ACTIVITY_A) + + String.format(ACTIVITY, ACTIVITY_B); + String expected = String.format(MANIFEST, permissionXml, activityXml); + assertEquals("Wrong manifest output", expected, output.toString()); + } + +}
diff --git a/common/host-side/xml-plan-generator/src/com/android/compatibility/common/xmlgenerator/XmlPlanGenerator.java b/common/host-side/xml-plan-generator/src/com/android/compatibility/common/xmlgenerator/XmlPlanGenerator.java index d0a3a37..efb53d5 100644 --- a/common/host-side/xml-plan-generator/src/com/android/compatibility/common/xmlgenerator/XmlPlanGenerator.java +++ b/common/host-side/xml-plan-generator/src/com/android/compatibility/common/xmlgenerator/XmlPlanGenerator.java
@@ -22,9 +22,9 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import vogar.Expectation; import vogar.ExpectationStore; import vogar.ModeId; +import vogar.Result; import java.io.File; import java.io.FileOutputStream; @@ -161,7 +161,7 @@ } public static boolean isKnownFailure(ExpectationStore store, String fullname) { - return store != null && store.get(fullname) != Expectation.SUCCESS; + return store != null && store.get(fullname).getResult() != Result.SUCCESS; } public static void main(String[] args) throws Exception {
diff --git a/common/util/src/com/android/compatibility/common/util/MetricsReportLog.java b/common/util/src/com/android/compatibility/common/util/MetricsReportLog.java new file mode 100644 index 0000000..4675231 --- /dev/null +++ b/common/util/src/com/android/compatibility/common/util/MetricsReportLog.java
@@ -0,0 +1,42 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +/** + * A {@link ReportLog} that can be used with the in memory metrics store used for host side metrics. + */ +public final class MetricsReportLog extends ReportLog { + private final String mDeviceSerial; + private final String mAbi; + private final String mClassMethodName; + + /** + * @param deviceSerial serial number of the device + * @param abi abi the test was run on + * @param classMethodName class name and method name of the test in class#method format. + * Note that ReportLog.getClassMethodNames() provide this. + */ + public MetricsReportLog(String deviceSerial, String abi, String classMethodName) { + mDeviceSerial = deviceSerial; + mAbi = abi; + mClassMethodName = classMethodName; + } + + public void submit() { + MetricsStore.storeResult(mDeviceSerial, mAbi, mClassMethodName, this); + } +}
diff --git a/common/util/src/com/android/compatibility/common/util/MetricsStore.java b/common/util/src/com/android/compatibility/common/util/MetricsStore.java new file mode 100644 index 0000000..9eeb94a --- /dev/null +++ b/common/util/src/com/android/compatibility/common/util/MetricsStore.java
@@ -0,0 +1,59 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * A simple in-memory store for metrics results. This should be used for hostside metrics reporting. + */ +public class MetricsStore { + + // needs concurrent version as there can be multiple client accessing this. + // But there is no additional protection for the same key as that should not happen. + private static final ConcurrentHashMap<String, ReportLog> mMap = + new ConcurrentHashMap<String, ReportLog>(); + + /** + * Stores a result. Existing result with the same key will be replaced. + * Note that key is generated in the form of device_serial#class#method name. + * So there should be no concurrent test for the same (serial, class, method). + * @param deviceSerial + * @param abi + * @param classMethodName + * @param reportLog Contains the result to be stored + */ + public static void storeResult( + String deviceSerial, String abi, String classMethodName, ReportLog reportLog) { + mMap.put(generateTestKey(deviceSerial, abi, classMethodName), reportLog); + } + + /** + * retrieves a metric result for the given condition and remove it from the internal + * storage. If there is no result for the given condition, it will return null. + */ + public static ReportLog removeResult(String deviceSerial, String abi, String classMethodName) { + return mMap.remove(generateTestKey(deviceSerial, abi, classMethodName)); + } + + /** + * @return test key in the form of device_serial#abi#class_name#method_name + */ + private static String generateTestKey(String deviceSerial, String abi, String classMethodName) { + return String.format("%s#%s#%s", deviceSerial, abi, classMethodName); + } +}
diff --git a/common/util/src/com/android/compatibility/common/util/ReportLog.java b/common/util/src/com/android/compatibility/common/util/ReportLog.java index 8cfc086..7209ac8 100644 --- a/common/util/src/com/android/compatibility/common/util/ReportLog.java +++ b/common/util/src/com/android/compatibility/common/util/ReportLog.java
@@ -16,28 +16,37 @@ package com.android.compatibility.common.util; -import org.xmlpull.v1.XmlSerializer; - -import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.StringTokenizer; +import java.util.regex.Pattern; /** * Utility class to add results to the report. */ -public abstract class ReportLog implements Serializable { +public class ReportLog implements Serializable { + private static final String LOG_SEPARATOR = "+++"; + private static final String SUMMARY_SEPARATOR = "++++"; + private static final String LOG_ELEM_SEPARATOR = "|"; + private static final String EMPTY_CHAR = " "; private Result mSummary; private final List<Result> mDetails = new ArrayList<Result>(); - class Result implements Serializable { - private static final int CALLER_STACKTRACE_DEPTH = 5; + static class Result implements Serializable { private String mLocation; private String mMessage; private double[] mValues; private ResultType mType; private ResultUnit mUnit; + private Double mTarget; + + + private Result(String location, String message, double[] values, + ResultType type, ResultUnit unit) { + this(location, message, values, null /*target*/, type, unit); + } /** * Creates a result object to be included in the report. Each object has a message @@ -47,23 +56,22 @@ * * @param message A string describing the values * @param values An array of the values + * @param target Nullable. The target value. * @param type Represents how to interpret the values (eg. A lower score is better) * @param unit Represents the unit in which the values are (eg. Milliseconds) - * @param depth A number used to increase the depth the stack is queried. This should only - * be given in the case that the report is populated by a helper function, in which case it - * would be 1, or else 0. */ - private Result(String message, double[] values, ResultType type, - ResultUnit unit, int depth) { - final StackTraceElement[] trace = Thread.currentThread().getStackTrace(); - final StackTraceElement e = - trace[Math.min(CALLER_STACKTRACE_DEPTH + depth, trace.length - 1)]; - mLocation = String.format( - "%s#%s:%d", e.getClassName(), e.getMethodName(), e.getLineNumber()); + private Result(String location, String message, double[] values, + Double target, ResultType type, ResultUnit unit) { + mLocation = location; mMessage = message; mValues = values; mType = type; mUnit = unit; + mTarget = target; + } + + public double getTarget() { + return mTarget; } public String getLocation() { @@ -85,51 +93,89 @@ public ResultUnit getUnit() { return mUnit; } + + /** + * Format: + * location|message|target|type|unit|value[s], target can be " " if there is no target set. + * log for array = classMethodName:line_number|message|unit|type|space separated values + */ + String toEncodedString() { + StringBuilder builder = new StringBuilder() + .append(mLocation) + .append(LOG_ELEM_SEPARATOR) + .append(mMessage) + .append(LOG_ELEM_SEPARATOR) + .append(mTarget != null ? mTarget : EMPTY_CHAR) + .append(LOG_ELEM_SEPARATOR) + .append(mType.name()) + .append(LOG_ELEM_SEPARATOR) + .append(mUnit.name()) + .append(LOG_ELEM_SEPARATOR); + for (double value : mValues) { + builder.append(value).append(" "); + } + return builder.toString(); + } + + static Result fromEncodedString(String encodedString) { + String[] elems = encodedString.split(Pattern.quote(LOG_ELEM_SEPARATOR)); + if (elems.length < 5) { + return null; + } + + String[] valueStrArray = elems[5].split(" "); + double[] valueArray = new double[valueStrArray.length]; + for (int i = 0; i < valueStrArray.length; i++) { + valueArray[i] = Double.parseDouble(valueStrArray[i]); + } + return new Result( + elems[0], /*location*/ + elems[1], /*message*/ + valueArray, /*values*/ + elems[2].equals(EMPTY_CHAR) ? null : Double.parseDouble(elems[2]), /*target*/ + ResultType.valueOf(elems[3]), /*type*/ + ResultUnit.valueOf(elems[4]) /*unit*/); + } } /** * Adds an array of values to the report. */ public void addValues(String message, double[] values, ResultType type, ResultUnit unit) { - mDetails.add(new Result(message, values, type, unit, 0)); + mDetails.add(new Result(Stacktrace.getTestCallerClassMethodNameLineNumber(), + message, values, type, unit)); } /** * Adds an array of values to the report. */ - public void addValues(String message, double[] values, ResultType type, - ResultUnit unit, int depth) { - mDetails.add(new Result(message, values, type, unit, depth)); + public void addValues( + String message, double[] values, ResultType type, ResultUnit unit, String location) { + mDetails.add(new Result(location, message, values, type, unit)); } /** * Adds a value to the report. */ public void addValue(String message, double value, ResultType type, ResultUnit unit) { - mDetails.add(new Result(message, new double[] {value}, type, unit, 0)); + mDetails.add(new Result(Stacktrace.getTestCallerClassMethodNameLineNumber(), message, + new double[] {value}, type, unit)); } /** * Adds a value to the report. */ public void addValue(String message, double value, ResultType type, - ResultUnit unit, int depth) { - mDetails.add(new Result(message, new double[] {value}, type, unit, depth)); + ResultUnit unit, String location) { + mDetails.add(new Result(location, message, new double[] {value}, type, unit)); } /** * Sets the summary of the report. */ public void setSummary(String message, double value, ResultType type, ResultUnit unit) { - mSummary = new Result(message, new double[] {value}, type, unit, 0); - } - - /** - * Sets the summary of the report. - */ - public void setSummary(String message, double value, ResultType type, - ResultUnit unit, int depth) { - mSummary = new Result(message, new double[] {value}, type, unit, depth); + mSummary = new Result(Stacktrace.getTestCallerClassMethodNameLineNumber(), + message, new double[] {value}, type, unit); } public Result getSummary() { @@ -139,4 +185,46 @@ public List<Result> getDetailedMetrics() { return new ArrayList<Result>(mDetails); } + + /** + * Parse a String encoded {@link com.android.compatibility.common.util.ReportLog} + */ + public static ReportLog fromEncodedString(String encodedString) { + ReportLog reportLog = new ReportLog(); + StringTokenizer tok = new StringTokenizer(encodedString, SUMMARY_SEPARATOR); + if (tok.hasMoreTokens()) { + // Extract the summary + reportLog.mSummary = Result.fromEncodedString(tok.nextToken()); + } + if (tok.hasMoreTokens()) { + // Extract the detailed results + StringTokenizer detailedTok = new StringTokenizer(tok.nextToken(), LOG_SEPARATOR); + while (detailedTok.hasMoreTokens()) { + reportLog.mDetails.add(Result.fromEncodedString(detailedTok.nextToken())); + } + } + return reportLog; + } + + /** + * @return a String representation of this report or null if not collected + */ + protected String toEncodedString() { + if ((mSummary == null) && mDetails.isEmpty()) { + // just return empty string + return null; + } + StringBuilder builder = new StringBuilder(); + builder.append(mSummary.toEncodedString()); + builder.append(SUMMARY_SEPARATOR); + for (Result result : mDetails) { + builder.append(result.toEncodedString()); + builder.append(LOG_SEPARATOR); + } + // delete the last separator + if (builder.length() >= LOG_SEPARATOR.length()) { + builder.delete(builder.length() - LOG_SEPARATOR.length(), builder.length()); + } + return builder.toString(); + } }
diff --git a/common/util/src/com/android/compatibility/common/util/Stacktrace.java b/common/util/src/com/android/compatibility/common/util/Stacktrace.java new file mode 100644 index 0000000..27bf9ca --- /dev/null +++ b/common/util/src/com/android/compatibility/common/util/Stacktrace.java
@@ -0,0 +1,70 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +/** + * Helper methods for dealing with stack traces + */ +public class Stacktrace { + + private static final int SAFETY_DEPTH = 4; + private static final String TEST_POSTFIX = "Test"; + + private Stacktrace() {} + + /** + * @return classname#methodname from call stack of the current thread + */ + public static String getTestCallerClassMethodName() { + return getTestCallerClassMethodName(false /*includeLineNumber*/); + } + + /** + * @return classname#methodname from call stack of the current thread + */ + public static String getTestCallerClassMethodNameLineNumber() { + return getTestCallerClassMethodName(true /*includeLineNumber*/); + } + + /** + * @return classname#methodname from call stack of the current thread + */ + private static String getTestCallerClassMethodName(boolean includeLineNumber) { + StackTraceElement[] elements = Thread.currentThread().getStackTrace(); + // Look for the first class name in the elements array that ends with Test + for (int i = 0; i < elements.length; i++) { + if (elements[i].getClassName().endsWith(TEST_POSTFIX)) { + return buildClassMethodName(elements, i, includeLineNumber); + } + } + + // Use a reasonable default if the test name isn't found + return buildClassMethodName(elements, SAFETY_DEPTH, includeLineNumber); + } + + private static String buildClassMethodName( + StackTraceElement[] elements, int depth, boolean includeLineNumber) { + depth = Math.min(depth, elements.length - 1); + StringBuilder builder = new StringBuilder(); + builder.append(elements[depth].getClassName()).append("#") + .append(elements[depth].getMethodName()); + if (includeLineNumber) { + builder.append(":").append(elements[depth].getLineNumber()); + } + return builder.toString(); + } +}
diff --git a/common/util/tests/src/com/android/compatibility/common/util/MetricsStoreTest.java b/common/util/tests/src/com/android/compatibility/common/util/MetricsStoreTest.java new file mode 100644 index 0000000..944cc43 --- /dev/null +++ b/common/util/tests/src/com/android/compatibility/common/util/MetricsStoreTest.java
@@ -0,0 +1,49 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +import junit.framework.TestCase; + +/** + * Unit tests for {@link MetricsStore} + */ +public class MetricsStoreTest extends TestCase { + + private static final String DEVICE_SERIAL = "DEVICE_SERIAL"; + private static final String ABI = "ABI"; + private static final String CLASSMETHOD_NAME = "CLASSMETHOD_NAME"; + + private static final double[] VALUES = new double[] {1, 11, 21, 1211, 111221}; + + private ReportLog mReportLog; + + @Override + protected void setUp() throws Exception { + this.mReportLog = new ReportLog(); + } + + public void testStoreAndRemove() { + mReportLog.setSummary("Sample Summary", 1.0, ResultType.HIGHER_BETTER, ResultUnit.BYTE); + mReportLog.addValues("Details", VALUES, ResultType.NEUTRAL, ResultUnit.FPS); + MetricsStore.storeResult(DEVICE_SERIAL, ABI, CLASSMETHOD_NAME, mReportLog); + + ReportLog reportLog = MetricsStore.removeResult(DEVICE_SERIAL, ABI, CLASSMETHOD_NAME); + assertSame(mReportLog, reportLog); + assertNull(MetricsStore.removeResult("blah", ABI, CLASSMETHOD_NAME)); + } + +}
diff --git a/common/util/tests/src/com/android/compatibility/common/util/MetricsXmlSerializerTest.java b/common/util/tests/src/com/android/compatibility/common/util/MetricsXmlSerializerTest.java index 70da820..05e69d8 100644 --- a/common/util/tests/src/com/android/compatibility/common/util/MetricsXmlSerializerTest.java +++ b/common/util/tests/src/com/android/compatibility/common/util/MetricsXmlSerializerTest.java
@@ -36,7 +36,8 @@ HEADER + "<Summary message=\"Sample\" scoreType=\"higher_better\" unit=\"byte\">1.0</Summary>" + "<Details>" - + "<ValueArray source=\"sun.reflect.NativeMethodAccessorImpl#invoke0:-2\"" + + "<ValueArray source=\"com.android.compatibility.common.util." + + "MetricsXmlSerializerTest#testSerialize:84\"" + " message=\"Details\" scoreType=\"neutral\" unit=\"fps\">" + "<Value>1.0</Value>" + "<Value>11.0</Value>"
diff --git a/common/util/tests/src/com/android/compatibility/common/util/ReportLogTest.java b/common/util/tests/src/com/android/compatibility/common/util/ReportLogTest.java new file mode 100644 index 0000000..a5f3306 --- /dev/null +++ b/common/util/tests/src/com/android/compatibility/common/util/ReportLogTest.java
@@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 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.compatibility.common.util; + +import junit.framework.TestCase; + +import java.util.Arrays; + +/** + * Unit tests for {@link ReportLog} + */ +public class ReportLogTest extends TestCase { + + private static final double[] VALUES = new double[] {1, 11, 21, 1211, 111221}; + + private static final String EXPECTED_ENCODED_REPORT_LOG = + "com.android.compatibility.common.util.ReportLogTest#testEncodeDecode:44|" + + "Sample Summary| |HIGHER_BETTER|BYTE|1.0 ++++" + + "com.android.compatibility.common.util.ReportLogTest#testEncodeDecode:45|" + + "Details| |NEUTRAL|FPS|1.0 11.0 21.0 1211.0 111221.0 "; + private ReportLog reportLog; + + @Override + protected void setUp() throws Exception { + this.reportLog = new ReportLog(); + } + + public void testEncodeDecode() { + + reportLog.setSummary("Sample Summary", 1.0, ResultType.HIGHER_BETTER, ResultUnit.BYTE); + reportLog.addValues("Details", VALUES, ResultType.NEUTRAL, ResultUnit.FPS); + + String encodedReportLog = reportLog.toEncodedString(); + assertEquals(EXPECTED_ENCODED_REPORT_LOG, encodedReportLog); + + ReportLog decodedReportLog = ReportLog.fromEncodedString(encodedReportLog); + ReportLog.Result summary = reportLog.getSummary(); + assertEquals("Sample Summary", summary.getMessage()); + assertFalse(summary.getLocation().isEmpty()); + assertEquals(ResultType.HIGHER_BETTER, summary.getType()); + assertEquals(ResultUnit.BYTE, summary.getUnit()); + assertTrue(Arrays.equals(new double[] {1.0}, summary.getValues())); + + assertEquals(1, decodedReportLog.getDetailedMetrics().size()); + ReportLog.Result detail = decodedReportLog.getDetailedMetrics().get(0); + assertEquals("Details", detail.getMessage()); + assertFalse(detail.getLocation().isEmpty()); + assertEquals(ResultType.NEUTRAL, detail.getType()); + assertEquals(ResultUnit.FPS, detail.getUnit()); + assertTrue(Arrays.equals(VALUES, detail.getValues())); + + assertEquals(encodedReportLog, decodedReportLog.toEncodedString()); + } +}
diff --git a/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java b/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java index b9a17e1..348c680 100644 --- a/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java +++ b/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java
@@ -26,6 +26,8 @@ public UnitTests() { super(); + addTestSuite(MetricsStoreTest.class); addTestSuite(MetricsXmlSerializerTest.class); + addTestSuite(ReportLogTest.class); } }
diff --git a/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-dsa-a.pk8 b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-dsa-a.pk8 new file mode 100644 index 0000000..ac0b0c1 --- /dev/null +++ b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-dsa-a.pk8 Binary files differ
diff --git a/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.pk8 b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.pk8 new file mode 100644 index 0000000..ec27be1 --- /dev/null +++ b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.pk8 Binary files differ
diff --git a/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.x509.pem b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.x509.pem new file mode 100644 index 0000000..183691d --- /dev/null +++ b/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a.x509.pem
@@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBejCCAR+gAwIBAgIJAMsY4Fz5jr/IMAoGCCqGSM49BAMCMBkxFzAVBgNVBAMM +DnVuaXRfdGVzdF9lY19hMB4XDTE1MDYwMTIxNDU1M1oXDTQyMTAxNzIxNDU1M1ow +GTEXMBUGA1UEAwwOdW5pdF90ZXN0X2VjX2EwWTATBgcqhkjOPQIBBggqhkjOPQMB +BwNCAAR8Q+7lg4KSOs2Be0XhFwlFCsiCCIh3iX2t6fE+V/MD+QBT1265hIyBKEH/ +oAsTpLy8FdGKLC0x+TwuCedui0SBo1AwTjAdBgNVHQ4EFgQUX4h7gPTgwQXorm0H +7R12wN2yNrwwHwYDVR0jBBgwFoAUX4h7gPTgwQXorm0H7R12wN2yNrwwDAYDVR0T +BAUwAwEB/zAKBggqhkjOPQQDAgNJADBGAiEA5kHO4aK20dwt81mCABAywD7Y6V1O +vqoff9yIx3USW8oCIQDTzo8tbHuPc+i3vBsb5Uo1+4BE/pcOe/je6PGlRHG8rg== +-----END CERTIFICATE-----
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java new file mode 100644 index 0000000..2ae2e10 --- /dev/null +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java
@@ -0,0 +1,350 @@ +/* + * Copyright (C) 2015 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.appsecurity; + +import static com.android.cts.appsecurity.SplitTests.ABI_TO_APK; +import static com.android.cts.appsecurity.SplitTests.APK; +import static com.android.cts.appsecurity.SplitTests.APK_mdpi; +import static com.android.cts.appsecurity.SplitTests.APK_xxhdpi; +import static com.android.cts.appsecurity.SplitTests.CLASS; +import static com.android.cts.appsecurity.SplitTests.PKG; + +import com.android.cts.appsecurity.SplitTests.BaseInstallMultiple; +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IAbi; +import com.android.tradefed.testtype.IAbiReceiver; +import com.android.tradefed.testtype.IBuildReceiver; + +import java.util.Arrays; + +/** + * Set of tests that verify behavior of adopted storage media, if supported. + */ +public class AdoptableHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { + private IAbi mAbi; + private CtsBuildHelper mCtsBuild; + + @Override + public void setAbi(IAbi abi) { + mAbi = abi; + } + + @Override + public void setBuild(IBuildInfo buildInfo) { + mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + assertNotNull(mAbi); + assertNotNull(mCtsBuild); + + getDevice().uninstallPackage(PKG); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + + getDevice().uninstallPackage(PKG); + } + + public void testApps() throws Exception { + if (!hasAdoptable()) return; + final String diskId = getAdoptionDisk(); + try { + final String abi = mAbi.getName(); + final String apk = ABI_TO_APK.get(abi); + assertNotNull("Failed to find APK for ABI " + abi, apk); + + // Install simple app on internal + new InstallMultiple().useNaturalAbi().addApk(APK).addApk(apk).run(); + runDeviceTests(PKG, CLASS, "testDataInternal"); + runDeviceTests(PKG, CLASS, "testDataWrite"); + runDeviceTests(PKG, CLASS, "testDataRead"); + runDeviceTests(PKG, CLASS, "testNative"); + + // Adopt that disk! + assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); + final LocalVolumeInfo vol = getAdoptionVolume(); + + // Move app and verify + assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " " + vol.uuid)); + runDeviceTests(PKG, CLASS, "testDataNotInternal"); + runDeviceTests(PKG, CLASS, "testDataRead"); + runDeviceTests(PKG, CLASS, "testNative"); + + // Unmount, remount and verify + getDevice().executeShellCommand("sm unmount " + vol.volId); + getDevice().executeShellCommand("sm mount " + vol.volId); + runDeviceTests(PKG, CLASS, "testDataNotInternal"); + runDeviceTests(PKG, CLASS, "testDataRead"); + runDeviceTests(PKG, CLASS, "testNative"); + + // Move app back and verify + assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal")); + runDeviceTests(PKG, CLASS, "testDataInternal"); + runDeviceTests(PKG, CLASS, "testDataRead"); + runDeviceTests(PKG, CLASS, "testNative"); + + // Un-adopt volume and app should still be fine + getDevice().executeShellCommand("sm partition " + diskId + " public"); + runDeviceTests(PKG, CLASS, "testDataInternal"); + runDeviceTests(PKG, CLASS, "testDataRead"); + runDeviceTests(PKG, CLASS, "testNative"); + + } finally { + cleanUp(diskId); + } + } + + public void testPrimaryStorage() throws Exception { + if (!hasAdoptable()) return; + final String diskId = getAdoptionDisk(); + try { + final String originalVol = getDevice() + .executeShellCommand("sm get-primary-storage-uuid").trim(); + + if ("null".equals(originalVol)) { + verifyPrimaryInternal(diskId); + } else if ("primary_physical".equals(originalVol)) { + verifyPrimaryPhysical(diskId); + } + } finally { + cleanUp(diskId); + } + } + + private void verifyPrimaryInternal(String diskId) throws Exception { + // Write some data to shared storage + new InstallMultiple().addApk(APK).run(); + runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); + runDeviceTests(PKG, CLASS, "testPrimaryInternal"); + runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // Adopt that disk! + assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); + final LocalVolumeInfo vol = getAdoptionVolume(); + + // Move storage there and verify that data went along for ride + assertSuccess(getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid)); + runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // Unmount and verify + getDevice().executeShellCommand("sm unmount " + vol.volId); + runDeviceTests(PKG, CLASS, "testPrimaryUnmounted"); + getDevice().executeShellCommand("sm mount " + vol.volId); + runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // Move app and verify backing storage volume is same + assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " " + vol.uuid)); + runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // And move back to internal + assertSuccess(getDevice().executeShellCommand("pm move-primary-storage internal")); + runDeviceTests(PKG, CLASS, "testPrimaryInternal"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal")); + runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + } + + private void verifyPrimaryPhysical(String diskId) throws Exception { + // Write some data to shared storage + new InstallMultiple().addApk(APK).run(); + runDeviceTests(PKG, CLASS, "testPrimaryPhysical"); + runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // Adopt that disk! + assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); + final LocalVolumeInfo vol = getAdoptionVolume(); + + // Move primary storage there, but since we just nuked primary physical + // the storage device will be empty + assertSuccess(getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid)); + runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); + runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // Unmount and verify + getDevice().executeShellCommand("sm unmount " + vol.volId); + runDeviceTests(PKG, CLASS, "testPrimaryUnmounted"); + getDevice().executeShellCommand("sm mount " + vol.volId); + runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + + // And move to internal + assertSuccess(getDevice().executeShellCommand("pm move-primary-storage internal")); + runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); + runDeviceTests(PKG, CLASS, "testPrimaryInternal"); + runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); + } + + /** + * Verify that we can install both new and inherited packages directly on + * adopted volumes. + */ + public void testPackageInstaller() throws Exception { + if (!hasAdoptable()) return; + final String diskId = getAdoptionDisk(); + try { + assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); + final LocalVolumeInfo vol = getAdoptionVolume(); + + // Install directly onto adopted volume + new InstallMultiple().locationAuto().forceUuid(vol.uuid) + .addApk(APK).addApk(APK_mdpi).run(); + runDeviceTests(PKG, CLASS, "testDataNotInternal"); + runDeviceTests(PKG, CLASS, "testDensityBest1"); + + // Now splice in an additional split which offers better resources + new InstallMultiple().locationAuto().inheritFrom(PKG) + .addApk(APK_xxhdpi).run(); + runDeviceTests(PKG, CLASS, "testDataNotInternal"); + runDeviceTests(PKG, CLASS, "testDensityBest2"); + + } finally { + cleanUp(diskId); + } + } + + /** + * Verify behavior when changes occur while adopted device is ejected and + * returned at a later time. + */ + public void testEjected() throws Exception { + if (!hasAdoptable()) return; + final String diskId = getAdoptionDisk(); + try { + assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); + final LocalVolumeInfo vol = getAdoptionVolume(); + + // Install directly onto adopted volume, and write data there + new InstallMultiple().locationAuto().forceUuid(vol.uuid).addApk(APK).run(); + runDeviceTests(PKG, CLASS, "testDataNotInternal"); + runDeviceTests(PKG, CLASS, "testDataWrite"); + runDeviceTests(PKG, CLASS, "testDataRead"); + + // Now unmount and uninstall; leaving stale package on adopted volume + getDevice().executeShellCommand("sm unmount " + vol.volId); + getDevice().uninstallPackage(PKG); + + // Install second copy on internal, but don't write anything + new InstallMultiple().locationInternalOnly().addApk(APK).run(); + runDeviceTests(PKG, CLASS, "testDataInternal"); + + // Kick through a remount cycle, which should purge the adopted app + getDevice().executeShellCommand("sm mount " + vol.volId); + runDeviceTests(PKG, CLASS, "testDataInternal"); + try { + runDeviceTests(PKG, CLASS, "testDataRead"); + fail("Unexpected data from adopted volume picked up"); + } catch (AssertionError expected) { + } + getDevice().executeShellCommand("sm unmount " + vol.volId); + + // Uninstall the internal copy and remount; we should have no record of app + getDevice().uninstallPackage(PKG); + getDevice().executeShellCommand("sm mount " + vol.volId); + + assertEmpty(getDevice().executeShellCommand("pm list packages " + PKG)); + } finally { + cleanUp(diskId); + } + } + + private boolean hasAdoptable() throws Exception { + return Boolean.parseBoolean(getDevice().executeShellCommand("sm has-adoptable").trim()); + } + + private String getAdoptionDisk() throws Exception { + final String disks = getDevice().executeShellCommand("sm list-disks adoptable"); + if (disks == null || disks.length() == 0) { + throw new AssertionError("Devices that claim to support adoptable storage must have " + + "adoptable media inserted during CTS to verify correct behavior"); + } + return disks.split("\n")[0].trim(); + } + + private LocalVolumeInfo getAdoptionVolume() throws Exception { + String[] lines = null; + int attempt = 0; + while (attempt++ < 15) { + lines = getDevice().executeShellCommand("sm list-volumes private").split("\n"); + for (String line : lines) { + final LocalVolumeInfo info = new LocalVolumeInfo(line.trim()); + if (!"private".equals(info.volId) && "mounted".equals(info.state)) { + return info; + } + } + Thread.sleep(1000); + } + throw new AssertionError("Expected private volume; found " + Arrays.toString(lines)); + } + + private void cleanUp(String diskId) throws Exception { + getDevice().executeShellCommand("sm partition " + diskId + " public"); + getDevice().executeShellCommand("sm forget all"); + } + + private void runDeviceTests(String packageName, String testClassName, String testMethodName) + throws DeviceNotAvailableException { + Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName); + } + + private static void assertSuccess(String str) { + if (str == null || !str.startsWith("Success")) { + throw new AssertionError("Expected success string but found " + str); + } + } + + private static void assertEmpty(String str) { + if (str != null && str.trim().length() > 0) { + throw new AssertionError("Expected empty string but found " + str); + } + } + + private static class LocalVolumeInfo { + public String volId; + public String state; + public String uuid; + + public LocalVolumeInfo(String line) { + final String[] split = line.split(" "); + volId = split[0]; + state = split[1]; + uuid = split[2]; + } + } + + private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> { + public InstallMultiple() { + super(getDevice(), mCtsBuild, mAbi); + } + } +}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java index 4d9ef00..bf9e81c 100644 --- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
@@ -19,16 +19,8 @@ import com.android.cts.tradefed.build.CtsBuildHelper; import com.android.cts.util.AbiUtils; import com.android.ddmlib.Log; -import com.android.ddmlib.testrunner.InstrumentationResultParser; -import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; -import com.android.ddmlib.testrunner.TestIdentifier; -import com.android.ddmlib.testrunner.TestResult; -import com.android.ddmlib.testrunner.TestResult.TestStatus; -import com.android.ddmlib.testrunner.TestRunResult; import com.android.tradefed.build.IBuildInfo; import com.android.tradefed.device.DeviceNotAvailableException; -import com.android.tradefed.device.ITestDevice; -import com.android.tradefed.result.CollectingTestListener; import com.android.tradefed.testtype.DeviceTestCase; import com.android.tradefed.testtype.IAbi; import com.android.tradefed.testtype.IAbiReceiver; @@ -36,15 +28,13 @@ import java.io.File; import java.io.FileNotFoundException; -import java.util.Map; /** - * Set of tests that verify various security checks involving multiple apps are properly enforced. + * Set of tests that verify various security checks involving multiple apps are + * properly enforced. */ public class AppSecurityTests extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { - private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner"; - // testSharedUidDifferentCerts constants private static final String SHARED_UI_APK = "CtsSharedUidInstall.apk"; private static final String SHARED_UI_PKG = "com.android.cts.shareuidinstall"; @@ -69,18 +59,6 @@ private static final String APP_ACCESS_DATA_APK = "CtsAppAccessData.apk"; private static final String APP_ACCESS_DATA_PKG = "com.android.cts.appaccessdata"; - // External storage constants - private static final String COMMON_EXTERNAL_STORAGE_APP_CLASS = "com.android.cts.externalstorageapp.CommonExternalStorageTest"; - private static final String EXTERNAL_STORAGE_APP_APK = "CtsExternalStorageApp.apk"; - private static final String EXTERNAL_STORAGE_APP_PKG = "com.android.cts.externalstorageapp"; - private static final String EXTERNAL_STORAGE_APP_CLASS = EXTERNAL_STORAGE_APP_PKG + ".ExternalStorageTest"; - private static final String READ_EXTERNAL_STORAGE_APP_APK = "CtsReadExternalStorageApp.apk"; - private static final String READ_EXTERNAL_STORAGE_APP_PKG = "com.android.cts.readexternalstorageapp"; - private static final String READ_EXTERNAL_STORAGE_APP_CLASS = READ_EXTERNAL_STORAGE_APP_PKG + ".ReadExternalStorageTest"; - private static final String WRITE_EXTERNAL_STORAGE_APP_APK = "CtsWriteExternalStorageApp.apk"; - private static final String WRITE_EXTERNAL_STORAGE_APP_PKG = "com.android.cts.writeexternalstorageapp"; - private static final String WRITE_EXTERNAL_STORAGE_APP_CLASS = WRITE_EXTERNAL_STORAGE_APP_PKG + ".WriteExternalStorageTest"; - // testInstrumentationDiffCert constants private static final String TARGET_INSTRUMENT_APK = "CtsTargetInstrumentationApp.apk"; private static final String TARGET_INSTRUMENT_PKG = "com.android.cts.targetinstrumentationapp"; @@ -98,13 +76,6 @@ private static final String PERMISSION_DIFF_CERT_PKG = "com.android.cts.usespermissiondiffcertapp"; - private static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; - - private static final String MULTIUSER_STORAGE_APK = "CtsMultiUserStorageApp.apk"; - private static final String MULTIUSER_STORAGE_PKG = "com.android.cts.multiuserstorageapp"; - private static final String MULTIUSER_STORAGE_CLASS = MULTIUSER_STORAGE_PKG - + ".MultiUserStorageTest"; - private static final String LOG_TAG = "AppSecurityTests"; private IAbi mAbi; @@ -155,8 +126,7 @@ assertNotNull("shared uid app with different cert than existing app installed " + "successfully", installResult); assertEquals("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE", installResult); - } - finally { + } finally { getDevice().uninstallPackage(SHARED_UI_PKG); getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG); } @@ -182,8 +152,7 @@ assertNotNull("app upgrade with different cert than existing app installed " + "successfully", installResult); assertEquals("INSTALL_FAILED_UPDATE_INCOMPATIBLE", installResult); - } - finally { + } finally { getDevice().uninstallPackage(SIMPLE_APP_PKG); } } @@ -204,115 +173,21 @@ assertNull(String.format("failed to install app with data. Reason: %s", installResult), installResult); // run appwithdata's tests to create private data - assertTrue("failed to create app's private data", runDeviceTests(APP_WITH_DATA_PKG, - APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD)); + runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD); installResult = getDevice().installPackage(getTestAppFile(APP_ACCESS_DATA_APK), false, options); assertNull(String.format("failed to install app access data. Reason: %s", installResult), installResult); // run appaccessdata's tests which attempt to access appwithdata's private data - assertTrue("could access app's private data", runDeviceTests(APP_ACCESS_DATA_PKG)); - } - finally { + runDeviceTests(APP_ACCESS_DATA_PKG); + } finally { getDevice().uninstallPackage(APP_WITH_DATA_PKG); getDevice().uninstallPackage(APP_ACCESS_DATA_PKG); } } /** - * Verify that app with no external storage permissions works correctly. - */ - public void testExternalStorageNone() throws Exception { - try { - wipePrimaryExternalStorage(getDevice()); - - getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - assertNull(getDevice() - .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options)); - assertTrue("Failed external storage with no permissions", - runDeviceTests(EXTERNAL_STORAGE_APP_PKG)); - } finally { - getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG); - } - } - - /** - * Verify that app with - * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} works - * correctly. - */ - public void testExternalStorageRead() throws Exception { - try { - wipePrimaryExternalStorage(getDevice()); - - getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - assertNull(getDevice() - .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options)); - assertTrue("Failed external storage with read permissions", - runDeviceTests(READ_EXTERNAL_STORAGE_APP_PKG)); - } finally { - getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG); - } - } - - /** - * Verify that app with - * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} works - * correctly. - */ - public void testExternalStorageWrite() throws Exception { - try { - wipePrimaryExternalStorage(getDevice()); - - getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - assertNull(getDevice() - .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options)); - assertTrue("Failed external storage with write permissions", - runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG)); - } finally { - getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG); - } - } - - /** - * Verify that app with WRITE_EXTERNAL can leave gifts in external storage - * directories belonging to other apps, and those apps can read. - */ - public void testExternalStorageGifts() throws Exception { - try { - wipePrimaryExternalStorage(getDevice()); - - getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG); - getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG); - getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - assertNull(getDevice() - .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options)); - assertNull(getDevice() - .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options)); - assertNull(getDevice() - .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options)); - - assertTrue("Failed to write gifts", runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG, - WRITE_EXTERNAL_STORAGE_APP_CLASS, "doWriteGifts")); - - assertTrue("Read failed to verify gifts", runDeviceTests(READ_EXTERNAL_STORAGE_APP_PKG, - READ_EXTERNAL_STORAGE_APP_CLASS, "doVerifyGifts")); - assertTrue("None failed to verify gifts", runDeviceTests(EXTERNAL_STORAGE_APP_PKG, - EXTERNAL_STORAGE_APP_CLASS, "doVerifyGifts")); - - } finally { - getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG); - getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG); - getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG); - } - } - - /** * Test that uninstall of an app removes its private data. */ public void testUninstallRemovesData() throws Exception { @@ -327,8 +202,7 @@ assertNull(String.format("failed to install app with data. Reason: %s", installResult), installResult); // run appwithdata's tests to create private data - assertTrue("failed to create app's private data", runDeviceTests(APP_WITH_DATA_PKG, - APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD)); + runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD); getDevice().uninstallPackage(APP_WITH_DATA_PKG); @@ -337,11 +211,9 @@ assertNull(String.format("failed to install app with data second time. Reason: %s", installResult), installResult); // run appwithdata's 'check if file exists' test - assertTrue("app's private data still exists after install", runDeviceTests( - APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, APP_WITH_DATA_CHECK_NOEXIST_METHOD)); - - } - finally { + runDeviceTests(APP_WITH_DATA_PKG, APP_WITH_DATA_CLASS, + APP_WITH_DATA_CHECK_NOEXIST_METHOD); + } finally { getDevice().uninstallPackage(APP_WITH_DATA_PKG); } } @@ -371,10 +243,8 @@ // run INSTRUMENT_DIFF_CERT_PKG tests // this test will attempt to call startInstrumentation directly and verify // SecurityException is thrown - assertTrue("running instrumentation with diff cert unexpectedly succeeded", - runDeviceTests(INSTRUMENT_DIFF_CERT_PKG)); - } - finally { + runDeviceTests(INSTRUMENT_DIFF_CERT_PKG); + } finally { getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG); getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG); } @@ -409,191 +279,20 @@ assertNull(String.format("failed to install permission app with diff cert. Reason: %s", installResult), installResult); // run PERMISSION_DIFF_CERT_PKG tests which try to access the permission - TestRunResult result = doRunTests(PERMISSION_DIFF_CERT_PKG, null, null); - assertDeviceTestsPass(result); - } - finally { + runDeviceTests(PERMISSION_DIFF_CERT_PKG); + } finally { getDevice().uninstallPackage(DECLARE_PERMISSION_PKG); getDevice().uninstallPackage(DECLARE_PERMISSION_COMPAT_PKG); getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG); } } - /** - * Test multi-user emulated storage environment, ensuring that each user has - * isolated storage. - */ - public void testMultiUserStorage() throws Exception { - final String PACKAGE = MULTIUSER_STORAGE_PKG; - final String CLAZZ = MULTIUSER_STORAGE_CLASS; - - if (!isMultiUserSupportedOnDevice(getDevice())) { - Log.d(LOG_TAG, "Single user device; skipping isolated storage tests"); - return; - } - - int owner = 0; - int secondary = -1; - try { - // Create secondary user - secondary = createUserOnDevice(getDevice()); - - // Install our test app - getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - final String installResult = getDevice() - .installPackage(getTestAppFile(MULTIUSER_STORAGE_APK), false, options); - assertNull("Failed to install: " + installResult, installResult); - - // Clear data from previous tests - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "cleanIsolatedStorage", owner)); - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "cleanIsolatedStorage", secondary)); - - // Have both users try writing into isolated storage - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "writeIsolatedStorage", owner)); - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "writeIsolatedStorage", secondary)); - - // Verify they both have isolated view of storage - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "readIsolatedStorage", owner)); - assertDeviceTestsPass( - doRunTestsAsUser(PACKAGE, CLAZZ, "readIsolatedStorage", secondary)); - } finally { - getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG); - if (secondary != -1) { - removeUserOnDevice(getDevice(), secondary); - } - } + private void runDeviceTests(String packageName) throws DeviceNotAvailableException { + Utils.runDeviceTests(getDevice(), packageName); } - /** - * Helper method that checks that all tests in given result passed, and attempts to generate - * a meaningful error message if they failed. - * - * @param result - */ - private void assertDeviceTestsPass(TestRunResult result) { - // TODO: consider rerunning if this occurred - assertFalse(String.format("Failed to successfully run device tests for %s. Reason: %s", - result.getName(), result.getRunFailureMessage()), result.isRunFailure()); - - if (result.hasFailedTests()) { - // build a meaningful error message - StringBuilder errorBuilder = new StringBuilder("on-device tests failed:\n"); - for (Map.Entry<TestIdentifier, TestResult> resultEntry : - result.getTestResults().entrySet()) { - if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) { - errorBuilder.append(resultEntry.getKey().toString()); - errorBuilder.append(":\n"); - errorBuilder.append(resultEntry.getValue().getStackTrace()); - } - } - fail(errorBuilder.toString()); - } - } - - /** - * Helper method that will the specified packages tests on device. - * - * @param pkgName Android application package for tests - * @return <code>true</code> if all tests passed. - * @throws DeviceNotAvailableException if connection to device was lost. - */ - private boolean runDeviceTests(String pkgName) throws DeviceNotAvailableException { - return runDeviceTests(pkgName, null, null); - } - - /** - * Helper method that will the specified packages tests on device. - * - * @param pkgName Android application package for tests - * @return <code>true</code> if all tests passed. - * @throws DeviceNotAvailableException if connection to device was lost. - */ - private boolean runDeviceTests(String pkgName, String testClassName, String testMethodName) + private void runDeviceTests(String packageName, String testClassName, String testMethodName) throws DeviceNotAvailableException { - TestRunResult runResult = doRunTests(pkgName, testClassName, testMethodName); - return !runResult.hasFailedTests(); - } - - /** - * Helper method to run tests and return the listener that collected the results. - * - * @param pkgName Android application package for tests - * @return the {@link TestRunResult} - * @throws DeviceNotAvailableException if connection to device was lost. - */ - private TestRunResult doRunTests(String pkgName, String testClassName, - String testMethodName) throws DeviceNotAvailableException { - - RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(pkgName, - RUNNER, getDevice().getIDevice()); - if (testClassName != null && testMethodName != null) { - testRunner.setMethodName(testClassName, testMethodName); - } - CollectingTestListener listener = new CollectingTestListener(); - getDevice().runInstrumentationTests(testRunner, listener); - return listener.getCurrentRunResults(); - } - - private static boolean isMultiUserSupportedOnDevice(ITestDevice device) - throws DeviceNotAvailableException { - // TODO: move this to ITestDevice once it supports users - final String output = device.executeShellCommand("pm get-max-users"); - try { - return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()) > 1; - } catch (NumberFormatException e) { - fail("Failed to parse result: " + output); - } - return false; - } - - private static int createUserOnDevice(ITestDevice device) throws DeviceNotAvailableException { - // TODO: move this to ITestDevice once it supports users - final String name = "CTS_" + System.currentTimeMillis(); - final String output = device.executeShellCommand("pm create-user " + name); - if (output.startsWith("Success")) { - try { - return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()); - } catch (NumberFormatException e) { - fail("Failed to parse result: " + output); - } - } else { - fail("Failed to create user: " + output); - } - throw new IllegalStateException(); - } - - private static void removeUserOnDevice(ITestDevice device, int userId) - throws DeviceNotAvailableException { - // TODO: move this to ITestDevice once it supports users - final String output = device.executeShellCommand("pm remove-user " + userId); - if (output.startsWith("Error")) { - fail("Failed to remove user: " + output); - } - } - - private TestRunResult doRunTestsAsUser( - String pkgName, String testClassName, String testMethodName, int userId) - throws DeviceNotAvailableException { - // TODO: move this to RemoteAndroidTestRunner once it supports users - final String cmd = "am instrument --user " + userId + " -w -r -e class " + testClassName - + "#" + testMethodName + " " + pkgName + "/" + RUNNER; - Log.i(LOG_TAG, "Running " + cmd + " on " + getDevice().getSerialNumber()); - - CollectingTestListener listener = new CollectingTestListener(); - InstrumentationResultParser parser = new InstrumentationResultParser(pkgName, listener); - - getDevice().executeShellCommand(cmd, parser); - return listener.getCurrentRunResults(); - } - - private static void wipePrimaryExternalStorage(ITestDevice device) - throws DeviceNotAvailableException { - device.executeShellCommand("rm -rf /sdcard/*"); + Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName); } }
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java index fbde558..a4ec65a 100644 --- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/DocumentsTest.java
@@ -24,6 +24,10 @@ import com.android.tradefed.testtype.IAbiReceiver; import com.android.tradefed.testtype.IBuildReceiver; +/** + * Set of tests that verify behavior of + * {@link android.provider.DocumentsContract} and related intents. + */ public class DocumentsTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { private static final String PROVIDER_PKG = "com.android.cts.documentprovider"; private static final String PROVIDER_APK = "CtsDocumentProvider.apk";
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java new file mode 100644 index 0000000..cb67c63 --- /dev/null +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
@@ -0,0 +1,249 @@ +/* + * Copyright (C) 2015 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.appsecurity; + +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.cts.util.AbiUtils; +import com.android.ddmlib.Log; +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IAbi; +import com.android.tradefed.testtype.IAbiReceiver; +import com.android.tradefed.testtype.IBuildReceiver; + +import java.io.File; +import java.io.FileNotFoundException; + +/** + * Set of tests that verify behavior of external storage devices. + */ +public class ExternalStorageHostTest extends DeviceTestCase + implements IAbiReceiver, IBuildReceiver { + private static final String TAG = "ExternalStorageHostTest"; + + private static final String COMMON_CLASS = + "com.android.cts.externalstorageapp.CommonExternalStorageTest"; + + private static final String NONE_APK = "CtsExternalStorageApp.apk"; + private static final String NONE_PKG = "com.android.cts.externalstorageapp"; + private static final String NONE_CLASS = ".ExternalStorageTest"; + private static final String READ_APK = "CtsReadExternalStorageApp.apk"; + private static final String READ_PKG = "com.android.cts.readexternalstorageapp"; + private static final String READ_CLASS = ".ReadExternalStorageTest"; + private static final String WRITE_APK = "CtsWriteExternalStorageApp.apk"; + private static final String WRITE_PKG = "com.android.cts.writeexternalstorageapp"; + private static final String WRITE_CLASS = ".WriteExternalStorageTest"; + private static final String MULTIUSER_APK = "CtsMultiUserStorageApp.apk"; + private static final String MULTIUSER_PKG = "com.android.cts.multiuserstorageapp"; + private static final String MULTIUSER_CLASS = ".MultiUserStorageTest"; + + private IAbi mAbi; + private CtsBuildHelper mCtsBuild; + + @Override + public void setAbi(IAbi abi) { + mAbi = abi; + } + + @Override + public void setBuild(IBuildInfo buildInfo) { + mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + private File getTestAppFile(String fileName) throws FileNotFoundException { + return mCtsBuild.getTestApp(fileName); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + assertNotNull(mAbi); + assertNotNull(mCtsBuild); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Verify that app with no external storage permissions works correctly. + */ + public void testExternalStorageNone() throws Exception { + final int[] users = createUsersForTest(); + try { + wipePrimaryExternalStorage(); + + getDevice().uninstallPackage(NONE_PKG); + String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + assertNull(getDevice().installPackage(getTestAppFile(NONE_APK), false, options)); + + for (int user : users) { + runDeviceTests(NONE_PKG, COMMON_CLASS, user); + runDeviceTests(NONE_PKG, NONE_CLASS, user); + } + } finally { + getDevice().uninstallPackage(NONE_PKG); + removeUsersForTest(users); + } + } + + /** + * Verify that app with + * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} works + * correctly. + */ + public void testExternalStorageRead() throws Exception { + final int[] users = createUsersForTest(); + try { + wipePrimaryExternalStorage(); + + getDevice().uninstallPackage(READ_PKG); + String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + assertNull(getDevice().installPackage(getTestAppFile(READ_APK), false, options)); + + for (int user : users) { + runDeviceTests(READ_PKG, COMMON_CLASS, user); + runDeviceTests(READ_PKG, READ_CLASS, user); + } + } finally { + getDevice().uninstallPackage(READ_PKG); + removeUsersForTest(users); + } + } + + /** + * Verify that app with + * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} works + * correctly. + */ + public void testExternalStorageWrite() throws Exception { + final int[] users = createUsersForTest(); + try { + wipePrimaryExternalStorage(); + + getDevice().uninstallPackage(WRITE_PKG); + String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + assertNull(getDevice().installPackage(getTestAppFile(WRITE_APK), false, options)); + + for (int user : users) { + runDeviceTests(WRITE_PKG, COMMON_CLASS, user); + runDeviceTests(WRITE_PKG, WRITE_CLASS, user); + } + } finally { + getDevice().uninstallPackage(WRITE_PKG); + removeUsersForTest(users); + } + } + + /** + * Verify that app with WRITE_EXTERNAL can leave gifts in external storage + * directories belonging to other apps, and those apps can read. + */ + public void testExternalStorageGifts() throws Exception { + final int[] users = createUsersForTest(); + try { + wipePrimaryExternalStorage(); + + getDevice().uninstallPackage(NONE_PKG); + getDevice().uninstallPackage(READ_PKG); + getDevice().uninstallPackage(WRITE_PKG); + String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + assertNull(getDevice().installPackage(getTestAppFile(NONE_APK), false, options)); + assertNull(getDevice().installPackage(getTestAppFile(READ_APK), false, options)); + assertNull(getDevice().installPackage(getTestAppFile(WRITE_APK), false, options)); + + for (int user : users) { + runDeviceTests(WRITE_PKG, "WriteGiftTest", user); + runDeviceTests(READ_PKG, "ReadGiftTest", user); + runDeviceTests(NONE_PKG, "GiftTest", user); + } + } finally { + getDevice().uninstallPackage(NONE_PKG); + getDevice().uninstallPackage(READ_PKG); + getDevice().uninstallPackage(WRITE_PKG); + removeUsersForTest(users); + } + } + + /** + * Test multi-user emulated storage environment, ensuring that each user has + * isolated storage. + */ + public void testMultiUserStorageIsolated() throws Exception { + final int[] users = createUsersForTest(); + try { + if (users.length == 1) { + Log.d(TAG, "Single user device; skipping isolated storage tests"); + return; + } + + final int owner = users[0]; + final int secondary = users[1]; + + // Install our test app + getDevice().uninstallPackage(MULTIUSER_PKG); + String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + final String installResult = getDevice() + .installPackage(getTestAppFile(MULTIUSER_APK), false, options); + assertNull("Failed to install: " + installResult, installResult); + + // Clear data from previous tests + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testCleanIsolatedStorage", owner); + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testCleanIsolatedStorage", secondary); + + // Have both users try writing into isolated storage + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testWriteIsolatedStorage", owner); + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testWriteIsolatedStorage", secondary); + + // Verify they both have isolated view of storage + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testReadIsolatedStorage", owner); + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testReadIsolatedStorage", secondary); + + // Verify they can't poke at each other + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testUserIsolation", owner); + runDeviceTests(MULTIUSER_PKG, MULTIUSER_CLASS, "testUserIsolation", secondary); + } finally { + getDevice().uninstallPackage(MULTIUSER_PKG); + removeUsersForTest(users); + } + } + + private void wipePrimaryExternalStorage() throws DeviceNotAvailableException { + getDevice().executeShellCommand("rm -rf /sdcard/*"); + } + + private int[] createUsersForTest() throws DeviceNotAvailableException { + return Utils.createUsersForTest(getDevice()); + } + + private void removeUsersForTest(int[] users) throws DeviceNotAvailableException { + Utils.removeUsersForTest(getDevice(), users); + } + + private void runDeviceTests(String packageName, String testClassName, int userId) + throws DeviceNotAvailableException { + Utils.runDeviceTests(getDevice(), packageName, testClassName, userId); + } + + private void runDeviceTests(String packageName, String testClassName, String testMethodName, + int userId) throws DeviceNotAvailableException { + Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName, userId); + } +}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/KeySetHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/KeySetHostTest.java index dae5ee7..9637a6c 100644 --- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/KeySetHostTest.java +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/KeySetHostTest.java
@@ -66,6 +66,20 @@ "CtsKeySetSigningAAndBUpgradeB.apk"; private static final String A_AND_C_SIGNED_B_UPGRADE = "CtsKeySetSigningAAndCUpgradeB.apk"; + private static final String SHARED_USR_A_SIGNED_B_UPGRADE = + "CtsKeySetSharedUserSigningAUpgradeB.apk"; + private static final String SHARED_USR_B_SIGNED_B_UPGRADE = + "CtsKeySetSharedUserSigningBUpgradeB.apk"; + private static final String A_SIGNED_BAD_B_B_UPGRADE = + "CtsKeySetSigningABadUpgradeB.apk"; + private static final String C_SIGNED_BAD_A_AB_UPGRADE = + "CtsKeySetSigningCBadAUpgradeAB.apk"; + private static final String A_SIGNED_NO_B_B_UPGRADE = + "CtsKeySetSigningANoDefUpgradeB.apk"; + private static final String A_SIGNED_EC_A_UPGRADE = + "CtsKeySetSigningAUpgradeEcA.apk"; + private static final String EC_A_SIGNED_A_UPGRADE = + "CtsKeySetSigningEcAUpgradeA.apk"; /* package which defines the KEYSET_PERM_NAME signature permission */ private static final String KEYSET_PERM_DEF_PKG = @@ -432,4 +446,70 @@ testKeyRotationPerm(PERM_DEF_A_SIGNED, PERM_USE_A_SIGNED, PERM_DEF_B_SIGNED, true, false); } -} \ No newline at end of file + + /* + * Check if an apk which indicates it uses a sharedUserId and defines an + * upgrade keyset is allowed to rotate to that keyset. + */ + public void testUpgradeSharedUser() throws Exception { + String installResult = testPackageUpgrade(KEYSET_PKG, SHARED_USR_A_SIGNED_B_UPGRADE, + SHARED_USR_B_SIGNED_B_UPGRADE); + assertNotNull("upgrade allowed for app with shareduserid!", installResult); + } + + /* + * Check that an apk with an upgrade key represented by a bad public key + * fails to install. + */ + public void testBadUpgradeBadPubKey() throws Exception { + mDevice.uninstallPackage(KEYSET_PKG); + String installResult = mDevice.installPackage(getTestAppFile(A_SIGNED_BAD_B_B_UPGRADE), + false); + assertNotNull("Installation of apk with upgrade key referring to a bad public key succeeded!", + installResult); + } + + /* + * Check that an apk with an upgrade keyset that includes a bad public key fails to install. + */ + public void testBadUpgradeMissingPubKey() throws Exception { + mDevice.uninstallPackage(KEYSET_PKG); + String installResult = mDevice.installPackage(getTestAppFile(C_SIGNED_BAD_A_AB_UPGRADE), + false); + assertNotNull("Installation of apk with upgrade key referring to a bad public key succeeded!", + installResult); + } + + /* + * Check that an apk with an upgrade key that has no corresponding public key fails to install. + */ + public void testBadUpgradeNoPubKey() throws Exception { + mDevice.uninstallPackage(KEYSET_PKG); + String installResult = mDevice.installPackage(getTestAppFile(A_SIGNED_NO_B_B_UPGRADE), + false); + assertNotNull("Installation of apk with upgrade key referring to a bad public key succeeded!", + installResult); + } + + /* + * Check if an apk signed by RSA pub key can upgrade to apk signed by EC key. + */ + public void testUpgradeKSRsaToEC() throws Exception { + String installResult = testPackageUpgrade(KEYSET_PKG, A_SIGNED_EC_A_UPGRADE, + EC_A_SIGNED_A_UPGRADE); + assertNull(String.format("failed to upgrade keyset app from one signed by RSA key" + + "to version signed by EC upgrade-key-set, Reason: %s", installResult), + installResult); + } + + /* + * Check if an apk signed by EC pub key can upgrade to apk signed by RSA key. + */ + public void testUpgradeKSECToRSA() throws Exception { + String installResult = testPackageUpgrade(KEYSET_PKG, EC_A_SIGNED_A_UPGRADE, + A_SIGNED_EC_A_UPGRADE); + assertNull(String.format("failed to upgrade keyset app from one signed by EC key" + + "to version signed by RSA upgrade-key-set, Reason: %s", installResult), + installResult); + } +}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java new file mode 100644 index 0000000..20a92aa --- /dev/null +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/PermissionsHostTest.java
@@ -0,0 +1,150 @@ +/* + * Copyright (C) 2015 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.appsecurity; + +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IAbi; +import com.android.tradefed.testtype.IAbiReceiver; +import com.android.tradefed.testtype.IBuildReceiver; + +/** + * Set of tests that verify behavior of runtime permissions, including both + * dynamic granting and behavior of legacy apps. + */ +public class PermissionsHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { + private static final String PKG = "com.android.cts.usepermission"; + + private static final String APK = "CtsUsePermissionApp.apk"; + private static final String APK_COMPAT = "CtsUsePermissionAppCompat.apk"; + + private IAbi mAbi; + private CtsBuildHelper mCtsBuild; + + @Override + public void setAbi(IAbi abi) { + mAbi = abi; + } + + @Override + public void setBuild(IBuildInfo buildInfo) { + mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + assertNotNull(mAbi); + assertNotNull(mCtsBuild); + + getDevice().uninstallPackage(PKG); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + + getDevice().uninstallPackage(PKG); + } + + public void testFail() throws Exception { + // Sanity check that remote failure is host failure + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + try { + runDeviceTests(PKG, ".UsePermissionTest", "testFail"); + fail("Expected remote failure"); + } catch (AssertionError expected) { + } + } + + public void testKill() throws Exception { + // Sanity check that remote kill is host failure + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + try { + runDeviceTests(PKG, ".UsePermissionTest", "testKill"); + fail("Expected remote failure"); + } catch (AssertionError expected) { + } + } + + public void testDefault() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + runDeviceTests(PKG, ".UsePermissionTest", "testDefault"); + } + + public void testGranted() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + grantPermission(PKG, "android.permission.READ_EXTERNAL_STORAGE"); + grantPermission(PKG, "android.permission.WRITE_EXTERNAL_STORAGE"); + runDeviceTests(PKG, ".UsePermissionTest", "testGranted"); + } + + public void testInteractiveGrant() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + runDeviceTests(PKG, ".UsePermissionTest", "testInteractiveGrant"); + } + + public void testRuntimeGroupGrantSpecificity() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + runDeviceTests(PKG, ".UsePermissionTest", "testRuntimeGroupGrantSpecificity"); + } + + public void testRuntimeGroupGrantExpansion() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK), false, false)); + runDeviceTests(PKG, ".UsePermissionTest", "testRuntimeGroupGrantExpansion"); + } + + public void testCompatDefault() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK_COMPAT), false, false)); + runDeviceTests(PKG, ".UsePermissionCompatTest", "testCompatDefault"); + } + + public void testCompatRevoked() throws Exception { + assertNull(getDevice().installPackage(mCtsBuild.getTestApp(APK_COMPAT), false, false)); + setAppOps(PKG, "android:read_external_storage", "deny"); + setAppOps(PKG, "android:write_external_storage", "deny"); + runDeviceTests(PKG, ".UsePermissionCompatTest", "testCompatRevoked"); + } + + private void runDeviceTests(String packageName, String testClassName, String testMethodName) + throws DeviceNotAvailableException { + Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName); + } + + private void grantPermission(String pkg, String permission) throws Exception { + assertEmpty(getDevice().executeShellCommand("pm grant " + pkg + " " + permission)); + } + + private void revokePermission(String pkg, String permission) throws Exception { + assertEmpty(getDevice().executeShellCommand("pm revoke " + pkg + " " + permission)); + } + + private void setAppOps(String pkg, String op, String mode) throws Exception { + assertEmpty(getDevice().executeShellCommand("appops set " + pkg + " " + op + " " + mode)); + } + + private static void assertEmpty(String str) { + if (str == null || str.length() == 0) { + return; + } else { + fail("Expected empty string but found " + str); + } + } +}
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/SplitTests.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/SplitTests.java index 90cbed9..ef3af8d 100644 --- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/SplitTests.java +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/SplitTests.java
@@ -36,14 +36,15 @@ * Tests that verify installing of various split APKs from host side. */ public class SplitTests extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { - private static final String PKG = "com.android.cts.splitapp"; + static final String PKG = "com.android.cts.splitapp"; + static final String CLASS = ".SplitAppTest"; - private static final String APK = "CtsSplitApp.apk"; + static final String APK = "CtsSplitApp.apk"; - private static final String APK_mdpi = "CtsSplitApp_mdpi-v4.apk"; - private static final String APK_hdpi = "CtsSplitApp_hdpi-v4.apk"; - private static final String APK_xhdpi = "CtsSplitApp_xhdpi-v4.apk"; - private static final String APK_xxhdpi = "CtsSplitApp_xxhdpi-v4.apk"; + static final String APK_mdpi = "CtsSplitApp_mdpi-v4.apk"; + static final String APK_hdpi = "CtsSplitApp_hdpi-v4.apk"; + static final String APK_xhdpi = "CtsSplitApp_xhdpi-v4.apk"; + static final String APK_xxhdpi = "CtsSplitApp_xxhdpi-v4.apk"; private static final String APK_v7 = "CtsSplitApp_v7.apk"; private static final String APK_fr = "CtsSplitApp_fr.apk"; @@ -69,7 +70,7 @@ private static final String APK_FEATURE = "CtsSplitAppFeature.apk"; private static final String APK_FEATURE_v7 = "CtsSplitAppFeature_v7.apk"; - private static final HashMap<String, String> ABI_TO_APK = new HashMap<>(); + static final HashMap<String, String> ABI_TO_APK = new HashMap<>(); static { ABI_TO_APK.put("x86", APK_x86); @@ -113,18 +114,18 @@ public void testSingleBase() throws Exception { new InstallMultiple().addApk(APK).run(); - runDeviceTests(PKG, ".SplitAppTest", "testSingleBase"); + runDeviceTests(PKG, CLASS, "testSingleBase"); } public void testDensitySingle() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_mdpi).run(); - runDeviceTests(PKG, ".SplitAppTest", "testDensitySingle"); + runDeviceTests(PKG, CLASS, "testDensitySingle"); } public void testDensityAll() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_mdpi).addApk(APK_hdpi).addApk(APK_xhdpi) .addApk(APK_xxhdpi).run(); - runDeviceTests(PKG, ".SplitAppTest", "testDensityAll"); + runDeviceTests(PKG, CLASS, "testDensityAll"); } /** @@ -133,11 +134,11 @@ */ public void testDensityBest() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_mdpi).run(); - runDeviceTests(PKG, ".SplitAppTest", "testDensityBest1"); + runDeviceTests(PKG, CLASS, "testDensityBest1"); // Now splice in an additional split which offers better resources new InstallMultiple().inheritFrom(PKG).addApk(APK_xxhdpi).run(); - runDeviceTests(PKG, ".SplitAppTest", "testDensityBest2"); + runDeviceTests(PKG, CLASS, "testDensityBest2"); } /** @@ -146,12 +147,12 @@ */ public void testApi() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testApi"); + runDeviceTests(PKG, CLASS, "testApi"); } public void testLocale() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_de).addApk(APK_fr).run(); - runDeviceTests(PKG, ".SplitAppTest", "testLocale"); + runDeviceTests(PKG, CLASS, "testLocale"); } /** @@ -164,7 +165,7 @@ assertNotNull("Failed to find APK for ABI " + abi, apk); new InstallMultiple().addApk(APK).addApk(apk).run(); - runDeviceTests(PKG, ".SplitAppTest", "testNative"); + runDeviceTests(PKG, CLASS, "testNative"); } /** @@ -179,7 +180,7 @@ assertNotNull("Failed to find APK for ABI " + abi, apk); new InstallMultiple().useNaturalAbi().addApk(APK).addApk(apk).run(); - runDeviceTests(PKG, ".SplitAppTest", "testNative"); + runDeviceTests(PKG, CLASS, "testNative"); } /** @@ -192,7 +193,7 @@ inst.addApk(apk); } inst.run(); - runDeviceTests(PKG, ".SplitAppTest", "testNative"); + runDeviceTests(PKG, CLASS, "testNative"); } /** @@ -207,7 +208,7 @@ inst.addApk(apk); } inst.run(); - runDeviceTests(PKG, ".SplitAppTest", "testNative"); + runDeviceTests(PKG, CLASS, "testNative"); } public void testDuplicateBase() throws Exception { @@ -238,21 +239,21 @@ public void testDiffRevision() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_DIFF_REVISION_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testRevision0_12"); + runDeviceTests(PKG, CLASS, "testRevision0_12"); } public void testDiffRevisionInheritBase() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testRevision0_0"); + runDeviceTests(PKG, CLASS, "testRevision0_0"); new InstallMultiple().inheritFrom(PKG).addApk(APK_DIFF_REVISION_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testRevision0_12"); + runDeviceTests(PKG, CLASS, "testRevision0_12"); } public void testDiffRevisionInheritSplit() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testRevision0_0"); + runDeviceTests(PKG, CLASS, "testRevision0_0"); new InstallMultiple().inheritFrom(PKG).addApk(APK_DIFF_REVISION).run(); - runDeviceTests(PKG, ".SplitAppTest", "testRevision12_0"); + runDeviceTests(PKG, CLASS, "testRevision12_0"); } public void testDiffRevisionDowngrade() throws Exception { @@ -262,12 +263,12 @@ public void testFeatureBase() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_FEATURE).run(); - runDeviceTests(PKG, ".SplitAppTest", "testFeatureBase"); + runDeviceTests(PKG, CLASS, "testFeatureBase"); } public void testFeatureApi() throws Exception { new InstallMultiple().addApk(APK).addApk(APK_FEATURE).addApk(APK_FEATURE_v7).run(); - runDeviceTests(PKG, ".SplitAppTest", "testFeatureApi"); + runDeviceTests(PKG, CLASS, "testFeatureApi"); } public void testInheritUpdatedBase() throws Exception { @@ -283,35 +284,72 @@ */ public void testClearCodeCache() throws Exception { new InstallMultiple().addApk(APK).run(); - runDeviceTests(PKG, ".SplitAppTest", "testCodeCacheWrite"); + runDeviceTests(PKG, CLASS, "testCodeCacheWrite"); new InstallMultiple().addArg("-r").addApk(APK_DIFF_VERSION).run(); - runDeviceTests(PKG, ".SplitAppTest", "testCodeCacheRead"); + runDeviceTests(PKG, CLASS, "testCodeCacheRead"); } - class InstallMultiple { - private List<String> mArgs = new ArrayList<>(); - private List<File> mApks = new ArrayList<>(); + private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> { + public InstallMultiple() { + super(getDevice(), mCtsBuild, mAbi); + } + } + + public static class BaseInstallMultiple<T extends BaseInstallMultiple<?>> { + private final ITestDevice mDevice; + private final CtsBuildHelper mBuild; + private final IAbi mAbi; + + private final List<String> mArgs = new ArrayList<>(); + private final List<File> mApks = new ArrayList<>(); private boolean mUseNaturalAbi; - InstallMultiple addArg(String arg) { + public BaseInstallMultiple(ITestDevice device, CtsBuildHelper build, IAbi abi) { + mDevice = device; + mBuild = build; + mAbi = abi; + addArg("-g"); + } + + T addArg(String arg) { mArgs.add(arg); - return this; + return (T) this; } - InstallMultiple addApk(String apk) throws FileNotFoundException { - mApks.add(mCtsBuild.getTestApp(apk)); - return this; + T addApk(String apk) throws FileNotFoundException { + mApks.add(mBuild.getTestApp(apk)); + return (T) this; } - InstallMultiple inheritFrom(String packageName) { + T inheritFrom(String packageName) { addArg("-r"); addArg("-p " + packageName); - return this; + return (T) this; } - InstallMultiple useNaturalAbi() { + T useNaturalAbi() { mUseNaturalAbi = true; - return this; + return (T) this; + } + + T locationAuto() { + addArg("--install-location 0"); + return (T) this; + } + + T locationInternalOnly() { + addArg("--install-location 1"); + return (T) this; + } + + T locationPreferExternal() { + addArg("--install-location 2"); + return (T) this; + } + + T forceUuid(String uuid) { + addArg("--force-uuid " + uuid); + return (T) this; } void run() throws DeviceNotAvailableException { @@ -323,7 +361,7 @@ } private void run(boolean expectingSuccess) throws DeviceNotAvailableException { - final ITestDevice device = getDevice(); + final ITestDevice device = mDevice; // Create an install session final StringBuilder cmd = new StringBuilder();
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java index c58d6bf..fdf84d3 100644 --- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java +++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/Utils.java
@@ -16,6 +16,7 @@ package com.android.cts.appsecurity; +import com.android.ddmlib.Log; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; import com.android.ddmlib.testrunner.TestIdentifier; import com.android.ddmlib.testrunner.TestResult; @@ -28,13 +29,37 @@ import java.util.Map; public class Utils { + private static final String TAG = "AppSecurity"; + + public static final int USER_OWNER = 0; + public static void runDeviceTests(ITestDevice device, String packageName) throws DeviceNotAvailableException { - runDeviceTests(device, packageName, null, null); + runDeviceTests(device, packageName, null, null, USER_OWNER); + } + + public static void runDeviceTests(ITestDevice device, String packageName, int userId) + throws DeviceNotAvailableException { + runDeviceTests(device, packageName, null, null, userId); + } + + public static void runDeviceTests(ITestDevice device, String packageName, String testClassName) + throws DeviceNotAvailableException { + runDeviceTests(device, packageName, testClassName, null, USER_OWNER); + } + + public static void runDeviceTests(ITestDevice device, String packageName, String testClassName, + int userId) throws DeviceNotAvailableException { + runDeviceTests(device, packageName, testClassName, null, userId); } public static void runDeviceTests(ITestDevice device, String packageName, String testClassName, String testMethodName) throws DeviceNotAvailableException { + runDeviceTests(device, packageName, testClassName, testMethodName, USER_OWNER); + } + + public static void runDeviceTests(ITestDevice device, String packageName, String testClassName, + String testMethodName, int userId) throws DeviceNotAvailableException { if (testClassName != null && testClassName.startsWith(".")) { testClassName = packageName + testClassName; } @@ -43,6 +68,13 @@ "android.support.test.runner.AndroidJUnitRunner", device.getIDevice()); if (testClassName != null && testMethodName != null) { testRunner.setMethodName(testClassName, testMethodName); + } else if (testClassName != null) { + testRunner.setClassName(testClassName); + } + + if (userId != USER_OWNER) { + // TODO: move this to RemoteAndroidTestRunner once it supports users + testRunner.addInstrumentationArg("hack_key", "hack_value --user " + userId); } final CollectingTestListener listener = new CollectingTestListener(); @@ -68,4 +100,66 @@ throw new AssertionError(errorBuilder.toString()); } } + + private static boolean isMultiUserSupportedOnDevice(ITestDevice device) + throws DeviceNotAvailableException { + // TODO: move this to ITestDevice once it supports users + final String output = device.executeShellCommand("pm get-max-users"); + try { + return Integer.parseInt(output.substring(output.lastIndexOf(" ")).trim()) > 1; + } catch (NumberFormatException e) { + throw new AssertionError("Failed to parse result: " + output); + } + } + + /** + * Return set of users that test should be run for, creating a secondary + * user if the device supports it. Always call + * {@link #removeUsersForTest(ITestDevice, int[])} when finished. + */ + public static int[] createUsersForTest(ITestDevice device) throws DeviceNotAvailableException { + if (isMultiUserSupportedOnDevice(device)) { + return new int[] { USER_OWNER, createUserOnDevice(device) }; + } else { + Log.d(TAG, "Single user device; skipping isolated storage tests"); + return new int[] { USER_OWNER }; + } + } + + public static void removeUsersForTest(ITestDevice device, int[] users) + throws DeviceNotAvailableException { + for (int user : users) { + if (user != USER_OWNER) { + removeUserOnDevice(device, user); + } + } + } + + private static int createUserOnDevice(ITestDevice device) throws DeviceNotAvailableException { + // TODO: move this to ITestDevice once it supports users + final String name = "CTS_" + System.currentTimeMillis(); + final String output = device.executeShellCommand("pm create-user " + name); + if (output.startsWith("Success")) { + try { + final int userId = Integer.parseInt( + output.substring(output.lastIndexOf(" ")).trim()); + device.executeShellCommand("am start-user " + userId); + return userId; + } catch (NumberFormatException e) { + throw new AssertionError("Failed to parse result: " + output); + } + } else { + throw new AssertionError("Failed to create user: " + output); + } + } + + private static void removeUserOnDevice(ITestDevice device, int userId) + throws DeviceNotAvailableException { + // TODO: move this to ITestDevice once it supports users + final String output = device.executeShellCommand("pm remove-user " + userId); + if (output.startsWith("Error")) { + throw new AssertionError("Failed to remove user: " + output); + } + } + }
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk index 2c9c624..4459e69 100644 --- a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk +++ b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk b/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk index 098ce9c..0916254 100644 --- a/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk +++ b/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk
@@ -29,4 +29,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk index 910e3cd..272ef28 100644 --- a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk +++ b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk
@@ -31,4 +31,4 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk index a886fb2..bbf7734 100644 --- a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk +++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk
@@ -31,4 +31,4 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/src/com/android/cts/documentprovider/MyDocumentsProvider.java b/hostsidetests/appsecurity/test-apps/DocumentProvider/src/com/android/cts/documentprovider/MyDocumentsProvider.java index fb8993c..14f215c 100644 --- a/hostsidetests/appsecurity/test-apps/DocumentProvider/src/com/android/cts/documentprovider/MyDocumentsProvider.java +++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/src/com/android/cts/documentprovider/MyDocumentsProvider.java
@@ -239,13 +239,16 @@ new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { - try { - final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream( - pipe[0]); - doc.contents = readFullyNoClose(is); - is.close(); - } catch (IOException e) { - Log.w(TAG, "Failed to stream", e); + synchronized (doc) { + try { + final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream( + pipe[0]); + doc.contents = readFullyNoClose(is); + is.close(); + doc.notifyAll(); + } catch (IOException e) { + Log.w(TAG, "Failed to stream", e); + } } return null; } @@ -255,13 +258,20 @@ new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { - try { - final OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream( - pipe[1]); - os.write(doc.contents); - os.close(); - } catch (IOException e) { - Log.w(TAG, "Failed to stream", e); + synchronized (doc) { + try { + final OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream( + pipe[1]); + while (doc.contents == null) { + doc.wait(); + } + os.write(doc.contents); + os.close(); + } catch (IOException e) { + Log.w(TAG, "Failed to stream", e); + } catch (InterruptedException e) { + Log.w(TAG, "Interuppted", e); + } } return null; }
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk index afc8764..a7de92a 100644 --- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk
@@ -25,4 +25,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml index 9d8f615..98fe92a 100644 --- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml +++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/AndroidManifest.xml
@@ -23,4 +23,6 @@ <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="com.android.cts.externalstorageapp" /> + <uses-permission android:name="android.permission.INTERNET" /> + </manifest>
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java index 5b4d9f7..7fe0b80 100644 --- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java +++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
@@ -16,18 +16,29 @@ package com.android.cts.externalstorageapp; +import android.content.ContentResolver; +import android.content.ContentValues; import android.content.Context; +import android.net.Uri; import android.os.Environment; +import android.provider.MediaStore; +import android.provider.MediaStore.Images; import android.test.AndroidTestCase; import android.util.Log; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -43,6 +54,14 @@ public static final String PACKAGE_WRITE = "com.android.cts.writeexternalstorageapp"; /** + * Dump helpful debugging details. + */ + public void testDumpDebug() throws Exception { + logCommand("/system/bin/id"); + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + } + + /** * Primary storage must always be mounted. */ public void testExternalStorageMounted() { @@ -88,7 +107,7 @@ for (File path : paths) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); assertDirReadWriteAccess(path); @@ -149,6 +168,21 @@ return paths; } + public static List<File> getMountPaths() throws IOException { + final List<File> paths = new ArrayList<>(); + final BufferedReader br = new BufferedReader(new FileReader("/proc/self/mounts")); + try { + String line; + while ((line = br.readLine()) != null) { + final String[] fields = line.split(" "); + paths.add(new File(fields[1])); + } + } finally { + br.close(); + } + return paths; + } + private static File[] dropFirst(File[] before) { final File[] after = new File[before.length - 1]; System.arraycopy(before, 1, after, 0, after.length); @@ -274,6 +308,35 @@ } } + public static void assertMediaNoAccess(ContentResolver resolver) throws Exception { + final ContentValues values = new ContentValues(); + values.put(Images.Media.MIME_TYPE, "image/jpeg"); + values.put(Images.Media.DATA, + buildProbeFile(Environment.getExternalStorageDirectory()).getAbsolutePath()); + + try { + resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); + fail("Expected access to be blocked"); + } catch (Exception expected) { + } + } + + public static void assertMediaReadWriteAccess(ContentResolver resolver) throws Exception { + final ContentValues values = new ContentValues(); + values.put(Images.Media.MIME_TYPE, "image/jpeg"); + values.put(Images.Media.DATA, + buildProbeFile(Environment.getExternalStorageDirectory()).getAbsolutePath()); + + final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); + try { + resolver.openFileDescriptor(uri, "rw").close(); + resolver.openFileDescriptor(uri, "w").close(); + resolver.openFileDescriptor(uri, "r").close(); + } finally { + resolver.delete(uri, null, null); + } + } + private static boolean isWhiteList(File file) { final String[] whiteLists = { "autorun.inf", ".android_secure", "android_secure" @@ -315,7 +378,9 @@ } File[] dirs = removeWhiteList(dir.listFiles()); - assertEquals(0, dirs.length); + if (dirs.length != 0) { + fail("Expected wiped storage but found: " + Arrays.toString(dirs)); + } } } @@ -336,4 +401,27 @@ is.close(); } } + + public static void logCommand(String... cmd) throws Exception { + final Process proc = new ProcessBuilder(cmd).redirectErrorStream(true).start(); + + final ByteArrayOutputStream buf = new ByteArrayOutputStream(); + copy(proc.getInputStream(), buf); + final int res = proc.waitFor(); + + Log.d(TAG, Arrays.toString(cmd) + " result " + res + ":"); + Log.d(TAG, buf.toString()); + } + + /** Shamelessly lifted from libcore.io.Streams */ + public static int copy(InputStream in, OutputStream out) throws IOException { + int total = 0; + byte[] buffer = new byte[8192]; + int c; + while ((c = in.read(buffer)) != -1) { + total += c; + out.write(buffer, 0, c); + } + return total; + } }
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java index 425815f..6030f1c 100644 --- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java +++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/ExternalStorageTest.java
@@ -16,21 +16,31 @@ package com.android.cts.externalstorageapp; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoWriteAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileNoAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getMountPaths; +import android.app.DownloadManager; +import android.app.DownloadManager.Query; +import android.app.DownloadManager.Request; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.database.Cursor; +import android.net.Uri; import android.os.Environment; +import android.os.SystemClock; import android.test.AndroidTestCase; +import android.text.format.DateUtils; +import java.io.BufferedReader; import java.io.File; +import java.io.FileReader; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; /** @@ -62,7 +72,7 @@ } // Keep walking up until we leave device - while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) { + while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) { assertDirNoAccess(path); path = path.getParentFile(); } @@ -70,17 +80,123 @@ } /** - * Verify we can read only our gifts. + * Verify that we don't have read access to any storage mountpoints. */ - public void doVerifyGifts() throws Exception { - final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); - assertFileReadWriteAccess(none); - assertEquals(100, readInt(none)); + public void testMountPointsNotReadable() throws Exception { + final String userId = Integer.toString(android.os.Process.myUid() / 100000); + final List<File> mountPaths = getMountPaths(); + for (File path : mountPaths) { + if (path.getAbsolutePath().startsWith("/mnt/") + || path.getAbsolutePath().startsWith("/storage/")) { + // Mount points could be multi-user aware, so try probing both + // top level and user-specific directory. + final File userPath = new File(path, userId); - final File read = buildGiftForPackage(getContext(), PACKAGE_READ); - assertFileNoAccess(read); + assertDirNoAccess(path); + assertDirNoAccess(userPath); + } + } + } - final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); - assertFileNoAccess(write); + /** + * Verify that we can't download things outside package directory. + */ + public void testDownloadManager() throws Exception { + final DownloadManager dm = getContext().getSystemService(DownloadManager.class); + try { + final Uri source = Uri.parse("http://www.example.com"); + final File target = new File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "meow"); + dm.enqueue(new Request(source).setDestinationUri(Uri.fromFile(target))); + fail("Unexpected success writing outside package directory"); + } catch (SecurityException expected) { + } + } + + /** + * Verify that we can download things into our package directory. + */ + public void testDownloadManagerPackage() throws Exception { + final DownloadManager dm = getContext().getSystemService(DownloadManager.class); + final DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); + try { + IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); + mContext.registerReceiver(receiver, intentFilter); + + final Uri source = Uri.parse("http://www.example.com"); + final File target = new File( + getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "meow"); + + final long id = dm.enqueue(new Request(source).setDestinationUri(Uri.fromFile(target))); + receiver.waitForDownloadComplete(30 * DateUtils.SECOND_IN_MILLIS, id); + assertSuccessfulDownload(id, target); + } finally { + mContext.unregisterReceiver(receiver); + } + } + + /** + * Shamelessly borrowed from DownloadManagerTest.java + */ + private static class DownloadCompleteReceiver extends BroadcastReceiver { + private HashSet<Long> mCompleteIds = new HashSet<>(); + + public DownloadCompleteReceiver() { + } + + @Override + public void onReceive(Context context, Intent intent) { + synchronized (mCompleteIds) { + mCompleteIds.add(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)); + mCompleteIds.notifyAll(); + } + } + + private boolean isCompleteLocked(long... ids) { + for (long id : ids) { + if (!mCompleteIds.contains(id)) { + return false; + } + } + return true; + } + + public void waitForDownloadComplete(long timeoutMillis, long... waitForIds) + throws InterruptedException { + if (waitForIds.length == 0) { + throw new IllegalArgumentException("Missing IDs to wait for"); + } + + final long startTime = SystemClock.elapsedRealtime(); + do { + synchronized (mCompleteIds) { + mCompleteIds.wait(timeoutMillis); + if (isCompleteLocked(waitForIds)) return; + } + } while ((SystemClock.elapsedRealtime() - startTime) < timeoutMillis); + + throw new InterruptedException("Timeout waiting for IDs " + Arrays.toString(waitForIds) + + "; received " + mCompleteIds.toString() + + ". Make sure you have WiFi or some other connectivity for this test."); + } + } + + private void assertSuccessfulDownload(long id, File location) { + final DownloadManager dm = getContext().getSystemService(DownloadManager.class); + + Cursor cursor = null; + try { + cursor = dm.query(new Query().setFilterById(id)); + assertTrue(cursor.moveToNext()); + assertEquals(DownloadManager.STATUS_SUCCESSFUL, cursor.getInt( + cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))); + assertEquals(Uri.fromFile(location).toString(), + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))); + assertTrue(location.exists()); + } finally { + if (cursor != null) { + cursor.close(); + } + } } }
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java new file mode 100644 index 0000000..e482b2f --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/src/com/android/cts/externalstorageapp/GiftTest.java
@@ -0,0 +1,46 @@ +/* + * Copyright (C) 2015 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.externalstorageapp; + +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; + +import android.test.AndroidTestCase; + +import java.io.File; + +public class GiftTest extends AndroidTestCase { + /** + * Verify we can read only our gifts. + */ + public void testGifts() throws Exception { + final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); + assertFileReadWriteAccess(none); + assertEquals(100, readInt(none)); + + final File read = buildGiftForPackage(getContext(), PACKAGE_READ); + assertFileNoAccess(read); + + final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); + assertFileNoAccess(write); + } +}
diff --git a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk index e8ce3b8..4c64204 100644 --- a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk +++ b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk index 1dd109a..c37d052 100644 --- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
@@ -27,4 +27,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java index 2a80c75..d9f00d2 100644 --- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java +++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
@@ -16,6 +16,7 @@ package com.android.cts.multiuserstorageapp; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPathsExceptObb; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.writeInt; @@ -45,7 +46,9 @@ private void wipeTestFiles(File dir) { dir.mkdirs(); - for (File file : dir.listFiles()) { + final File[] files = dir.listFiles(); + if (files == null) return; + for (File file : files) { if (file.getName().startsWith(FILE_PREFIX)) { Log.d(TAG, "Wiping " + file); file.delete(); @@ -53,11 +56,11 @@ } } - public void cleanIsolatedStorage() throws Exception { + public void testCleanIsolatedStorage() throws Exception { wipeTestFiles(Environment.getExternalStorageDirectory()); } - public void writeIsolatedStorage() throws Exception { + public void testWriteIsolatedStorage() throws Exception { final int uid = android.os.Process.myUid(); writeInt(buildApiPath(FILE_SINGLETON), uid); @@ -67,13 +70,13 @@ for (File path : getAllPackageSpecificPathsExceptObb(getContext())) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); writeInt(new File(path, FILE_SINGLETON), uid); } } - public void readIsolatedStorage() throws Exception { + public void testReadIsolatedStorage() throws Exception { final int uid = android.os.Process.myUid(); // Expect that the value we wrote earlier is still valid and wasn't @@ -91,23 +94,23 @@ for (File path : getAllPackageSpecificPathsExceptObb(getContext())) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); assertEquals("Unexpected value in singleton file at " + path, uid, readInt(new File(path, FILE_SINGLETON))); } } - public void cleanObbStorage() throws Exception { + public void testCleanObbStorage() throws Exception { wipeTestFiles(getContext().getObbDir()); } - public void writeObbStorage() throws Exception { + public void testWriteObbStorage() throws Exception { writeInt(buildApiObbPath(FILE_OBB_API_SINGLETON), OBB_API_VALUE); writeInt(buildEnvObbPath(FILE_OBB_SINGLETON), OBB_VALUE); } - public void readObbStorage() throws Exception { + public void testReadObbStorage() throws Exception { assertEquals("Failed to read OBB file from API path", OBB_API_VALUE, readInt(buildApiObbPath(FILE_OBB_API_SINGLETON))); @@ -117,6 +120,24 @@ readInt(buildRawObbPath(FILE_OBB_SINGLETON))); } + /** + * Verify that we can't poke at storage of other users. + */ + public void testUserIsolation() throws Exception { + final File myPath = Environment.getExternalStorageDirectory(); + final int myId = android.os.Process.myUid() / 100000; + assertEquals(String.valueOf(myId), myPath.getName()); + + Log.d(TAG, "My path is " + myPath); + final File basePath = myPath.getParentFile(); + for (int i = 0; i < 128; i++) { + if (i == myId) continue; + + final File otherPath = new File(basePath, String.valueOf(i)); + assertDirNoAccess(otherPath); + } + } + private File buildApiObbPath(String file) { return new File(getContext().getObbDir(), file); }
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk index 60d6fad..43d3547 100644 --- a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk index ba7285c..5109c99 100644 --- a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk +++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk index 3e392e3..c662d39 100644 --- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk
@@ -27,4 +27,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java index bbd1e7a..995da90 100644 --- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java +++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadExternalStorageTest.java
@@ -16,16 +16,11 @@ package com.android.cts.readexternalstorageapp; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoWriteAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadOnlyAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadOnlyAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getMountPaths; import android.os.Environment; import android.test.AndroidTestCase; @@ -54,7 +49,7 @@ for (File path : paths) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); assertTrue(path.getAbsolutePath().contains(packageName)); @@ -65,7 +60,7 @@ } // Keep walking up until we leave device - while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) { + while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) { assertDirReadOnlyAccess(path); path = path.getParentFile(); } @@ -73,19 +68,21 @@ } /** - * Verify we can read all gifts. + * Verify that we don't have write access to any mountpoints. */ - public void doVerifyGifts() throws Exception { - final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); - assertFileReadOnlyAccess(none); - assertEquals(100, readInt(none)); + public void testMountPointsNotWritable() throws Exception { + final String userId = Integer.toString(android.os.Process.myUid() / 100000); + final List<File> mountPaths = getMountPaths(); + for (File path : mountPaths) { + if (path.getAbsolutePath().startsWith("/mnt/") + || path.getAbsolutePath().startsWith("/storage/")) { + // Mount points could be multi-user aware, so try probing both + // top level and user-specific directory. + final File userPath = new File(path, userId); - final File read = buildGiftForPackage(getContext(), PACKAGE_READ); - assertFileReadWriteAccess(read); - assertEquals(101, readInt(read)); - - final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); - assertFileReadOnlyAccess(write); - assertEquals(102, readInt(write)); + assertDirNoWriteAccess(path); + assertDirNoWriteAccess(userPath); + } + } } }
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java new file mode 100644 index 0000000..e72be77 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/src/com/android/cts/readexternalstorageapp/ReadGiftTest.java
@@ -0,0 +1,48 @@ +/* + * Copyright (C) 2015 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.readexternalstorageapp; + +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadOnlyAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; + +import android.test.AndroidTestCase; + +import java.io.File; + +public class ReadGiftTest extends AndroidTestCase { + /** + * Verify we can read all gifts. + */ + public void testGifts() throws Exception { + final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); + assertFileReadOnlyAccess(none); + assertEquals(100, readInt(none)); + + final File read = buildGiftForPackage(getContext(), PACKAGE_READ); + assertFileReadWriteAccess(read); + assertEquals(101, readInt(read)); + + final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); + assertFileReadOnlyAccess(write); + assertEquals(102, readInt(write)); + } +}
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk index 76187ab..05438ef 100644 --- a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk
@@ -32,4 +32,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk index c1422ec..eaed910 100644 --- a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk index fb925cd..01cffdb 100644 --- a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk index 2224d72..032ef57 100644 --- a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk index bf89576..de46dea 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk
@@ -35,7 +35,7 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) ################################################# @@ -59,7 +59,7 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) ################################################ @@ -82,7 +82,7 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) ################################################ @@ -105,7 +105,7 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) ifeq (,$(ONE_SHOT_MAKEFILE))
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk index 809a6b8..fbb7764 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
@@ -35,4 +35,4 @@ LOCAL_AAPT_FLAGS += --feature-of $(featureOfApk) -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk index 543e4ac..9faaba1 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk index 7cdef62..87b32aa 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk index 26ec5bd..fe289e0 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk index fea0603..d66d674 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk index 3cc5609..7232324 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk index d45ca8f..f1cd994 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk index fa0e488..521f6f2 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk +++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
@@ -25,4 +25,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java b/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java index 3d6cee7..c5f0fd0 100644 --- a/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java +++ b/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java
@@ -19,6 +19,7 @@ import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; +import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; @@ -27,9 +28,17 @@ import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; +import android.os.Environment; +import android.os.ParcelFileDescriptor; +import android.os.StatFs; +import android.system.Os; +import android.system.OsConstants; +import android.system.StructStat; import android.test.AndroidTestCase; import android.test.MoreAsserts; import android.util.DisplayMetrics; @@ -39,7 +48,12 @@ import org.xmlpull.v1.XmlPullParserException; import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.DataOutputStream; import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; @@ -51,9 +65,14 @@ private static final String TAG = "SplitAppTest"; private static final String PKG = "com.android.cts.splitapp"; + private static final long MB_IN_BYTES = 1 * 1024 * 1024; + public static boolean sFeatureTouched = false; public static String sFeatureValue = null; + public void testNothing() throws Exception { + } + public void testSingleBase() throws Exception { final Resources r = getContext().getResources(); final PackageManager pm = getContext().getPackageManager(); @@ -311,6 +330,131 @@ assertEquals(0, result.size()); } + /** + * Write app data in a number of locations that expect to remain intact over + * long periods of time, such as across app moves. + */ + public void testDataWrite() throws Exception { + final String token = String.valueOf(android.os.Process.myUid()); + writeString(getContext().getFileStreamPath("my_int"), token); + + final SQLiteDatabase db = getContext().openOrCreateDatabase("my_db", + Context.MODE_PRIVATE, null); + try { + db.execSQL("DROP TABLE IF EXISTS my_table"); + db.execSQL("CREATE TABLE my_table(value INTEGER)"); + db.execSQL("INSERT INTO my_table VALUES (101), (102), (103)"); + } finally { + db.close(); + } + } + + /** + * Verify that data written by {@link #testDataWrite()} is still intact. + */ + public void testDataRead() throws Exception { + final String token = String.valueOf(android.os.Process.myUid()); + assertEquals(token, readString(getContext().getFileStreamPath("my_int"))); + + final SQLiteDatabase db = getContext().openOrCreateDatabase("my_db", + Context.MODE_PRIVATE, null); + try { + final Cursor cursor = db.query("my_table", null, null, null, null, null, "value ASC"); + try { + assertEquals(3, cursor.getCount()); + assertTrue(cursor.moveToPosition(0)); + assertEquals(101, cursor.getInt(0)); + assertTrue(cursor.moveToPosition(1)); + assertEquals(102, cursor.getInt(0)); + assertTrue(cursor.moveToPosition(2)); + assertEquals(103, cursor.getInt(0)); + } finally { + cursor.close(); + } + } finally { + db.close(); + } + } + + /** + * Verify that app is installed on internal storage. + */ + public void testDataInternal() throws Exception { + final StructStat internal = Os.stat(Environment.getDataDirectory().getAbsolutePath()); + final StructStat actual = Os.stat(getContext().getFilesDir().getAbsolutePath()); + assertEquals(internal.st_dev, actual.st_dev); + } + + /** + * Verify that app is not installed on internal storage. + */ + public void testDataNotInternal() throws Exception { + final StructStat internal = Os.stat(Environment.getDataDirectory().getAbsolutePath()); + final StructStat actual = Os.stat(getContext().getFilesDir().getAbsolutePath()); + MoreAsserts.assertNotEqual(internal.st_dev, actual.st_dev); + } + + public void testPrimaryDataWrite() throws Exception { + final String token = String.valueOf(android.os.Process.myUid()); + writeString(new File(getContext().getExternalFilesDir(null), "my_ext"), token); + } + + public void testPrimaryDataRead() throws Exception { + final String token = String.valueOf(android.os.Process.myUid()); + assertEquals(token, readString(new File(getContext().getExternalFilesDir(null), "my_ext"))); + } + + /** + * Verify shared storage behavior when on internal storage. + */ + public void testPrimaryInternal() throws Exception { + assertTrue("emulated", Environment.isExternalStorageEmulated()); + assertFalse("removable", Environment.isExternalStorageRemovable()); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + } + + /** + * Verify shared storage behavior when on physical storage. + */ + public void testPrimaryPhysical() throws Exception { + assertFalse("emulated", Environment.isExternalStorageEmulated()); + assertTrue("removable", Environment.isExternalStorageRemovable()); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + } + + /** + * Verify shared storage behavior when on adopted storage. + */ + public void testPrimaryAdopted() throws Exception { + assertTrue("emulated", Environment.isExternalStorageEmulated()); + assertTrue("removable", Environment.isExternalStorageRemovable()); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + } + + /** + * Verify that shared storage is unmounted. + */ + public void testPrimaryUnmounted() throws Exception { + MoreAsserts.assertNotEqual(Environment.MEDIA_MOUNTED, + Environment.getExternalStorageState()); + } + + /** + * Verify that shared storage lives on same volume as app. + */ + public void testPrimaryOnSameVolume() throws Exception { + final File current = getContext().getFilesDir(); + final File primary = Environment.getExternalStorageDirectory(); + + // Shared storage may jump through another filesystem for permission + // enforcement, so we verify that total/free space are identical. + final long totalDelta = Math.abs(current.getTotalSpace() - primary.getTotalSpace()); + final long freeDelta = Math.abs(current.getFreeSpace() - primary.getFreeSpace()); + if (totalDelta > MB_IN_BYTES || freeDelta > MB_IN_BYTES) { + fail("Expected primary storage to be on same volume as app"); + } + } + public void testCodeCacheWrite() throws Exception { assertTrue(new File(getContext().getFilesDir(), "normal.raw").createNewFile()); assertTrue(new File(getContext().getCodeCacheDir(), "cache.raw").createNewFile()); @@ -390,4 +534,22 @@ if (in != null) in.close(); } } + + private static void writeString(File file, String value) throws IOException { + final DataOutputStream os = new DataOutputStream(new FileOutputStream(file)); + try { + os.writeUTF(value); + } finally { + os.close(); + } + } + + private static String readString(File file) throws IOException { + final DataInputStream is = new DataInputStream(new FileInputStream(file)); + try { + return is.readUTF(); + } finally { + is.close(); + } + } }
diff --git a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk index 38a0511..f5ac52f 100644 --- a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp/Android.mk new file mode 100644 index 0000000..f91d0c4 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp/Android.mk
@@ -0,0 +1,35 @@ +# +# Copyright (C) 2015 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. +# + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test ctsdeviceutil ctstestrunner ub-uiautomator + +LOCAL_SRC_FILES := $(call all-java-files-under, src) \ + ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java + +LOCAL_PACKAGE_NAME := CtsUsePermissionApp + +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2 + +LOCAL_PROGUARD_ENABLED := disabled +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp/AndroidManifest.xml new file mode 100644 index 0000000..ece4ebe --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp/AndroidManifest.xml
@@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.usepermission"> + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name=".MyActivity" /> + </application> + <instrumentation + android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.usepermission" /> + + <!-- Note that WRITE_EXTERNAL_STORAGE implies READ_EXTERNAL_STORAGE; + this is a special case. --> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + + <!-- Deliberately request WRITE_CONTACTS but *not* READ_CONTACTS --> + <uses-permission android:name="android.permission.WRITE_CONTACTS" /> + + <!-- Request two different permissions within the same group --> + <uses-permission android:name="android.permission.SEND_SMS" /> + <uses-permission android:name="android.permission.RECEIVE_SMS" /> + +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/MyActivity.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/MyActivity.java new file mode 100644 index 0000000..5af3886 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/MyActivity.java
@@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 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.usepermission; + +import android.app.Activity; +import android.os.Bundle; +import android.view.WindowManager; + +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; + +public class MyActivity extends Activity { + private final SynchronousQueue<Result> mResult = new SynchronousQueue<>(); + + public static class Result { + public final int requestCode; + public final String[] permissions; + public final int[] grantResults; + + public Result(int requestCode, String[] permissions, int[] grantResults) { + this.requestCode = requestCode; + this.permissions = permissions; + this.grantResults = grantResults; + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON + | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, + int[] grantResults) { + try { + mResult.offer(new Result(requestCode, permissions, grantResults), 5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public Result getResult() { + try { + return mResult.take(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +}
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/UsePermissionTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/UsePermissionTest.java new file mode 100644 index 0000000..8d3b976 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp/src/com/android/cts/usepermission/UsePermissionTest.java
@@ -0,0 +1,196 @@ +/* + * Copyright (C) 2015 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.usepermission; + +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertMediaNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertMediaReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.logCommand; + +import android.content.pm.PackageManager; +import android.os.Environment; +import android.support.test.uiautomator.UiDevice; +import android.support.test.uiautomator.UiObject; +import android.support.test.uiautomator.UiSelector; +import android.test.InstrumentationTestCase; + +public class UsePermissionTest extends InstrumentationTestCase { + private static final String TAG = "UsePermissionTest"; + + private UiDevice mDevice; + private MyActivity mActivity; + + public void testFail() throws Exception { + fail("Expected"); + } + + public void testKill() throws Exception { + android.os.Process.killProcess(android.os.Process.myPid()); + } + + public void testDefault() throws Exception { + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + // New permission model is denied by default + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)); + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + assertDirNoAccess(Environment.getExternalStorageDirectory()); + assertDirReadWriteAccess(getInstrumentation().getContext().getExternalCacheDir()); + assertMediaNoAccess(getInstrumentation().getContext().getContentResolver()); + } + + public void testGranted() throws Exception { + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)); + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + assertDirReadWriteAccess(Environment.getExternalStorageDirectory()); + assertDirReadWriteAccess(getInstrumentation().getContext().getExternalCacheDir()); + assertMediaReadWriteAccess(getInstrumentation().getContext().getContentResolver()); + } + + public void testInteractiveGrant() throws Exception { + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + // Start out without permission + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)); + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + assertDirNoAccess(Environment.getExternalStorageDirectory()); + assertDirReadWriteAccess(getInstrumentation().getContext().getExternalCacheDir()); + assertMediaNoAccess(getInstrumentation().getContext().getContentResolver()); + + // Go through normal grant flow + mDevice = UiDevice.getInstance(getInstrumentation()); + mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(), + MyActivity.class, null); + mDevice.waitForIdle(); + + mActivity.requestPermissions(new String[] { + android.Manifest.permission.READ_EXTERNAL_STORAGE, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, 42); + mDevice.waitForIdle(); + + new UiObject(new UiSelector() + .resourceId("com.android.packageinstaller:id/permission_allow_button")).click(); + mDevice.waitForIdle(); + + MyActivity.Result result = mActivity.getResult(); + assertEquals(42, result.requestCode); + assertEquals(android.Manifest.permission.READ_EXTERNAL_STORAGE, result.permissions[0]); + assertEquals(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, result.permissions[1]); + assertEquals(PackageManager.PERMISSION_GRANTED, result.grantResults[0]); + assertEquals(PackageManager.PERMISSION_GRANTED, result.grantResults[1]); + + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + // We should have permission now! + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)); + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + assertDirReadWriteAccess(Environment.getExternalStorageDirectory()); + assertDirReadWriteAccess(getInstrumentation().getContext().getExternalCacheDir()); + assertMediaReadWriteAccess(getInstrumentation().getContext().getContentResolver()); + + mActivity.finish(); + } + + public void testRuntimeGroupGrantSpecificity() throws Exception { + // Start out without permission + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS)); + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_CONTACTS)); + + // Go through normal grant flow + mDevice = UiDevice.getInstance(getInstrumentation()); + mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(), + MyActivity.class, null); + mDevice.waitForIdle(); + + // request only one permission from the 'contacts' permission group + mActivity.requestPermissions(new String[] { + android.Manifest.permission.WRITE_CONTACTS }, 43); + mDevice.waitForIdle(); + + new UiObject(new UiSelector() + .resourceId("com.android.packageinstaller:id/permission_allow_button")).click(); + mDevice.waitForIdle(); + + MyActivity.Result result = mActivity.getResult(); + assertEquals(43, result.requestCode); + assertEquals(android.Manifest.permission.WRITE_CONTACTS, result.permissions[0]); + assertEquals(PackageManager.PERMISSION_GRANTED, result.grantResults[0]); + + // We should have only the explicitly requested permission from this group + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS)); + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.READ_CONTACTS)); + + mActivity.finish(); + } + + public void testRuntimeGroupGrantExpansion() throws Exception { + // Start out without permission + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.RECEIVE_SMS)); + assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.SEND_SMS)); + + // Go through normal grant flow + mDevice = UiDevice.getInstance(getInstrumentation()); + mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(), + MyActivity.class, null); + mDevice.waitForIdle(); + + // request only one permission from the 'SMS' permission group at runtime, + // but two from this group are <uses-permission> in the manifest + mActivity.requestPermissions(new String[] { + android.Manifest.permission.RECEIVE_SMS }, 44); + mDevice.waitForIdle(); + + new UiObject(new UiSelector() + .resourceId("com.android.packageinstaller:id/permission_allow_button")).click(); + mDevice.waitForIdle(); + + MyActivity.Result result = mActivity.getResult(); + assertEquals(44, result.requestCode); + assertEquals(android.Manifest.permission.RECEIVE_SMS, result.permissions[0]); + assertEquals(PackageManager.PERMISSION_GRANTED, result.grantResults[0]); + + // We should now have been granted both of the permissions from this group + // that are mentioned in our manifest + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.RECEIVE_SMS)); + assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext() + .checkSelfPermission(android.Manifest.permission.SEND_SMS)); + + mActivity.finish(); + } +}
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/Android.mk new file mode 100644 index 0000000..70b4b0f --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/Android.mk
@@ -0,0 +1,35 @@ +# +# Copyright (C) 2015 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. +# + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := 21 +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test ctsdeviceutil ctstestrunner ub-uiautomator + +LOCAL_SRC_FILES := $(call all-java-files-under, src) \ + ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java + +LOCAL_PACKAGE_NAME := CtsUsePermissionAppCompat + +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2 + +LOCAL_PROGUARD_ENABLED := disabled +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/AndroidManifest.xml new file mode 100644 index 0000000..253d85d --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/AndroidManifest.xml
@@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.usepermission"> + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name=".MyActivity" /> + </application> + <instrumentation + android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.usepermission" /> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/src/com/android/cts/usepermission/UsePermissionCompatTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/src/com/android/cts/usepermission/UsePermissionCompatTest.java new file mode 100644 index 0000000..7f21d3400 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/UsePermissionAppCompat/src/com/android/cts/usepermission/UsePermissionCompatTest.java
@@ -0,0 +1,83 @@ +/* + * Copyright (C) 2015 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.usepermission; + +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertMediaNoAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertMediaReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.logCommand; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Environment; +import android.os.Process; +import android.test.InstrumentationTestCase; + +import java.io.File; + +public class UsePermissionCompatTest extends InstrumentationTestCase { + private static final String TAG = "UsePermissionTest"; + + public void testCompatDefault() throws Exception { + final Context context = getInstrumentation().getContext(); + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + // Legacy permission model is granted by default + assertEquals(PackageManager.PERMISSION_GRANTED, + context.checkPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, + Process.myPid(), Process.myUid())); + assertEquals(PackageManager.PERMISSION_GRANTED, + context.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, + Process.myPid(), Process.myUid())); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState()); + assertDirReadWriteAccess(Environment.getExternalStorageDirectory()); + for (File path : getAllPackageSpecificPaths(context)) { + if (path != null) { + assertDirReadWriteAccess(path); + } + } + assertMediaReadWriteAccess(getInstrumentation().getContext().getContentResolver()); + } + + public void testCompatRevoked() throws Exception { + final Context context = getInstrumentation().getContext(); + logCommand("/system/bin/cat", "/proc/self/mountinfo"); + + // Legacy permission model appears granted, but storage looks and + // behaves like it's ejected + assertEquals(PackageManager.PERMISSION_GRANTED, + context.checkPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, + Process.myPid(), Process.myUid())); + assertEquals(PackageManager.PERMISSION_GRANTED, + context.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, + Process.myPid(), Process.myUid())); + assertEquals(Environment.MEDIA_UNMOUNTED, Environment.getExternalStorageState()); + assertDirNoAccess(Environment.getExternalStorageDirectory()); + for (File dir : getAllPackageSpecificPaths(context)) { + if (dir != null) { + assertDirNoAccess(dir); + } + } + assertMediaNoAccess(getInstrumentation().getContext().getContentResolver()); + + // Just to be sure, poke explicit path + assertDirNoAccess(new File(Environment.getExternalStorageDirectory(), + "/Android/data/" + getInstrumentation().getContext().getPackageName())); + } +}
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk index 8878c47..6e0d090 100644 --- a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk +++ b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk
@@ -31,4 +31,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk index a98fcea..cdd77e8 100644 --- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
@@ -27,4 +27,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java index 6857236..5e6aa3e 100644 --- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java +++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteExternalStorageTest.java
@@ -17,17 +17,14 @@ package com.android.cts.writeexternalstorageapp; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.TAG; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirNoWriteAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadOnlyAccess; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertDirReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; -import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildProbeFile; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.deleteContents; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getAllPackageSpecificPaths; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getMountPaths; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getPrimaryPackageSpecificPaths; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.getSecondaryPackageSpecificPaths; import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; @@ -39,9 +36,7 @@ import com.android.cts.externalstorageapp.CommonExternalStorageTest; -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; import java.util.List; import java.util.Random; @@ -93,6 +88,17 @@ assertEquals(readInt(TEST_FILE), 32); } + public void testWriteExternalStorageDirs() throws Exception { + final File probe = new File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), + "100CTS"); + + assertFalse(probe.exists()); + assertTrue(probe.mkdirs()); + + assertDirReadWriteAccess(probe); + } + /** * Verify that legacy filesystem paths continue working, and that they all * point to same location. @@ -131,12 +137,12 @@ for (File path : paths) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); assertTrue(path.getAbsolutePath().contains(packageName)); // Walk until we leave device, writing the whole way - while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) { + while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) { assertDirReadWriteAccess(path); path = path.getParentFile(); } @@ -168,7 +174,7 @@ int depth = 0; while (depth++ < 32) { assertDirReadWriteAccess(path); - assertEquals(Environment.MEDIA_MOUNTED, Environment.getStorageState(path)); + assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState(path)); if (path.getAbsolutePath().equals(top.getAbsolutePath())) { break; @@ -183,7 +189,7 @@ // And going one step further should be outside our reach path = path.getParentFile(); assertDirNoWriteAccess(path); - assertEquals(Environment.MEDIA_UNKNOWN, Environment.getStorageState(path)); + assertEquals(Environment.MEDIA_UNKNOWN, Environment.getExternalStorageState(path)); } /** @@ -191,11 +197,11 @@ */ public void testMountStatus() { assertEquals(Environment.MEDIA_UNKNOWN, - Environment.getStorageState(new File("/meow-should-never-exist"))); + Environment.getExternalStorageState(new File("/meow-should-never-exist"))); // Internal data isn't a mount point assertEquals(Environment.MEDIA_UNKNOWN, - Environment.getStorageState(getContext().getCacheDir())); + Environment.getExternalStorageState(getContext().getCacheDir())); } /** @@ -209,7 +215,7 @@ for (File path : paths) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); assertTrue(path.getAbsolutePath().contains(packageName)); @@ -220,7 +226,7 @@ } // Keep walking up until we leave device - while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) { + while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) { assertDirReadOnlyAccess(path); path = path.getParentFile(); } @@ -239,12 +245,12 @@ for (File path : paths) { assertNotNull("Valid media must be inserted during CTS", path); assertEquals("Valid media must be inserted during CTS", Environment.MEDIA_MOUNTED, - Environment.getStorageState(path)); + Environment.getExternalStorageState(path)); final File start = path; boolean found = false; - while (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(path))) { + while (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(path))) { final File test = new File(path, ".nomedia"); if (test.exists()) { found = true; @@ -266,57 +272,29 @@ * {@link CommonExternalStorageTest#testAllPackageDirsWritable()}. */ public void testSecondaryMountPointsNotWritable() throws Exception { + // Probe path could be /storage/emulated/0 or /storage/1234-5678 final File probe = buildProbeFile(Environment.getExternalStorageDirectory()); assertTrue(probe.createNewFile()); - final BufferedReader br = new BufferedReader(new FileReader("/proc/self/mounts")); - try { - String line; - while ((line = br.readLine()) != null) { - final String[] fields = line.split(" "); - final File testMount = new File(fields[1]); - final File testProbe = new File(testMount, probe.getName()); - if (testProbe.exists()) { - Log.d(TAG, "Primary external mountpoint " + testMount); - } else { - // This mountpoint is not primary external storage; we must - // not be able to write. - Log.d(TAG, "Other mountpoint " + testMount); - assertDirNoWriteAccess(testProbe.getParentFile()); - } + final String userId = Integer.toString(android.os.Process.myUid() / 100000); + final List<File> mountPaths = getMountPaths(); + for (File path : mountPaths) { + // Mount points could be multi-user aware, so try probing both top + // level and user-specific directory. + final File userPath = new File(path, userId); + + final File testProbe = new File(path, probe.getName()); + final File testUserProbe = new File(userPath, probe.getName()); + + if (testProbe.exists() || testUserProbe.exists()) { + Log.d(TAG, "Primary external mountpoint " + path); + } else { + // This mountpoint is not primary external storage; we must + // not be able to write. + Log.d(TAG, "Other mountpoint " + path); + assertDirNoWriteAccess(path); + assertDirNoWriteAccess(userPath); } - } finally { - br.close(); - probe.delete(); - } - } - - /** - * Leave gifts for other packages in their primary external cache dirs. - */ - public void doWriteGifts() throws Exception { - final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); - none.getParentFile().mkdirs(); - none.createNewFile(); - assertFileReadWriteAccess(none); - - writeInt(none, 100); - assertEquals(100, readInt(none)); - - final File read = buildGiftForPackage(getContext(), PACKAGE_READ); - read.getParentFile().mkdirs(); - read.createNewFile(); - assertFileReadWriteAccess(read); - - writeInt(read, 101); - assertEquals(101, readInt(read)); - - final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); - write.getParentFile().mkdirs(); - write.createNewFile(); - assertFileReadWriteAccess(write); - - writeInt(write, 102); - assertEquals(102, readInt(write)); + } } }
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java new file mode 100644 index 0000000..5da42da --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/src/com/android/cts/writeexternalstorageapp/WriteGiftTest.java
@@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 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.writeexternalstorageapp; + +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_NONE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_READ; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.PACKAGE_WRITE; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.assertFileReadWriteAccess; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.buildGiftForPackage; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.readInt; +import static com.android.cts.externalstorageapp.CommonExternalStorageTest.writeInt; + +import android.test.AndroidTestCase; + +import java.io.File; + +public class WriteGiftTest extends AndroidTestCase { + /** + * Leave gifts for other packages in their primary external cache dirs. + */ + public void testGifts() throws Exception { + final File none = buildGiftForPackage(getContext(), PACKAGE_NONE); + none.getParentFile().mkdirs(); + none.createNewFile(); + assertFileReadWriteAccess(none); + + writeInt(none, 100); + assertEquals(100, readInt(none)); + + final File read = buildGiftForPackage(getContext(), PACKAGE_READ); + read.getParentFile().mkdirs(); + read.createNewFile(); + assertFileReadWriteAccess(read); + + writeInt(read, 101); + assertEquals(101, readInt(read)); + + final File write = buildGiftForPackage(getContext(), PACKAGE_WRITE); + write.getParentFile().mkdirs(); + write.createNewFile(); + assertFileReadWriteAccess(write); + + writeInt(write, 102); + assertEquals(102, readInt(write)); + } +}
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk new file mode 100644 index 0000000..207160f --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk
@@ -0,0 +1,27 @@ +# 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. + +LOCAL_PATH:= $(call my-dir) + +#apks signed cts-keyset-test-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSigningABadUpgradeB +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/AndroidManifest.xml new file mode 100644 index 0000000..e18bde5 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/AndroidManifest.xml
@@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.keysets"> + <application android:hasCode="false"> + </application> + <key-sets> + <key-set android:name="B" > + <public-key android:name="keyB" + android:value="makebadpubkeyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoeFZqMqTbZiozFTXMkXtSKJRzn2qODZgvVXAAwKTi50xYcbPcHTfKxtif8+q7OCp/50JYDH32bg6wkUunn5+dEaHkxZY8d7uw46tQtl5dNGi+6cc4MezVLCS6nkqNDusAgdvgLU6Fl6SGi02KTp1vkt6CwLO977YJP7kt9ouDRTG7ASJiq3OyRRoOqYHhD9gpsbUq4w+1bXGfuuZujA1dXyovXtvrHUGOdFIEBYOVYGfCcwh3lXPmjNJMlHtKQkurq8/LH7a1B5ocoXCGsyR8YHdlWfrqRAfzgOB1KCnNNmWqskU9LOci3uQn9IDeMEFmAd8FqF8SwV+4Ludk/xWGQIDAQAB" /> + </key-set> + <upgrade-key-set android:name="B"/> + </key-sets> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk new file mode 100644 index 0000000..84f3f75 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk
@@ -0,0 +1,27 @@ +# 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. + +LOCAL_PATH:= $(call my-dir) + +#apks signed cts-keyset-test-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSigningANoDefUpgradeB +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/AndroidManifest.xml new file mode 100644 index 0000000..aac717b --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/AndroidManifest.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.keysets"> + <application android:hasCode="false"> + </application> + <key-sets> + <upgrade-key-set android:name="B"/> + </key-sets> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk new file mode 100644 index 0000000..7290f06 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk
@@ -0,0 +1,27 @@ +# 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. + +LOCAL_PATH:= $(call my-dir) + +#apks signed cts-keyset-test-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSigningCBadAUpgradeAB +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-c +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/AndroidManifest.xml new file mode 100644 index 0000000..8242f6c --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/AndroidManifest.xml
@@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.keysets"> + <application android:hasCode="false"> + </application> + <key-sets> + <key-set android:name="AB" > + <public-key android:name="keyA" + android:value="makebadpubkeyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwf5zJblvYSB7Ym7or/7GggAAu7mp7RrykPJsXhod8doFhVT5s7eF3A4MCE55vvANP7HvwMw2b+T6qx7Pq0VJtbbSDtlBHBtIc47Pjq0CsDg590BUcgKp7PdJ9J6UVgtzDnV6cGEpXmSag3sY+lqiW04ytPhCVwzYTWGdYe9+TIl47cBrveRfLOlGrcuFQe+zCTmDFqzBKCRHK9b7l5PDWvXXyg65Uu/MBUA/TZWO0fEqOlxZG/nn6DUKQLhPdmJRXWJ3WqMNMhJGD+nKtkmdX703xRqmg4h+6g0S7M9Y3IQ2NUGyw05AYzCguHB/Mv6uVIiW659wpbyb45TgKG3UhQIDAQAB" /> + <public-key android:name="keyB" + android:value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoeFZqMqTbZiozFTXMkXtSKJRzn2qODZgvVXAAwKTi50xYcbPcHTfKxtif8+q7OCp/50JYDH32bg6wkUunn5+dEaHkxZY8d7uw46tQtl5dNGi+6cc4MezVLCS6nkqNDusAgdvgLU6Fl6SGi02KTp1vkt6CwLO977YJP7kt9ouDRTG7ASJiq3OyRRoOqYHhD9gpsbUq4w+1bXGfuuZujA1dXyovXtvrHUGOdFIEBYOVYGfCcwh3lXPmjNJMlHtKQkurq8/LH7a1B5ocoXCGsyR8YHdlWfrqRAfzgOB1KCnNNmWqskU9LOci3uQn9IDeMEFmAd8FqF8SwV+4Ludk/xWGQIDAQAB" /> + </key-set> + <upgrade-key-set android:name="AB"/> + </key-sets> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk index 715905a..f5a7286 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk
@@ -24,7 +24,7 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed cts-keyset-test-b include $(CLEAR_VARS) @@ -36,4 +36,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk index eceea38..678d89d 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk
@@ -24,7 +24,7 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed cts-keyset-test-b include $(CLEAR_VARS) @@ -36,4 +36,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk index ed6db690..b8acc99 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk
@@ -23,4 +23,4 @@ LOCAL_PACKAGE_NAME := CtsKeySetTestApp LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk index efba345..79d053b 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk
@@ -24,7 +24,7 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed by cts-keyset-test-b include $(CLEAR_VARS) @@ -35,7 +35,19 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) + +#apks signed by cts-keyset-test-ec-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSigningEcAUpgradeA +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed by cts-keyset-test-a and cts-keyset-test-b include $(CLEAR_VARS) @@ -47,4 +59,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_ADDITIONAL_CERTIFICATES := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk index 219689e..406529c 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk
@@ -24,4 +24,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk index 040c378..23d6b17 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk
@@ -24,4 +24,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk index 62b5461..f2cedf9 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk
@@ -24,7 +24,7 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed cts-keyset-test-b include $(CLEAR_VARS) @@ -36,7 +36,7 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE) #apks signed by cts-keyset-test-a and cts-keyset-test-c include $(CLEAR_VARS) @@ -49,4 +49,4 @@ LOCAL_ADDITIONAL_CERTIFICATES := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-c LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk new file mode 100644 index 0000000..1d6d5a5 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk
@@ -0,0 +1,39 @@ +# 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. + +LOCAL_PATH:= $(call my-dir) + +#apks signed cts-keyset-test-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSharedUserSigningAUpgradeB +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE) + +#apks signed cts-keyset-test-b +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSharedUserSigningBUpgradeB +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/AndroidManifest.xml new file mode 100644 index 0000000..55a1c24 --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/AndroidManifest.xml
@@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.keysets" + android:sharedUserId="com.android.cts.keysets.shareduser"> + <application android:hasCode="false"> + </application> + <key-sets> + <key-set android:name="B" > + <public-key android:name="keyB" + android:value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoeFZqMqTbZiozFTXMkXtSKJRzn2qODZgvVXAAwKTi50xYcbPcHTfKxtif8+q7OCp/50JYDH32bg6wkUunn5+dEaHkxZY8d7uw46tQtl5dNGi+6cc4MezVLCS6nkqNDusAgdvgLU6Fl6SGi02KTp1vkt6CwLO977YJP7kt9ouDRTG7ASJiq3OyRRoOqYHhD9gpsbUq4w+1bXGfuuZujA1dXyovXtvrHUGOdFIEBYOVYGfCcwh3lXPmjNJMlHtKQkurq8/LH7a1B5ocoXCGsyR8YHdlWfrqRAfzgOB1KCnNNmWqskU9LOci3uQn9IDeMEFmAd8FqF8SwV+4Ludk/xWGQIDAQAB" /> + </key-set> + <upgrade-key-set android:name="B"/> + </key-sets> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk new file mode 100644 index 0000000..3d0109a --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk
@@ -0,0 +1,27 @@ +# 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. + +LOCAL_PATH:= $(call my-dir) + +#apks signed by cts-keyset-test-a +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test +LOCAL_PACKAGE_NAME := CtsKeySetSigningAUpgradeEcA +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a +LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uEcA/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/keysets/uEcA/AndroidManifest.xml new file mode 100644 index 0000000..a84704a --- /dev/null +++ b/hostsidetests/appsecurity/test-apps/keysets/uEcA/AndroidManifest.xml
@@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.keysets"> + <application android:hasCode="false"> + </application> + <key-sets> + <key-set android:name="EcA" > + <public-key android:name="keyEcA" + android:value="MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfEPu5YOCkjrNgXtF4RcJRQrIggiId4l9renxPlfzA/kAU9duuYSMgShB/6ALE6S8vBXRiiwtMfk8LgnnbotEgQ=="/> + </key-set> + <upgrade-key-set android:name="EcA"/> + </key-sets> +</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk index 5fc4ab9..9b327fe 100644 --- a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk +++ b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk
@@ -24,4 +24,4 @@ LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/atrace/Android.mk b/hostsidetests/atrace/Android.mk new file mode 100644 index 0000000..1fd7102 --- /dev/null +++ b/hostsidetests/atrace/Android.mk
@@ -0,0 +1,30 @@ +# 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +# Must match the package name in CtsTestCaseList.mk +LOCAL_MODULE := CtsAtraceHostTestCases + +LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed-prebuilt + +LOCAL_CTS_TEST_PACKAGE := android.host.atrace + +include $(BUILD_CTS_HOST_JAVA_LIBRARY) + +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/atrace/AtraceTestApp/Android.mk b/hostsidetests/atrace/AtraceTestApp/Android.mk new file mode 100644 index 0000000..0eb7cfd --- /dev/null +++ b/hostsidetests/atrace/AtraceTestApp/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2009 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test + +LOCAL_PACKAGE_NAME := CtsAtraceTestApp + +# sign this app with a different cert than CtsSimpleAppInstallDiffCert +#LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1 + +#LOCAL_DEX_PREOPT := false + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/atrace/AtraceTestApp/AndroidManifest.xml b/hostsidetests/atrace/AtraceTestApp/AndroidManifest.xml new file mode 100644 index 0000000..c460300 --- /dev/null +++ b/hostsidetests/atrace/AtraceTestApp/AndroidManifest.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.atracetestapp"> + <!-- + A simple app with a tracing section to test that apps tracing signals are + emitted by atrace. + --> + <application android:debuggable="true"> <!-- Debuggable to enable tracing --> + <activity android:name=".AtraceTestAppActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> +</manifest>
diff --git a/hostsidetests/atrace/AtraceTestApp/src/com/android/cts/atracetestapp/AtraceTestAppActivity.java b/hostsidetests/atrace/AtraceTestApp/src/com/android/cts/atracetestapp/AtraceTestAppActivity.java new file mode 100644 index 0000000..0269d0d --- /dev/null +++ b/hostsidetests/atrace/AtraceTestApp/src/com/android/cts/atracetestapp/AtraceTestAppActivity.java
@@ -0,0 +1,29 @@ +/* + * Copyright (C) 2015 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.atracetestapp; + +import android.app.Activity; +import android.os.Bundle; +import android.os.Trace; + +public class AtraceTestAppActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + Trace.beginSection("traceable-app-test-section"); + super.onCreate(savedInstanceState); + Trace.endSection(); + } +}
diff --git a/hostsidetests/atrace/src/android/atrace/cts/AtraceHostTest.java b/hostsidetests/atrace/src/android/atrace/cts/AtraceHostTest.java new file mode 100644 index 0000000..760723e --- /dev/null +++ b/hostsidetests/atrace/src/android/atrace/cts/AtraceHostTest.java
@@ -0,0 +1,299 @@ +/* + * Copyright (C) 2015 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 android.atrace.cts; + +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.ddmlib.Log; +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.ITestDevice; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IBuildReceiver; + +import java.io.BufferedReader; +import java.io.File; +import java.io.Reader; +import java.io.StringReader; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Test to check that atrace is usable, to enable usage of systrace. + */ +public class AtraceHostTest extends DeviceTestCase implements IBuildReceiver { + private static final String TEST_APK = "CtsAtraceTestApp.apk"; + private static final String TEST_PKG = "com.android.cts.atracetestapp"; + + private interface FtraceEntryCallback { + void onTraceEntry(String threadName, int pid, int tid, String eventType, String args); + void onFinished(); + } + + /** + * Helper for parsing ftrace data. + * Regexs copied from (and should be kept in sync with) ftrace importer in catapult. + */ + private static class FtraceParser { + // Matches the trace record in 3.2 and later with the print-tgid option: + // <idle>-0 0 [001] d... 1.23: sched_switch + private static final Pattern sLineWithTgid = Pattern.compile( + "^\\s*(.+)-(\\d+)\\s+\\(\\s*(\\d+|-+)\\)\\s\\[(\\d+)\\]" + + "\\s+[dX.][N.][Hhs.][0-9a-f.]" + + "\\s+(\\d+\\.\\d+):\\s+(\\S+):\\s(.*)"); + + // Matches the default trace record in 3.2 and later (includes irq-info): + // <idle>-0 [001] d... 1.23: sched_switch + private static final Pattern sLineWithIrqInfo = Pattern.compile( + "^\\s*(.+)-(\\d+)\\s+\\[(\\d+)\\]" + + "\\s+[dX.][N.][Hhs.][0-9a-f.]" + + "\\s+(\\d+\\.\\d+):\\s+(\\S+):\\s(.*)$"); + + // Matches the default trace record pre-3.2: + // <idle>-0 [001] 1.23: sched_switch + private static final Pattern sLineLegacy = Pattern.compile( + "^\\s*(.+)-(\\d+)\\s+\\[(\\d+)\\]\\s*(\\d+\\.\\d+):\\s+(\\S+):\\s(.*)"); + private static void parseLine(String line, FtraceEntryCallback callback) { + Matcher m = sLineWithTgid.matcher(line); + if (m.matches()) { + callback.onTraceEntry( + /*threadname*/ m.group(1), + /*pid*/ m.group(3).startsWith("-") ? -1 : Integer.parseInt(m.group(3)), + /*tid*/ Integer.parseInt(m.group(2)), + /*eventName*/ m.group(6), + /*details*/ m.group(7)); + return; + } + + m = sLineWithIrqInfo.matcher(line); + if (m.matches()) { + callback.onTraceEntry( + /*threadname*/ m.group(1), + /*pid*/ -1, + /*tid*/ Integer.parseInt(m.group(2)), + /*eventName*/ m.group(5), + /*details*/ m.group(6)); + return; + } + + m = sLineLegacy.matcher(line); + if (m.matches()) { + callback.onTraceEntry( + /*threadname*/ m.group(1), + /*pid*/ -1, + /*tid*/ Integer.parseInt(m.group(2)), + /*eventName*/ m.group(5), + /*details*/ m.group(6)); + return; + } + System.err.println("line doesn't match: " + line); + } + + private static void parse(Reader reader, FtraceEntryCallback callback) throws Exception { + try { + BufferedReader bufferedReader = new BufferedReader(reader); + String line; + while ((line = bufferedReader.readLine()) != null) { + FtraceParser.parseLine(line, callback); + } + } finally { + callback.onFinished(); + } + } + } + + private CtsBuildHelper mCtsBuild; + + /** + * {@inheritDoc} + */ + @Override + public void setBuild(IBuildInfo buildInfo) { + mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + // Collection of all userspace tags, and 'sched' + private static final List<String> sRequiredCategoriesList = Arrays.asList( + "sched", + "gfx", + "input", + "view", + "webview", + "wm", + "am", + "sm", + "audio", + "video", + "camera", + "hal", + "app", + "res", + "dalvik", + "rs", + "bionic", + "power" + ); + + /** + * Tests that atrace exists and is runnable with no args + */ + public void testSimpleRun() throws Exception { + String output = getDevice().executeShellCommand("atrace"); + String[] lines = output.split("\\r?\\n"); + + // check for expected stdout + assertEquals("capturing trace... done", lines[0]); + assertEquals("TRACE:", lines[1]); + + // commented trace marker starts here + assertEquals("# tracer: nop", lines[2]); + } + + /** + * Tests the output of "atrace --list_categories" to ensure required categories exist. + */ + public void testCategories() throws Exception { + String output = getDevice().executeShellCommand("atrace --list_categories"); + String[] categories = output.split("\\r?\\n"); + + Set<String> requiredCategories = new HashSet<String>(sRequiredCategoriesList); + + for (String category : categories) { + int dashIndex = category.indexOf("-"); + + assertTrue(dashIndex > 1); // must match category output format + category = category.substring(0, dashIndex).trim(); + + requiredCategories.remove(category); + } + + if (!requiredCategories.isEmpty()) { + for (String missingCategory : requiredCategories) { + System.err.println("missing category: " + missingCategory); + } + fail("Expected categories missing from atrace"); + } + } + + /** + * Tests that atrace captures app launch, including app level tracing + */ + public void testTracingContent() throws Exception { + String atraceOutput = null; + try { + // cleanup test apps that might be installed from previous partial test run + getDevice().uninstallPackage(TEST_PKG); + + // install the test app + File testAppFile = mCtsBuild.getTestApp(TEST_APK); + String installResult = getDevice().installPackage(testAppFile, false); + assertNull( + String.format("failed to install atrace test app. Reason: %s", installResult), + installResult); + + // capture a launch of the app with async tracing + // content traced by 'view' tag tested below, 'sched' used to ensure tgid printed + String atraceArgs = "-a " + TEST_PKG + " -c -b 16000 view"; // TODO: zipping + getDevice().executeShellCommand("atrace --async_stop " + atraceArgs); + getDevice().executeShellCommand("atrace --async_start " + atraceArgs); + getDevice().executeShellCommand("am start " + TEST_PKG); + getDevice().executeShellCommand("sleep 1"); + atraceOutput = getDevice().executeShellCommand("atrace --async_stop " + atraceArgs); + } finally { + assertNotNull("unable to capture atrace output", atraceOutput); + getDevice().uninstallPackage(TEST_PKG); + } + + + // now parse the trace data (see external/chromium-trace/systrace.py) + final String MARKER = "TRACE:"; + int dataStart = atraceOutput.indexOf(MARKER); + assertTrue(dataStart >= 0); + String traceData = atraceOutput.substring(dataStart + MARKER.length()); + + FtraceEntryCallback callback = new FtraceEntryCallback() { + private int userSpaceMatches = 0; + private int beginMatches = 0; + private int nextSectionIndex = -1; + private int appTid = -1; + + + private final String initialSection = "traceable-app-test-section"; + // list of tags expected to be seen on app launch, in order, after the initial. + private final String[] requiredSectionList = { + "inflate", + "Choreographer#doFrame", + "traversal", + "measure", + "layout", + "draw", + "Record View#draw()" + }; + + @Override + public void onTraceEntry(String truncatedThreadName, int pid, int tid, + String eventName, String details) { + if (!"tracing_mark_write".equals(eventName)) { + // not userspace trace, ignore + return; + } + + assertNotNull(truncatedThreadName); + assertTrue(tid > 0); + userSpaceMatches++; + + if (details == null || !details.startsWith("B|")) { + // not a begin event + return; + } + beginMatches++; + + if (details.endsWith("|" + initialSection)) { + // initial section observed, start looking for others in order + assertEquals(nextSectionIndex, -1); + nextSectionIndex = 0; + appTid = tid; + return; + } + + if (nextSectionIndex >= 0 + && tid == appTid + && nextSectionIndex < requiredSectionList.length + && details.endsWith("|" + requiredSectionList[nextSectionIndex])) { + // found next required section in sequence + nextSectionIndex++; + } + } + + @Override + public void onFinished() { + assertTrue("Unable to parse any userspace sections from atrace output", + userSpaceMatches != 0); + assertTrue("Unable to parse any section begin events from atrace output", + beginMatches != 0); + assertTrue("Unable to parse initial userspace sections from test app", + nextSectionIndex >= 0); + assertEquals("Didn't see required list of traced sections, in order", + requiredSectionList.length, nextSectionIndex); + } + }; + + FtraceParser.parse(new StringReader(traceData), callback); + } +}
diff --git a/hostsidetests/devicepolicy/app/CertInstaller/Android.mk b/hostsidetests/devicepolicy/app/CertInstaller/Android.mk new file mode 100644 index 0000000..22a78e2 --- /dev/null +++ b/hostsidetests/devicepolicy/app/CertInstaller/Android.mk
@@ -0,0 +1,31 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_PACKAGE_NAME := CtsCertInstallerApp + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := android.test.runner + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/CertInstaller/AndroidManifest.xml b/hostsidetests/devicepolicy/app/CertInstaller/AndroidManifest.xml new file mode 100644 index 0000000..c50e5fd --- /dev/null +++ b/hostsidetests/devicepolicy/app/CertInstaller/AndroidManifest.xml
@@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.certinstaller"> + + <uses-sdk android:minSdkVersion="22"/> + + <application> + <activity android:name="CertInstallerActivity"> + <intent-filter> + <action android:name="com.android.cts.certinstaller.install_cert" /> + <action android:name="com.android.cts.certinstaller.remove_cert" /> + <action android:name="com.android.cts.certinstaller.verify_cert" /> + <action android:name="com.android.cts.certinstaller.install_keypair" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> + +</manifest>
diff --git a/hostsidetests/devicepolicy/app/CertInstaller/src/com/android/cts/certinstaller/CertInstallerActivity.java b/hostsidetests/devicepolicy/app/CertInstaller/src/com/android/cts/certinstaller/CertInstallerActivity.java new file mode 100644 index 0000000..b14822b --- /dev/null +++ b/hostsidetests/devicepolicy/app/CertInstaller/src/com/android/cts/certinstaller/CertInstallerActivity.java
@@ -0,0 +1,177 @@ +/* + * Copyright (C) 2015 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.certinstaller; + +import android.app.Activity; +import android.app.admin.DevicePolicyManager; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.util.Base64; +import android.util.Base64InputStream; +import android.util.Log; + +import java.io.ByteArrayInputStream; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.util.List; + +/** + * Delegated certificate installer app that responds to specific intents and executes various DPM + * certificate manipulation APIs. The following APIs are exercised: + * {@link DevicePolicyManager#installCaCert}, + * {@link DevicePolicyManager#uninstallCaCert}, + * {@link DevicePolicyManager#hasCaCertInstalled}, + * {@link DevicePolicyManager#getInstalledCaCerts}, + * {@link DevicePolicyManager#installKeyPair}. + */ +public class CertInstallerActivity extends Activity { + + private static final String TAG = "DelegatedCertInstaller"; + // exercises {@link DevicePolicyManager#installCaCert} and + // {@link DevicePolicyManager#hasCaCertInstalled}, + private static final String ACTION_INSTALL_CERT = "com.android.cts.certinstaller.install_cert"; + // exercises {@link DevicePolicyManager#uninstallCaCert} and + // {@link DevicePolicyManager#hasCaCertInstalled}, + private static final String ACTION_REMOVE_CERT = "com.android.cts.certinstaller.remove_cert"; + // exercises {@link DevicePolicyManager#getInstalledCaCerts}, + private static final String ACTION_VERIFY_CERT = "com.android.cts.certinstaller.verify_cert"; + // exercises {@link DevicePolicyManager#installKeyPair}, + private static final String ACTION_INSTALL_KEYPAIR = + "com.android.cts.certinstaller.install_keypair"; + + private static final String ACTION_CERT_OPERATION_DONE = "com.android.cts.certinstaller.done"; + + private static final String EXTRA_CERT_DATA = "extra_cert_data"; + private static final String EXTRA_KEY_DATA = "extra_key_data"; + private static final String EXTRA_KEY_ALIAS = "extra_key_alias"; + private static final String EXTRA_RESULT_VALUE = "extra_result_value"; + private static final String EXTRA_RESULT_EXCEPTION = "extra_result_exception"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = getIntent(); + if (intent == null) { + finish(); + return; + } + + String action = intent.getAction(); + DevicePolicyManager dpm = (DevicePolicyManager) getSystemService( + Context.DEVICE_POLICY_SERVICE); + + byte[] certBuffer; + + if (ACTION_INSTALL_CERT.equals(action)) { + try { + certBuffer = intent.getByteArrayExtra(EXTRA_CERT_DATA); + // Verify cert is not currently installed. + if (dpm.hasCaCertInstalled(null, certBuffer)) { + throw new RuntimeException("Cert already on device?"); + } + if (!dpm.installCaCert(null, certBuffer)) { + throw new RuntimeException("installCaCert returned false."); + } + if (!dpm.hasCaCertInstalled(null, certBuffer)) { + throw new RuntimeException("Cannot find cert after installation."); + } + sendResult(true, null); + } catch (Exception e) { + Log.e(TAG, "Exception raised duing ACTION_INSTALL_CERT", e); + sendResult(false, e); + } + } else if (ACTION_REMOVE_CERT.equals(action)) { + try { + certBuffer = intent.getByteArrayExtra(EXTRA_CERT_DATA); + if (!dpm.hasCaCertInstalled(null, certBuffer)) { + throw new RuntimeException("Trying to uninstall a non-existent cert."); + } + dpm.uninstallCaCert(null, certBuffer); + sendResult(!dpm.hasCaCertInstalled(null, certBuffer), null); + } catch (Exception e) { + Log.e(TAG, "Exception raised duing ACTION_REMOVE_CERT", e); + sendResult(false, e); + } + } else if (ACTION_VERIFY_CERT.equals(action)) { + try { + certBuffer = intent.getByteArrayExtra(EXTRA_CERT_DATA); + sendResult(containsCertificate(dpm.getInstalledCaCerts(null), certBuffer), null); + } catch (Exception e) { + Log.e(TAG, "Exception raised duing ACTION_VERIFY_CERT", e); + sendResult(false, e); + } + } else if (ACTION_INSTALL_KEYPAIR.equals(action)) { + String alias = intent.getStringExtra(EXTRA_KEY_ALIAS); + String key = intent.getStringExtra(EXTRA_KEY_DATA); + String cert = intent.getStringExtra(EXTRA_CERT_DATA); + try { + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec( + Base64.decode(key, Base64.DEFAULT)); + KeyFactory kf = KeyFactory.getInstance("RSA"); + PrivateKey privatekey = kf.generatePrivate(keySpec); + + Certificate certificate = CertificateFactory.getInstance("X.509") + .generateCertificate( + new Base64InputStream(new ByteArrayInputStream(cert.getBytes()), + Base64.DEFAULT)); + // Unfortunately there is no programmatically way to check if the given private key + // is indeed in the key store as a unprivileged app. So we just rely on + // installKeyPair() returning true as the success criteria of this test. Separate + // CTS keychain tests will make sure the API's behaviour is correct. + // Note: installKeyPair() will silently return false if there is no lockscreen + // password, however the test setup should have set one already. + sendResult(dpm.installKeyPair(null, privatekey, certificate, alias), null); + } catch (Exception e) { + Log.e(TAG, "Exception raised duing ACTION_INSTALL_KEYPAIR", e); + sendResult(false, e); + } + } + finish(); + } + + private void sendResult(boolean succeed, Exception e) { + Intent intent = new Intent(); + intent.setAction(ACTION_CERT_OPERATION_DONE); + intent.putExtra(EXTRA_RESULT_VALUE, succeed); + if (e != null) { + intent.putExtra(EXTRA_RESULT_EXCEPTION, e); + } + sendBroadcast(intent); + } + + private boolean containsCertificate(List<byte[]> certificates, byte[] toMatch) + throws CertificateException { + Certificate certificateToMatch = readCertificate(toMatch); + for (byte[] certBuffer : certificates) { + Certificate cert = readCertificate(certBuffer); + if (certificateToMatch.equals(cert)) { + return true; + } + } + return false; + } + + private Certificate readCertificate(byte[] certBuffer) throws CertificateException { + final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + return certFactory.generateCertificate(new ByteArrayInputStream(certBuffer)); + } + +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.mk new file mode 100644 index 0000000..0548af6 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_PACKAGE_NAME := CtsDeviceAndProfileOwnerApp + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit + +LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner ub-uiautomator + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/AndroidManifest.xml new file mode 100644 index 0000000..fe07bcb --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/AndroidManifest.xml
@@ -0,0 +1,86 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.deviceandprofileowner"> + + <uses-sdk android:minSdkVersion="23"/> + <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> + <uses-permission android:name="android.permission.GET_ACCOUNTS" /> + <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> + + <application> + <uses-library android:name="android.test.runner" /> + <receiver + android:name="com.android.cts.deviceandprofileowner.BaseDeviceAdminTest$BasicAdminReceiver" + android:permission="android.permission.BIND_DEVICE_ADMIN"> + <meta-data android:name="android.app.device_admin" + android:resource="@xml/device_admin" /> + <intent-filter> + <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> + </intent-filter> + </receiver> + <receiver + android:name="com.android.cts.deviceandprofileowner.PrimaryUserDeviceAdmin" + android:permission="android.permission.BIND_DEVICE_ADMIN"> + <meta-data android:name="android.app.device_admin" + android:resource="@xml/primary_device_admin" /> + <intent-filter> + <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> + </intent-filter> + </receiver> + <activity + android:name="com.android.cts.deviceandprofileowner.ApplicationRestrictionsActivity" /> + <activity + android:name="com.android.cts.deviceandprofileowner.ScreenCaptureDisabledActivity" /> + <activity + android:name="com.android.cts.deviceandprofileowner.ExampleIntentReceivingActivity1"> + <intent-filter> + <action android:name="com.android.cts.deviceandprofileowner.EXAMPLE_ACTION" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + + <activity + android:name="com.android.cts.deviceandprofileowner.ExampleIntentReceivingActivity2"> + <intent-filter> + <action android:name="com.android.cts.deviceandprofileowner.EXAMPLE_ACTION" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + + <service android:name=".MockAccountService" android:exported="true"> + <intent-filter> + <action android:name="android.accounts.AccountAuthenticator" /> + </intent-filter> + + <meta-data android:name="android.accounts.AccountAuthenticator" + android:resource="@xml/authenticator" /> + </service> + + <activity android:name=".UserRestrictionActivity" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT"/> + </intent-filter> + </activity> + + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.deviceandprofileowner" + android:label="Profile and Device Owner CTS Tests"/> +</manifest>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/values/strings.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/values/strings.xml new file mode 100644 index 0000000..4aca824 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/values/strings.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- Label for this package --> + <string name="authenticator_label">Android CTS - Device and Profile Owner</string> +</resources>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/authenticator.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/authenticator.xml new file mode 100644 index 0000000..0d8ecd8 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/authenticator.xml
@@ -0,0 +1,22 @@ +<!-- Copyright (C) 2015 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. +--> + +<!-- The attributes in this XML file provide configuration information --> +<!-- for the Account Manager. --> + +<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" + android:accountType="com.android.cts.deviceandprofileowner.account.type" + android:label="@string/authenticator_label" +/>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/device_admin.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/device_admin.xml new file mode 100644 index 0000000..69a661c --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/device_admin.xml
@@ -0,0 +1,18 @@ +<!-- Copyright (C) 2015 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. +--> +<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> + <uses-policies> + </uses-policies> +</device-admin>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/primary_device_admin.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/primary_device_admin.xml new file mode 100644 index 0000000..a6aff49 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/xml/primary_device_admin.xml
@@ -0,0 +1,20 @@ +<!-- Copyright (C) 2015 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. +--> +<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> + <uses-policies> + <reset-password /> + <limit-password /> + </uses-policies> +</device-admin>
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountManagementTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountManagementTest.java new file mode 100644 index 0000000..2d30ee3 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountManagementTest.java
@@ -0,0 +1,167 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.accounts.AuthenticatorException; +import android.accounts.OperationCanceledException; +import android.app.admin.DevicePolicyManager; +import android.content.Context; +import android.os.Bundle; + +import java.io.IOException; + +/** + * Functionality tests for {@link DevicePolicyManager#setAccountManagementDisabled} + * + * Fire up a remote unprivileged service and attempt to add/remove/list + * accounts from it to verify the enforcement is in place. + * + * This test depend on {@link MockAccountService}, which provides authenticator of type + * {@link MockAccountService#ACCOUNT_TYPE}. + */ +public class AccountManagementTest extends BaseDeviceAdminTest { + + // Account type for MockAccountAuthenticator + private final static String ACCOUNT_TYPE_1 = MockAccountAuthenticator.ACCOUNT_TYPE; + private final static String ACCOUNT_TYPE_2 = "com.dummy.account"; + private final static Account ACCOUNT_0 = new Account("user0", ACCOUNT_TYPE_1); + private final static Account ACCOUNT_1 = new Account("user1", ACCOUNT_TYPE_1); + + private AccountManager mAccountManager; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mAccountManager = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE); + clearAllAccountManagementDisabled(); + AccountUtilsTest.removeAllAccountsForType(mAccountManager, ACCOUNT_TYPE_1); + } + + @Override + protected void tearDown() throws Exception { + clearAllAccountManagementDisabled(); + AccountUtilsTest.removeAllAccountsForType(mAccountManager, ACCOUNT_TYPE_1); + super.tearDown(); + } + + public void testAccountManagementDisabled_setterAndGetter() { + // Some local tests: adding and removing disabled accounts and make sure + // DevicePolicyManager keeps track of the disabled set correctly + assertEquals(0, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + true); + assertEquals(1, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + assertEquals(ACCOUNT_TYPE_1, + mDevicePolicyManager.getAccountTypesWithManagementDisabled()[0]); + + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + false); + assertEquals(0, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + } + + public void testAccountManagementDisabled_addAccount() throws AuthenticatorException, + IOException, OperationCanceledException { + // Test for restriction on addAccount() + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + true); + // Test if disabling ACCOUNT_TYPE_2 affects ACCOUNT_TYPE_1 + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_2, + false); + assertEquals(1, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + + assertEquals(0, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + // Management is disabled, adding account should fail. + try { + mAccountManager.addAccount(ACCOUNT_TYPE_1, null, null, null, null, null, null) + .getResult(); + fail("Expected OperationCanceledException is not thrown."); + } catch (OperationCanceledException e) { + // Expected + } + assertEquals(0, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + + // Management is re-enabled, adding account should succeed. + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + false); + assertEquals(0, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + Bundle result = mAccountManager.addAccount(ACCOUNT_TYPE_1, + null, null, null, null, null, null).getResult(); + + // Normally the expected result of addAccount() is AccountManager returning + // an intent to start the authenticator activity for adding new accounts. + // But MockAccountAuthenticator returns a new account straightway. + assertEquals(ACCOUNT_TYPE_1, result.getString(AccountManager.KEY_ACCOUNT_TYPE)); + } + + public void testAccountManagementDisabled_removeAccount() throws AuthenticatorException, + IOException, OperationCanceledException { + // Test for restriction on removeAccount() + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + true); + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_2, + false); + assertEquals(1, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + + assertEquals(0, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + // First prepare some accounts by manually adding them, + // setAccountManagementDisabled(true) should not stop addAccountExplicitly(). + assertTrue(mAccountManager.addAccountExplicitly(ACCOUNT_0, "password", null)); + assertTrue(mAccountManager.addAccountExplicitly(ACCOUNT_1, "password", null)); + assertEquals(2, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + + // Removing account should fail, as we just disabled it. + try { + mAccountManager.removeAccount(ACCOUNT_0, null, null).getResult(); + fail("Expected OperationCanceledException is not thrown."); + } catch (OperationCanceledException e) { + // Expected + } + assertEquals(2, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + + // Re-enable management, so we can successfully remove account this time. + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_1, + false); + assertEquals(0, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + assertTrue(mAccountManager.removeAccount(ACCOUNT_0, null, null).getResult()); + + // Make sure the removal actually succeeds. + Account[] accounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE_1); + assertEquals(1, accounts.length); + assertEquals(ACCOUNT_1, accounts[0]); + + // Disable account type 2, we should still be able to remove from type 1. + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, ACCOUNT_TYPE_2, + true); + assertEquals(1, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + assertTrue(mAccountManager.removeAccount(ACCOUNT_1, null, null).getResult()); + + // Make sure the removal actually succeeds. + assertEquals(0, mAccountManager.getAccountsByType(ACCOUNT_TYPE_1).length); + } + + private void clearAllAccountManagementDisabled() { + for (String accountType : mDevicePolicyManager.getAccountTypesWithManagementDisabled()) { + mDevicePolicyManager.setAccountManagementDisabled(ADMIN_RECEIVER_COMPONENT, accountType, + false); + } + assertEquals(0, mDevicePolicyManager.getAccountTypesWithManagementDisabled().length); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountUtilsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountUtilsTest.java new file mode 100644 index 0000000..7a9e5ad --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AccountUtilsTest.java
@@ -0,0 +1,65 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.content.Context; +import android.os.Bundle; +import android.test.AndroidTestCase; + +/** + * Utility class that allows adding and removing accounts. + * + * This test depend on {@link MockAccountService}, which provides authenticator of type + * {@link MockAccountService#ACCOUNT_TYPE}. + */ +public class AccountUtilsTest extends AndroidTestCase { + + private final static Account ACCOUNT_0 = new Account("user0", + MockAccountAuthenticator.ACCOUNT_TYPE); + private AccountManager mAccountManager; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mAccountManager = (AccountManager) getContext().getSystemService(Context.ACCOUNT_SERVICE); + } + + public void testAddAccount() throws Exception { + assertEquals(0, mAccountManager.getAccountsByType(MockAccountAuthenticator.ACCOUNT_TYPE) + .length); + assertTrue(mAccountManager.addAccountExplicitly(ACCOUNT_0, "password", null)); + assertEquals(1, mAccountManager.getAccountsByType(MockAccountAuthenticator.ACCOUNT_TYPE) + .length); + } + + public void testRemoveAccounts() throws Exception { + removeAllAccountsForType(mAccountManager, MockAccountAuthenticator.ACCOUNT_TYPE); + } + + static void removeAllAccountsForType(AccountManager am, String accountType) + throws Exception { + Account[] accounts = am.getAccountsByType(accountType); + for (Account account : accounts) { + AccountManagerFuture<Boolean> result = am.removeAccount(account, null, null); + assertTrue(result.getResult()); + } + assertEquals(0, am.getAccountsByType(accountType).length); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationHiddenTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationHiddenTest.java new file mode 100644 index 0000000..d8be42f --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationHiddenTest.java
@@ -0,0 +1,120 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DevicePolicyManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.Uri; +import android.util.Log; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Tests for {@link DevicePolicyManager#setApplicationHidden} and + * {@link DevicePolicyManager#isApplicationHidden} APIs. + */ +public class ApplicationHiddenTest extends BaseDeviceAdminTest { + + private static final String TAG = "ApplicationHiddenTest"; + + private static final String PACKAGE_TO_HIDE = "com.android.cts.permissionapp"; + private static final String NONEXISTING_PACKAGE_NAME = "a.b.c.d"; + + private static final IntentFilter PACKAGE_INTENT_FILTER; + static { + PACKAGE_INTENT_FILTER = new IntentFilter(); + PACKAGE_INTENT_FILTER.addAction(Intent.ACTION_PACKAGE_ADDED); + PACKAGE_INTENT_FILTER.addAction(Intent.ACTION_PACKAGE_REMOVED); + PACKAGE_INTENT_FILTER.addDataScheme("package"); + } + private final ApplicationHiddenReceiver mReceiver = new ApplicationHiddenReceiver(); + + @Override + protected void setUp() throws Exception { + super.setUp(); + mContext.registerReceiver(mReceiver, PACKAGE_INTENT_FILTER); + } + + @Override + protected void tearDown() throws Exception { + mContext.unregisterReceiver(mReceiver); + mDevicePolicyManager.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, PACKAGE_TO_HIDE, false); + super.tearDown(); + } + + public void testSetApplicationHidden() throws Exception { + assertTrue(mDevicePolicyManager.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, + PACKAGE_TO_HIDE, true)); + assertTrue(mDevicePolicyManager.isApplicationHidden(ADMIN_RECEIVER_COMPONENT, + PACKAGE_TO_HIDE)); + mReceiver.waitForRemovedBroadcast(); + assertTrue(mDevicePolicyManager.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, + PACKAGE_TO_HIDE, false)); + assertFalse(mDevicePolicyManager.isApplicationHidden(ADMIN_RECEIVER_COMPONENT, + PACKAGE_TO_HIDE)); + mReceiver.waitForAddedBroadcast(); + } + + public void testCannotHideActiveAdmin() throws Exception { + assertFalse(mDevicePolicyManager.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, + PACKAGE_NAME, true)); + } + + public void testCannotHideNonExistingPackage() throws Exception { + assertFalse(mDevicePolicyManager.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, + NONEXISTING_PACKAGE_NAME, true)); + } + + private class ApplicationHiddenReceiver extends BroadcastReceiver { + private final Semaphore mAddedSemaphore = new Semaphore(0); + private final Semaphore mRemovedSemaphore = new Semaphore(0); + + @Override + public void onReceive(Context context, Intent intent) { + Uri uri = intent.getData(); + if (uri == null) { + return; + } + String pkgName = uri.getSchemeSpecificPart(); + if (!PACKAGE_TO_HIDE.equals(pkgName)) { + return; + } + if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) { + Log.d(TAG, "Received PACKAGE_ADDED broadcast"); + mAddedSemaphore.release(); + } else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) { + Log.d(TAG, "Received PACKAGE_REMOVED broadcast"); + mRemovedSemaphore.release(); + } + } + + public void waitForAddedBroadcast() throws Exception { + if (!mAddedSemaphore.tryAcquire(60, TimeUnit.SECONDS)) { + fail("Did not receive PACKAGE_ADDED broadcast."); + } + } + + public void waitForRemovedBroadcast() throws Exception { + if (!mRemovedSemaphore.tryAcquire(60, TimeUnit.SECONDS)) { + fail("Did not receive PACKAGE_REMOVED broadcast."); + } + } + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsActivity.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsActivity.java new file mode 100644 index 0000000..ccf8222 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsActivity.java
@@ -0,0 +1,93 @@ +/* + * 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.deviceandprofileowner; + +import android.app.Activity; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.os.UserManager; + +/** + * Test activity for setApplicationRestrictions(). + * + * The actual test will set restrictions for this package, and the purpose of this + * activity is to listen for the ACTION_APPLICATION_RESTRICTIONS_CHANGED broadcast + * and relay the retrieved restriction bundle back to the test for validation. + */ +public class ApplicationRestrictionsActivity extends Activity { + + // Incoming intent type + public static final String FINISH = "finishActivity"; + + // Outgoing broadcast + public static final String REGISTERED_ACTION = + "com.android.cts.deviceandprofileowner.APP_RESTRICTION_REGISTERED"; + public static final String RESTRICTION_ACTION = + "com.android.cts.deviceandprofileowner.APP_RESTRICTION_VALUE"; + + private UserManager mUserManager; + + private final BroadcastReceiver mAppRestrictionReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + broadcastRestriction(); + } + }; + + private void broadcastRestriction() { + Bundle restrictions = mUserManager.getApplicationRestrictions(getPackageName()); + Intent intent = new Intent(RESTRICTION_ACTION); + intent.putExtra("value", restrictions); + sendBroadcast(intent); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + handleIntent(intent); + } + + @Override + protected void onCreate(android.os.Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + handleIntent(getIntent()); + } + + @Override + protected void onResume() { + super.onResume(); + mUserManager = (UserManager) getSystemService(Context.USER_SERVICE); + IntentFilter filter = new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); + registerReceiver(mAppRestrictionReceiver, filter); + sendBroadcast(new Intent(REGISTERED_ACTION)); + } + + @Override + protected void onPause() { + super.onPause(); + unregisterReceiver(mAppRestrictionReceiver); + } + + private void handleIntent(Intent intent) { + if (intent.getBooleanExtra(FINISH, false)) { + finish(); + } + } + +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsTest.java new file mode 100644 index 0000000..98ae202 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ApplicationRestrictionsTest.java
@@ -0,0 +1,241 @@ +/* + * 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.deviceandprofileowner; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.os.Parcelable; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Functionality tests for setApplicationRestrictions and getApplicationRestrictions + * in DevicePolicyManager. + * + * First of all, these two APIs are executed locally to assert that what you set + * can later be retrieved via the getter. It also fires up an external activity + * (which runs in com.google.android.xts.gmscore, unlike the test code itself + * which runs in the test target package com.google.android.gms due to + * instrumentation) to observe an application's view of its restrictions. + * The activity listens to ACTION_APPLICATION_RESTRICTIONS_CHANGED broadcast + * which is fired by the system whenever its restriction is modified, + * and relays the value back to this test for verification. + */ +public class ApplicationRestrictionsTest extends BaseDeviceAdminTest { + + private static final String[] testStrings = new String[] { + "<bad/>", + ">worse!\"£$%^&*()'<", + "<JSON>\"{ \\\"One\\\": { \\\"OneOne\\\": \\\"11\\\", \\\"" + + "OneTwo\\\": \\\"12\\\" }, \\\"Two\\\": \\\"2\\\" } <JSON/>\"" + }; + + private final Semaphore mOnRegisteredSemaphore = new Semaphore(0); + private final Semaphore mOnRestrictionSemaphore = new Semaphore(0); + private Bundle mReceivedRestrictions; + + @Override + protected void setUp() throws Exception { + super.setUp(); + IntentFilter filter = new IntentFilter(); + filter.addAction(ApplicationRestrictionsActivity.REGISTERED_ACTION); + filter.addAction(ApplicationRestrictionsActivity.RESTRICTION_ACTION); + mContext.registerReceiver(mReceiver, filter); + } + + @Override + protected void tearDown() throws Exception { + mContext.unregisterReceiver(mReceiver); + super.tearDown(); + } + + public void testSetApplicationRestrictions() { + final String CTS_PACKAGE = PACKAGE_NAME; + final String OTHER_PACKAGE = CTS_PACKAGE + "dummy"; + + startAndWait(); + + Bundle bundle0 = createBundle0(); + Bundle bundle1 = createBundle1(); + + // Test setting restrictions + mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, CTS_PACKAGE, + bundle0); + mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, OTHER_PACKAGE, + bundle1); + + // Retrieve restrictions locally and make sure they are what we put in. + assertBundle0(mDevicePolicyManager.getApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, + CTS_PACKAGE)); + assertBundle1(mDevicePolicyManager.getApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, + OTHER_PACKAGE)); + + // The test activity should have received a change_restriction broadcast + // and relay the value back to us. + assertBundle0(waitForChangedRestriction()); + + // Test overwriting + mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, CTS_PACKAGE, + bundle1); + assertBundle1(mDevicePolicyManager.getApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, + CTS_PACKAGE)); + assertBundle1(waitForChangedRestriction()); + + // Cleanup + mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, CTS_PACKAGE, + new Bundle()); + assertTrue(mDevicePolicyManager.getApplicationRestrictions( + ADMIN_RECEIVER_COMPONENT, CTS_PACKAGE).isEmpty()); + assertTrue(waitForChangedRestriction().isEmpty()); + mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, OTHER_PACKAGE, + new Bundle()); + assertTrue(mDevicePolicyManager.getApplicationRestrictions( + ADMIN_RECEIVER_COMPONENT, OTHER_PACKAGE).isEmpty()); + + finish(); + } + + // Should be consistent with assertBundle0 + private Bundle createBundle0() { + Bundle result = new Bundle(); + // Tests for 6 allowed types: Integer, Boolean, String, String[], Bundle and Parcelable[] + // Also test for string escaping handling + result.putBoolean("boolean_0", false); + result.putBoolean("boolean_1", true); + result.putInt("integer", 0x7fffffff); + // If a null is stored, "" will be read back + result.putString("empty", ""); + result.putString("string", "text"); + result.putStringArray("string[]", testStrings); + + // Adding a bundle, which contain 2 nested restrictions - bundle_string and bundle_int + Bundle bundle = new Bundle(); + bundle.putString("bundle_string", "bundle_string"); + bundle.putInt("bundle_int", 1); + result.putBundle("bundle", bundle); + + // Adding an array of 2 bundles + Bundle[] bundleArray = new Bundle[2]; + bundleArray[0] = new Bundle(); + bundleArray[0].putString("bundle_array_string", "bundle_array_string"); + // Put bundle inside bundle + bundleArray[0].putBundle("bundle_array_bundle", bundle); + bundleArray[1] = new Bundle(); + bundleArray[1].putString("bundle_array_string2", "bundle_array_string2"); + result.putParcelableArray("bundle_array", bundleArray); + return result; + } + + // Should be consistent with createBundle0 + private void assertBundle0(Bundle bundle) { + assertEquals(8, bundle.size()); + assertEquals(false, bundle.getBoolean("boolean_0")); + assertEquals(true, bundle.getBoolean("boolean_1")); + assertEquals(0x7fffffff, bundle.getInt("integer")); + assertEquals("", bundle.getString("empty")); + assertEquals("text", bundle.getString("string")); + + String[] strings = bundle.getStringArray("string[]"); + assertTrue(strings != null && strings.length == testStrings.length); + for (int i = 0; i < strings.length; i++) { + assertEquals(strings[i], testStrings[i]); + } + + Bundle childBundle = bundle.getBundle("bundle"); + assertEquals("bundle_string", childBundle.getString("bundle_string")); + assertEquals(1, childBundle.getInt("bundle_int")); + + Parcelable[] bundleArray = bundle.getParcelableArray("bundle_array"); + assertEquals(2, bundleArray.length); + // Verifying bundle_array[0] + Bundle bundle1 = (Bundle) bundleArray[0]; + assertEquals("bundle_array_string", bundle1.getString("bundle_array_string")); + Bundle bundle1ChildBundle = bundle1.getBundle("bundle_array_bundle"); + assertNotNull(bundle1ChildBundle); + assertEquals("bundle_string", bundle1ChildBundle.getString("bundle_string")); + assertEquals(1, bundle1ChildBundle.getInt("bundle_int")); + // Verifying bundle_array[1] + Bundle bundle2 = (Bundle) bundleArray[1]; + assertEquals("bundle_array_string2", bundle2.getString("bundle_array_string2")); + } + + // Should be consistent with assertBundle1 + private Bundle createBundle1() { + Bundle result = new Bundle(); + result.putInt("dummy", 1); + return result; + } + + // Should be consistent with createBundle1 + private void assertBundle1(Bundle bundle) { + assertEquals(1, bundle.size()); + assertEquals(1, bundle.getInt("dummy")); + } + + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (ApplicationRestrictionsActivity.REGISTERED_ACTION.equals(action)) { + mOnRegisteredSemaphore.release(); + } else if (ApplicationRestrictionsActivity.RESTRICTION_ACTION.equals(action)) { + mReceivedRestrictions = intent.getBundleExtra("value"); + mOnRestrictionSemaphore.release(); + } + } + }; + + private void startTestActivity(String command) { + Intent intent = new Intent(); + intent.setClassName(PACKAGE_NAME, ApplicationRestrictionsActivity.class.getName()); + intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + + if (command != null) { + intent.putExtra(command, true); + } + mContext.startActivity(intent); + } + + private void startAndWait() { + startTestActivity(null); + // Wait until the activity has registered its broadcast receiver and ready for incoming + // restriction changes. + try { + assertTrue(mOnRegisteredSemaphore.tryAcquire(5, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + fail("Start ApplicationRestrictionActivity interrupted"); + } + } + + private Bundle waitForChangedRestriction() { + try { + assertTrue(mOnRestrictionSemaphore.tryAcquire(5, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + fail("getRestrictionsAndWait() interrupted"); + } + + return mReceivedRestrictions; + } + + private void finish() { + startTestActivity(ApplicationRestrictionsActivity.FINISH); + } + +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java new file mode 100644 index 0000000..148d8a8 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java
@@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DeviceAdminReceiver; +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.test.InstrumentationTestCase; + +/** + * Base class for profile and device based tests. + * + * This class handles making sure that the test is the profile or device owner and that it has an + * active admin registered, so that all tests may assume these are done. + */ +public class BaseDeviceAdminTest extends InstrumentationTestCase { + + public static class BasicAdminReceiver extends DeviceAdminReceiver { + } + + public static final String PACKAGE_NAME = BasicAdminReceiver.class.getPackage().getName(); + public static final ComponentName ADMIN_RECEIVER_COMPONENT = new ComponentName( + PACKAGE_NAME, BasicAdminReceiver.class.getName()); + + protected DevicePolicyManager mDevicePolicyManager; + protected Context mContext; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mContext = getInstrumentation().getContext(); + + mDevicePolicyManager = (DevicePolicyManager) + mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + assertNotNull(mDevicePolicyManager); + + assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT)); + assertTrue("App is neither device nor profile owner", + mDevicePolicyManager.isProfileOwnerApp(PACKAGE_NAME) || + mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME)); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ClearDeviceOwnerTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ClearDeviceOwnerTest.java new file mode 100644 index 0000000..2fe0569 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ClearDeviceOwnerTest.java
@@ -0,0 +1,58 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.test.AndroidTestCase; + +public class ClearDeviceOwnerTest extends AndroidTestCase { + + private DevicePolicyManager mDevicePolicyManager; + + @Override + protected void tearDown() throws Exception { + mDevicePolicyManager = (DevicePolicyManager) + mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + if (mDevicePolicyManager != null) { + removeActiveAdmin(BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT); + if (mDevicePolicyManager.isDeviceOwnerApp(BaseDeviceAdminTest.PACKAGE_NAME)) { + mDevicePolicyManager.clearDeviceOwnerApp(BaseDeviceAdminTest.PACKAGE_NAME); + } + assertFalse(mDevicePolicyManager.isAdminActive( + BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT)); + assertFalse(mDevicePolicyManager.isDeviceOwnerApp(BaseDeviceAdminTest.PACKAGE_NAME)); + } + + super.tearDown(); + } + + // This test clears the device owner and active admin on tearDown(). To be called from the host + // side test once a test case is finished. + public void testClearDeviceOwner() { + } + + private void removeActiveAdmin(ComponentName cn) throws InterruptedException { + if (mDevicePolicyManager.isAdminActive(cn)) { + mDevicePolicyManager.removeActiveAdmin(cn); + for (int i = 0; i < 1000 && mDevicePolicyManager.isAdminActive(cn); i++) { + Thread.sleep(100); + } + } + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DelegatedCertInstallerTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DelegatedCertInstallerTest.java new file mode 100644 index 0000000..3eb8c35 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/DelegatedCertInstallerTest.java
@@ -0,0 +1,291 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.KeyguardManager; +import android.app.admin.DevicePolicyManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.security.KeyChain; +import android.security.KeyChainException; +import android.test.AndroidTestCase; +import android.util.Base64; +import android.util.Base64InputStream; + +import java.io.ByteArrayInputStream; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Exercise delegated cert installer APIs in {@link DevicePolicyManager} by setting the test app + * (CtsCertInstallerApp) as a delegated cert installer and then asking it to invoke various + * cert-related APIs. The expected certificate changes are validated both remotely and locally. + */ +public class DelegatedCertInstallerTest extends BaseDeviceAdminTest { + + private static final String CERT_INSTALLER_PACKAGE = "com.android.cts.certinstaller"; + + private static final String ACTION_INSTALL_CERT = "com.android.cts.certinstaller.install_cert"; + private static final String ACTION_REMOVE_CERT = "com.android.cts.certinstaller.remove_cert"; + private static final String ACTION_VERIFY_CERT = "com.android.cts.certinstaller.verify_cert"; + private static final String ACTION_INSTALL_KEYPAIR = + "com.android.cts.certinstaller.install_keypair"; + private static final String ACTION_CERT_OPERATION_DONE = "com.android.cts.certinstaller.done"; + + private static final String EXTRA_CERT_DATA = "extra_cert_data"; + private static final String EXTRA_KEY_DATA = "extra_key_data"; + private static final String EXTRA_KEY_ALIAS = "extra_key_alias"; + private static final String EXTRA_RESULT_VALUE = "extra_result_value"; + private static final String EXTRA_RESULT_EXCEPTION = "extra_result_exception"; + + /* + * The CA and keypair below are generated with: + * + * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem + * openssl req -newkey rsa:1024 -keyout userkey.pem -nodes -days 3650 -out userkey.req + * mkdir -p demoCA/newcerts + * touch demoCA/index.txt + * echo "01" > demoCA/serial + * openssl ca -out usercert.pem -in userkey.req -cert cacert.pem -keyfile cakey.pem -days 3650 + */ + + // Content from cacert.pem + private static final String TEST_CA = + "-----BEGIN CERTIFICATE-----\n" + + "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" + + "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" + + "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" + + "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" + + "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" + + "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" + + "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" + + "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" + + "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" + + "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" + + "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" + + "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" + + "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" + + "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" + + "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" + + "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" + + "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" + + "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" + + "wQ==\n" + + "-----END CERTIFICATE-----"; + // Content from userkey.pem without the private key header and footer. + private static final String TEST_KEY = + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALCYprGsTU+5L3KM\n" + + "fhkm0gXM2xjGUH+543YLiMPGVr3eVS7biue1/tQlL+fJsw3rqsPKJe71RbVWlpqU\n" + + "mhegxG4s3IvGYVB0KZoRIjDKmnnvlx6nngL2ZJ8O27U42pHsw4z4MKlcQlWkjL3T\n" + + "9sV6zW2Wzri+f5mvzKjhnArbLktHAgMBAAECgYBlfVVPhtZnmuXJzzQpAEZzTugb\n" + + "tN1OimZO0RIocTQoqj4KT+HkiJOLGFQPwbtFpMre+q4SRqNpM/oZnI1yRtKcCmIc\n" + + "mZgkwJ2k6pdSxqO0ofxFFTdT9czJ3rCnqBHy1g6BqUQFXT4olcygkxUpKYUwzlz1\n" + + "oAl487CoPxyr4sVEAQJBANwiUOHcdGd2RoRILDzw5WOXWBoWPOKzX/K9wt0yL+mO\n" + + "wlFNFSymqo9eLheHcEq/VD9qK9rT700dCewJfWj6+bECQQDNXmWNYIxGii5NJilT\n" + + "OBOHiMD/F0NE178j+/kmacbhDJwpkbLYXaP8rW4+Iswrm4ORJ59lvjNuXaZ28+sx\n" + + "fFp3AkA6Z7Bl/IO135+eATgbgx6ZadIqObQ1wbm3Qbmtzl7/7KyJvZXcnuup1icM\n" + + "fxa//jtwB89S4+Ad6ZJ0WaA4dj5BAkEAuG7V9KmIULE388EZy8rIfyepa22Q0/qN\n" + + "hdt8XasRGHsio5Jdc0JlSz7ViqflhCQde/aBh/XQaoVgQeO8jKyI8QJBAJHekZDj\n" + + "WA0w1RsBVVReN1dVXgjm1CykeAT8Qx8TUmBUfiDX6w6+eGQjKtS7f4KC2IdRTV6+\n" + + "bDzDoHBChHNC9ms=\n"; + + // Content from usercert.pem without the header and footer. + private static final String TEST_CERT = + "MIIDEjCCAfqgAwIBAgIBATANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJBVTET\n" + + "MBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQ\n" + + "dHkgTHRkMB4XDTE1MDUwMTE2NTQwNVoXDTI1MDQyODE2NTQwNVowWzELMAkGA1UE\n" + + "BhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdp\n" + + "ZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLY2xpZW50IGNlcnQwgZ8wDQYJKoZIhvcN\n" + + "AQEBBQADgY0AMIGJAoGBALCYprGsTU+5L3KMfhkm0gXM2xjGUH+543YLiMPGVr3e\n" + + "VS7biue1/tQlL+fJsw3rqsPKJe71RbVWlpqUmhegxG4s3IvGYVB0KZoRIjDKmnnv\n" + + "lx6nngL2ZJ8O27U42pHsw4z4MKlcQlWkjL3T9sV6zW2Wzri+f5mvzKjhnArbLktH\n" + + "AgMBAAGjezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2Vu\n" + + "ZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBQ8GL+jKSarvTn9fVNA2AzjY7qq\n" + + "gjAfBgNVHSMEGDAWgBRzBBA5sNWyT/fK8GrhN3tOqO5tgjANBgkqhkiG9w0BAQsF\n" + + "AAOCAQEAgwQEd2bktIDZZi/UOwU1jJUgGq7NiuBDPHcqgzjxhGFLQ8SQAAP3v3PR\n" + + "mLzcfxsxnzGynqN5iHQT4rYXxxaqrp1iIdj9xl9Wl5FxjZgXITxhlRscOd/UOBvG\n" + + "oMrazVczjjdoRIFFnjtU3Jf0Mich68HD1Z0S3o7X6sDYh6FTVR5KbLcxbk6RcoG4\n" + + "VCI5boR5LUXgb5Ed5UxczxvN12S71fyxHYVpuuI0z0HTIbAxKeRw43I6HWOmR1/0\n" + + "G6byGCNL/1Fz7Y+264fGqABSNTKdZwIU2K4ANEH7F+9scnhoO6OBp+gjBe5O+7jb\n" + + "wZmUCAoTka4hmoaOCj7cqt/IkmxozQ==\n"; + + private DevicePolicyManager mDpm; + private volatile boolean mReceivedResult; + private volatile Exception mReceivedException; + private Semaphore mAvailableResultSemaphore; + + private final BroadcastReceiver receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (ACTION_CERT_OPERATION_DONE.equals(intent.getAction())) { + synchronized (DelegatedCertInstallerTest.this) { + mReceivedResult = intent.getBooleanExtra(EXTRA_RESULT_VALUE, false); + mReceivedException = + (Exception) intent.getSerializableExtra(EXTRA_RESULT_EXCEPTION); + mAvailableResultSemaphore.release(); + } + } + } + }; + + @Override + public void setUp() throws Exception { + super.setUp(); + mDpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + mAvailableResultSemaphore = new Semaphore(0); + mReceivedResult = false; + mReceivedException = null; + IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_CERT_OPERATION_DONE); + mContext.registerReceiver(receiver, filter); + } + + @Override + public void tearDown() throws Exception { + mContext.unregisterReceiver(receiver); + mDpm.uninstallCaCert(ADMIN_RECEIVER_COMPONENT, TEST_CA.getBytes()); + // Installed private key pair will be removed once the lockscreen password is cleared, + // which is done in the hostside test. + mDpm.setCertInstallerPackage(ADMIN_RECEIVER_COMPONENT, null); + super.tearDown(); + } + + public void testCaCertsOperations() throws InterruptedException { + byte[] cert = TEST_CA.getBytes(); + + mDpm.setCertInstallerPackage(ADMIN_RECEIVER_COMPONENT, CERT_INSTALLER_PACKAGE); + assertEquals(CERT_INSTALLER_PACKAGE, + mDpm.getCertInstallerPackage(ADMIN_RECEIVER_COMPONENT)); + + // Exercise installCaCert() + installCaCert(cert); + assertResult("installCaCert", true); + assertTrue("Certificate is not installed properly", mDpm.hasCaCertInstalled( + ADMIN_RECEIVER_COMPONENT, cert)); + + // Exercise getInstalledCaCerts() + verifyCaCert(cert); + assertResult("getInstalledCaCerts()", true); + + // Exercise uninstallCaCert() + removeCaCert(cert); + assertResult("uninstallCaCert()", true); + assertFalse("Certificate is not removed properly", mDpm.hasCaCertInstalled( + ADMIN_RECEIVER_COMPONENT, cert)); + + // Clear delegated cert installer. + // Tests after this are expected to fail. + mDpm.setCertInstallerPackage(ADMIN_RECEIVER_COMPONENT, null); + + installCaCert(cert); + assertResult("installCaCert", false); + } + + public void testInstallKeyPair() throws InterruptedException, KeyChainException { + final String alias = "delegated-cert-installer-test-key"; + + // Clear delegated cert installer. + mDpm.setCertInstallerPackage(ADMIN_RECEIVER_COMPONENT, null); + // The app is not the cert installer , it shouldn't have have privilege to call + // installKeyPair(). + installKeyPair(TEST_KEY, TEST_CERT, alias); + assertResult("installKeyPair", false); + + // Set the app to be cert installer. + mDpm.setCertInstallerPackage(ADMIN_RECEIVER_COMPONENT, CERT_INSTALLER_PACKAGE); + assertEquals(CERT_INSTALLER_PACKAGE, + mDpm.getCertInstallerPackage(ADMIN_RECEIVER_COMPONENT)); + + // Exercise installKeyPair() + checkKeyguardPrecondition(); + installKeyPair(TEST_KEY, TEST_CERT, alias); + assertResult("installKeyPair", true); + } + + /** + * installKeyPair() requires the system to have a lockscreen password, which should have been + * set by the host side test. + */ + private void checkKeyguardPrecondition() throws InterruptedException { + KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); + if (!km.isKeyguardSecure()) { + Thread.sleep(5000); + } + assertTrue("A lockscreen password is required before keypair can be installed", + km.isKeyguardSecure()); + } + + private void installCaCert(byte[] cert) { + Intent intent = new Intent(); + intent.setAction(ACTION_INSTALL_CERT); + intent.putExtra(EXTRA_CERT_DATA, cert); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(intent); + } + + private void removeCaCert(byte[] cert) { + Intent intent = new Intent(); + intent.setAction(ACTION_REMOVE_CERT); + intent.putExtra(EXTRA_CERT_DATA, cert); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(intent); + } + + private void verifyCaCert(byte[] cert) { + Intent intent = new Intent(); + intent.setAction(ACTION_VERIFY_CERT); + intent.putExtra(EXTRA_CERT_DATA, cert); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(intent); + } + + private void assertResult(String testName, Boolean expectSuccess) throws InterruptedException { + assertTrue("Cert installer did not respond in time.", + mAvailableResultSemaphore.tryAcquire(5, TimeUnit.SECONDS)); + synchronized (this) { + if (expectSuccess) { + assertTrue(testName + " failed unexpectedly.", mReceivedResult); + assertNull(testName + " raised exception", mReceivedException); + } else { + assertFalse(testName + " succeeded unexpectedly.", mReceivedResult); + assertTrue(testName + " did not raise SecurityException", + mReceivedException != null && + mReceivedException instanceof SecurityException); + } + } + } + + private void installKeyPair(String key, String cert, String alias) { + Intent intent = new Intent(); + intent.setAction(ACTION_INSTALL_KEYPAIR); + intent.putExtra(EXTRA_CERT_DATA, cert); + intent.putExtra(EXTRA_KEY_DATA, key); + intent.putExtra(EXTRA_KEY_ALIAS, alias); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(intent); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity1.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity1.java new file mode 100644 index 0000000..bbcc3b1 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity1.java
@@ -0,0 +1,34 @@ +/* + * 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.deviceandprofileowner; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +public class ExampleIntentReceivingActivity1 extends Activity { + static final String CONFIRM_ACTION = "com.android.cts.deviceandprofileowner.CONFIRM_1"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getIntent().getAction().equals(PersistentIntentResolvingTest.EXAMPLE_ACTION)) { + sendBroadcast(new Intent(CONFIRM_ACTION)); + } + finish(); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity2.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity2.java new file mode 100644 index 0000000..5122b06 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ExampleIntentReceivingActivity2.java
@@ -0,0 +1,34 @@ +/* + * 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.deviceandprofileowner; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +public class ExampleIntentReceivingActivity2 extends Activity { + static final String CONFIRM_ACTION = "com.android.cts.deviceandprofileowner.CONFIRM_2"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getIntent().getAction().equals(PersistentIntentResolvingTest.EXAMPLE_ACTION)) { + sendBroadcast(new Intent(CONFIRM_ACTION)); + } + finish(); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountAuthenticator.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountAuthenticator.java new file mode 100644 index 0000000..e8e5b45 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountAuthenticator.java
@@ -0,0 +1,100 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.accounts.AbstractAccountAuthenticator; +import android.accounts.Account; +import android.accounts.AccountAuthenticatorResponse; +import android.accounts.AccountManager; +import android.accounts.NetworkErrorException; +import android.content.Context; +import android.os.Bundle; + +/* package */ class MockAccountAuthenticator extends AbstractAccountAuthenticator { + private static MockAccountAuthenticator sMockAuthenticator = null; + private static final String ACCOUNT_NAME = "com.android.cts.deviceandprofileowner.account.name"; + static final String ACCOUNT_TYPE = "com.android.cts.deviceandprofileowner.account.type"; + private static final String AUTH_TOKEN = "mockAuthToken"; + private static final String AUTH_TOKEN_LABEL = "mockAuthTokenLabel"; + + private MockAccountAuthenticator(Context context) { + super(context); + } + + private Bundle createResultBundle() { + Bundle result = new Bundle(); + result.putString(AccountManager.KEY_ACCOUNT_NAME, ACCOUNT_NAME); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE); + result.putString(AccountManager.KEY_AUTHTOKEN, AUTH_TOKEN); + + return result; + } + + @Override + public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, + String authTokenType, String[] requiredFeatures, Bundle options) + throws NetworkErrorException { + return createResultBundle(); + } + + @Override + public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { + return createResultBundle(); + } + + @Override + public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, + String authTokenType, Bundle options) throws NetworkErrorException { + return createResultBundle(); + } + + @Override + public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, + Bundle options) throws NetworkErrorException { + + Bundle result = new Bundle(); + result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + return result; + } + + @Override + public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, + String authTokenType, Bundle options) throws NetworkErrorException { + return createResultBundle(); + } + + @Override + public String getAuthTokenLabel(String authTokenType) { + return AUTH_TOKEN_LABEL; + } + + @Override + public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, + String[] features) throws NetworkErrorException { + + Bundle result = new Bundle(); + result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + return result; + } + + public static synchronized MockAccountAuthenticator getMockAuthenticator(Context context) { + if (null == sMockAuthenticator) { + sMockAuthenticator = new MockAccountAuthenticator(context); + } + return sMockAuthenticator; + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountService.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountService.java new file mode 100644 index 0000000..dfedccb --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/MockAccountService.java
@@ -0,0 +1,32 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +/** + * a basic Mock Service for wrapping the MockAccountAuthenticator + */ +public class MockAccountService extends Service { + + @Override + public IBinder onBind(Intent intent) { + return MockAccountAuthenticator.getMockAuthenticator(this).getIBinder(); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PermissionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PermissionsTest.java new file mode 100644 index 0000000..d181ad5 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PermissionsTest.java
@@ -0,0 +1,320 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DevicePolicyManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.os.UserManager; +import android.support.test.uiautomator.By; +import android.support.test.uiautomator.BySelector; +import android.support.test.uiautomator.UiDevice; +import android.support.test.uiautomator.UiObject2; +import android.support.test.uiautomator.UiWatcher; +import android.support.test.uiautomator.Until; +import android.util.Log; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * Test Runtime Permissions APIs in DevicePolicyManager. + */ +public class PermissionsTest extends BaseDeviceAdminTest { + private static final String TAG = "PermissionsTest"; + + private static final String PERMISSION_APP_PACKAGE_NAME + = "com.android.cts.permissionapp"; + private static final String SIMPLE_PRE_M_APP_PACKAGE_NAME = + "com.android.cts.launcherapps.simplepremapp"; + private static final String PERMISSION_NAME = "android.permission.READ_CONTACTS"; + + private static final String PERMISSIONS_ACTIVITY_NAME + = PERMISSION_APP_PACKAGE_NAME + ".PermissionActivity"; + private static final String ACTION_CHECK_HAS_PERMISSION + = "com.android.cts.permission.action.CHECK_HAS_PERMISSION"; + private static final String ACTION_REQUEST_PERMISSION + = "com.android.cts.permission.action.REQUEST_PERMISSION"; + private static final String ACTION_PERMISSION_RESULT + = "com.android.cts.permission.action.PERMISSION_RESULT"; + private static final String EXTRA_PERMISSION + = "com.android.cts.permission.extra.PERMISSION"; + private static final String EXTRA_GRANT_STATE + = "com.android.cts.permission.extra.GRANT_STATE"; + private static final int PERMISSION_ERROR = -2; + private static final BySelector CRASH_POPUP_BUTTON_SELECTOR = By + .clazz(android.widget.Button.class.getName()) + .text("OK") + .pkg("android"); + private static final BySelector CRASH_POPUP_TEXT_SELECTOR = By + .clazz(android.widget.TextView.class.getName()) + .pkg("android"); + private static final String CRASH_WATCHER_ID = "CRASH"; + + private PermissionBroadcastReceiver mReceiver; + private PackageManager mPackageManager; + private UiDevice mDevice; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mReceiver = new PermissionBroadcastReceiver(); + mContext.registerReceiver(mReceiver, new IntentFilter(ACTION_PERMISSION_RESULT)); + mPackageManager = mContext.getPackageManager(); + mDevice = UiDevice.getInstance(getInstrumentation()); + } + + @Override + protected void tearDown() throws Exception { + mContext.unregisterReceiver(mReceiver); + mDevice.removeWatcher(CRASH_WATCHER_ID); + super.tearDown(); + } + + public void testPermissionGrantState() throws Exception { + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED); + assertPermissionGrantState(PackageManager.PERMISSION_DENIED); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + // Should stay denied + assertPermissionGrantState(PackageManager.PERMISSION_DENIED); + + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + assertPermissionGrantState(PackageManager.PERMISSION_GRANTED); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + // Should stay granted + assertPermissionGrantState(PackageManager.PERMISSION_GRANTED); + } + + public void testPermissionPolicy() throws Exception { + // reset permission to denied and unlocked + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED); + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + // permission should be locked, so changing the policy should not change the grant state + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + + // reset permission to denied and unlocked + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + // permission should be locked, so changing the policy should not change the grant state + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + } + + public void testPermissionMixedPolicies() throws Exception { + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + } + + public void testPermissionPrompts() throws Exception { + // register a crash watcher + mDevice.registerWatcher(CRASH_WATCHER_ID, new UiWatcher() { + @Override + public boolean checkForCondition() { + UiObject2 button = mDevice.findObject(CRASH_POPUP_BUTTON_SELECTOR); + if (button != null) { + UiObject2 text = mDevice.findObject(CRASH_POPUP_TEXT_SELECTOR); + Log.d(TAG, "Removing an error dialog: " + text != null ? text.getText() : null); + button.click(); + return true; + } + return false; + } + }); + mDevice.runWatchers(); + + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_PROMPT); + assertPermissionRequest(PackageManager.PERMISSION_DENIED, "permission_deny_button"); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED, "permission_allow_button"); + } + + public void testPermissionUpdate_setDeniedState() throws Exception { + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME), + DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED); + } + + public void testPermissionUpdate_setAutoDeniedPolicy() throws Exception { + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME), + DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_DENY); + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + } + + public void testPermissionUpdate_checkDenied() throws Exception { + assertPermissionRequest(PackageManager.PERMISSION_DENIED); + assertPermissionGrantState(PackageManager.PERMISSION_DENIED); + } + + public void testPermissionUpdate_setGrantedState() throws Exception { + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME), + DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + assertSetPermissionGrantState(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + } + + public void testPermissionUpdate_setAutoGrantedPolicy() throws Exception { + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME), + DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + assertSetPermissionPolicy(DevicePolicyManager.PERMISSION_POLICY_AUTO_GRANT); + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + } + + public void testPermissionUpdate_checkGranted() throws Exception { + assertPermissionRequest(PackageManager.PERMISSION_GRANTED); + assertPermissionGrantState(PackageManager.PERMISSION_GRANTED); + } + + public void testPermissionGrantStatePreMApp() throws Exception { + // These tests are to make sure that pre-M apps are not granted runtime permissions + // by a profile owner + assertSetPermissionGrantStatePreMApp(DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED); + assertSetPermissionGrantStatePreMApp(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + } + + private void assertPermissionRequest(int expected) throws Exception { + assertPermissionRequest(expected, null); + } + + private void assertPermissionRequest(int expected, String buttonResource) throws Exception { + Intent launchIntent = new Intent(); + launchIntent.setComponent(new ComponentName(PERMISSION_APP_PACKAGE_NAME, + PERMISSIONS_ACTIVITY_NAME)); + launchIntent.putExtra(EXTRA_PERMISSION, PERMISSION_NAME); + launchIntent.setAction(ACTION_REQUEST_PERMISSION); + launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); + mContext.startActivity(launchIntent); + pressPermissionPromptButton(buttonResource); + assertEquals(expected, mReceiver.waitForBroadcast()); + assertEquals(expected, mPackageManager.checkPermission(PERMISSION_NAME, + PERMISSION_APP_PACKAGE_NAME)); + } + + private void assertPermissionGrantState(int expected) throws Exception { + assertEquals(expected, mPackageManager.checkPermission(PERMISSION_NAME, + PERMISSION_APP_PACKAGE_NAME)); + Intent launchIntent = new Intent(); + launchIntent.setComponent(new ComponentName(PERMISSION_APP_PACKAGE_NAME, + PERMISSIONS_ACTIVITY_NAME)); + launchIntent.putExtra(EXTRA_PERMISSION, PERMISSION_NAME); + launchIntent.setAction(ACTION_CHECK_HAS_PERMISSION); + launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); + mContext.startActivity(launchIntent); + assertEquals(expected, mReceiver.waitForBroadcast()); + } + + private void assertSetPermissionPolicy(int value) throws Exception { + mDevicePolicyManager.setPermissionPolicy(ADMIN_RECEIVER_COMPONENT, + value); + assertEquals(mDevicePolicyManager.getPermissionPolicy(ADMIN_RECEIVER_COMPONENT), + value); + } + + private void assertSetPermissionGrantState(int value) throws Exception { + mDevicePolicyManager.setPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME, + value); + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + PERMISSION_APP_PACKAGE_NAME, PERMISSION_NAME), + value); + } + + private void assertSetPermissionGrantStatePreMApp(int value) throws Exception { + assertFalse(mDevicePolicyManager.setPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + SIMPLE_PRE_M_APP_PACKAGE_NAME, PERMISSION_NAME, + value)); + assertEquals(mDevicePolicyManager.getPermissionGrantState(ADMIN_RECEIVER_COMPONENT, + SIMPLE_PRE_M_APP_PACKAGE_NAME, PERMISSION_NAME), + DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); + // Install time permissions should always be granted + assertEquals(mPackageManager.checkPermission(PERMISSION_NAME, + SIMPLE_PRE_M_APP_PACKAGE_NAME), + PackageManager.PERMISSION_GRANTED); + } + + private void pressPermissionPromptButton(String resName) throws Exception { + if (resName == null) { + return; + } + + BySelector selector = By + .clazz(android.widget.Button.class.getName()) + .res("com.android.packageinstaller", resName); + mDevice.wait(Until.hasObject(selector), 5000); + UiObject2 button = mDevice.findObject(selector); + assertNotNull("Couldn't find button with resource id: " + resName, button); + button.click(); + } + + private class PermissionBroadcastReceiver extends BroadcastReceiver { + private BlockingQueue<Integer> mQueue = new ArrayBlockingQueue<Integer> (1); + + @Override + public void onReceive(Context context, Intent intent) { + Integer result = new Integer(intent.getIntExtra(EXTRA_GRANT_STATE, PERMISSION_ERROR)); + Log.d(TAG, "Grant state received " + result); + assertTrue(mQueue.add(result)); + } + + public int waitForBroadcast() throws Exception { + Integer result = mQueue.poll(30, TimeUnit.SECONDS); + mQueue.clear(); + assertNotNull(result); + Log.d(TAG, "Grant state retrieved " + result.intValue()); + return result.intValue(); + } + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PersistentIntentResolvingTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PersistentIntentResolvingTest.java new file mode 100644 index 0000000..41526ec --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PersistentIntentResolvingTest.java
@@ -0,0 +1,129 @@ +/* + * 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.deviceandprofileowner; + +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.SystemClock; + +public class PersistentIntentResolvingTest extends BaseDeviceAdminTest { + static final String EXAMPLE_ACTION = "com.android.cts.deviceandprofileowner.EXAMPLE_ACTION"; + + private boolean mReceivedConfirmationFrom1; + private boolean mReceivedConfirmationFrom2; + private BroadcastReceiver mReceiver; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + IntentFilter filter = new IntentFilter(); + filter.addAction(ExampleIntentReceivingActivity1.CONFIRM_ACTION); + filter.addAction(ExampleIntentReceivingActivity2.CONFIRM_ACTION); + + mReceiver = new ConfirmReceiver(); + mContext.registerReceiver(mReceiver, filter); + + synchronized(this) { + mReceivedConfirmationFrom1 = false; + mReceivedConfirmationFrom2 = false; + } + } + + @Override + protected void tearDown() throws Exception { + mDevicePolicyManager.clearPackagePersistentPreferredActivities(ADMIN_RECEIVER_COMPONENT, + PACKAGE_NAME); + mContext.unregisterReceiver(mReceiver); + + super.tearDown(); + } + + public void testNoPersistentPreferredActivityYieldsResolverActivity() { + sendExampleIntent(); + SystemClock.sleep(5000); + + // Default behavior: intent results in resolver activity, since there are two potential + // receivers. No intent is received. + synchronized(this) { + assertFalse(mReceivedConfirmationFrom1); + assertFalse(mReceivedConfirmationFrom2); + } + } + + public void testAddPersistentPreferredActivityYieldsReceptionAtTarget() { + addPersistentPreferredActivity(); + sendExampleIntent(); + SystemClock.sleep(5000); + + // Persistent preferred activity present: intent should be received by activity 2. + synchronized(this) { + assertFalse(mReceivedConfirmationFrom1); + assertTrue(mReceivedConfirmationFrom2); + } + } + + public void testAddAndClearPersistentPreferredActivitiesYieldsResolverActivity() { + addPersistentPreferredActivity(); + mDevicePolicyManager.clearPackagePersistentPreferredActivities(ADMIN_RECEIVER_COMPONENT, + PACKAGE_NAME); + + sendExampleIntent(); + SystemClock.sleep(5000); + + // Default behavior: intent results in resolver activity, since there are two potential + // receivers. No intent is received. + synchronized(this) { + assertFalse(mReceivedConfirmationFrom1); + assertFalse(mReceivedConfirmationFrom2); + } + } + + public class ConfirmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(ExampleIntentReceivingActivity1.CONFIRM_ACTION)) { + synchronized (PersistentIntentResolvingTest.this) { + mReceivedConfirmationFrom1 = true; + } + } else if (intent.getAction().equals(ExampleIntentReceivingActivity2 + .CONFIRM_ACTION)) { + synchronized (PersistentIntentResolvingTest.this) { + mReceivedConfirmationFrom2 = true; + } + } + } + } + + private void sendExampleIntent() { + Intent exampleIntent = new Intent(EXAMPLE_ACTION); + exampleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(exampleIntent); + } + + private void addPersistentPreferredActivity() { + IntentFilter filter = new IntentFilter(); + filter.addAction(EXAMPLE_ACTION); + filter.addCategory(Intent.CATEGORY_DEFAULT); + ComponentName targetComponent = new ComponentName(PACKAGE_NAME, + ExampleIntentReceivingActivity2.class.getName()); + mDevicePolicyManager.addPersistentPreferredActivity(ADMIN_RECEIVER_COMPONENT, filter, + targetComponent); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserAdminHelper.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserAdminHelper.java new file mode 100644 index 0000000..7fc0173 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserAdminHelper.java
@@ -0,0 +1,71 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.test.AndroidTestCase; + +/** + * This test executes helper tasks as active device admin in the primary user. Current tasks are + * setting and clearing lockscreen password used by the host side delegated cert installer test. + */ +public class PrimaryUserAdminHelper extends AndroidTestCase { + + private DevicePolicyManager mDpm; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mDpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + } + + /** + * Device admin can only be deactivated by itself and this test should be executed before the + * device admin package can be uninstalled. + */ + public void testClearDeviceAdmin() throws Exception { + ComponentName cn = PrimaryUserDeviceAdmin.ADMIN_RECEIVER_COMPONENT; + if (mDpm.isAdminActive(cn)) { + mDpm.removeActiveAdmin(cn); + // Wait until device admin is not active (with 2 minutes timeout). + for (int i = 0; i < 2 * 60 && mDpm.isAdminActive(cn); i++) { + Thread.sleep(1000); // 1 second. + } + } + assertFalse(mDpm.isAdminActive(cn)); + } + + /** + * Set lockscreen password. + */ + public void testSetPassword() { + // Enable credential storage by setting a nonempty password. + assertTrue(mDpm.resetPassword("test", 0)); + } + + /** + * Clear lockscreen password. + */ + public void testClearPassword() { + mDpm.setPasswordQuality(PrimaryUserDeviceAdmin.ADMIN_RECEIVER_COMPONENT, + DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); + mDpm.setPasswordMinimumLength( + PrimaryUserDeviceAdmin.ADMIN_RECEIVER_COMPONENT, 0); + assertTrue(mDpm.resetPassword("", 0)); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserDeviceAdmin.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserDeviceAdmin.java new file mode 100644 index 0000000..f3c8ff6 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PrimaryUserDeviceAdmin.java
@@ -0,0 +1,29 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.admin.DeviceAdminReceiver; +import android.content.ComponentName; + +/** + * A device admin class running in the primary user. Currently used by delegated cert installer + * test to set a lockscreen password which is prerequisite of installKeyPair(). + */ +public class PrimaryUserDeviceAdmin extends DeviceAdminReceiver { + public static final ComponentName ADMIN_RECEIVER_COMPONENT = new ComponentName( + PrimaryUserDeviceAdmin.class.getPackage().getName(), + PrimaryUserDeviceAdmin.class.getName()); +} \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java new file mode 100644 index 0000000..b5b4fdc --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java
@@ -0,0 +1,34 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.Activity; +import android.content.Intent; + +/** + * Test activity for setScreenCaptureDisabled(). + */ +public class ScreenCaptureDisabledActivity extends Activity { + + static final String ACTIVITY_RESUMED = + "com.android.cts.deviceandprofileowner.ACTIVITY_RESUMED"; + + @Override + protected void onResume() { + super.onResume(); + sendBroadcast(new Intent(ACTIVITY_RESUMED)); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java new file mode 100644 index 0000000..e2deaa4 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
@@ -0,0 +1,99 @@ +/* + * 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.deviceandprofileowner; + +import android.app.admin.DevicePolicyManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.util.Log; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Tests for {@link DevicePolicyManager#setScreenCaptureDisabled} and + * {@link DevicePolicyManager#getScreenCaptureDisabled} APIs. + */ +public class ScreenCaptureDisabledTest extends BaseDeviceAdminTest { + + private static final String TAG = "ScreenCaptureDisabledTest"; + + private ScreenCaptureBroadcastReceiver mReceiver = new ScreenCaptureBroadcastReceiver(); + + protected void setUp() throws Exception { + super.setUp(); + mContext.registerReceiver(mReceiver, new IntentFilter( + ScreenCaptureDisabledActivity.ACTIVITY_RESUMED)); + } + + protected void tearDown() throws Exception { + mContext.unregisterReceiver(mReceiver); + super.tearDown(); + } + + public void testSetScreenCaptureDisabled_false() throws Exception { + mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, false); + assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT)); + assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */)); + startTestActivity(); + assertNotNull(getInstrumentation().getUiAutomation().takeScreenshot()); + } + + public void testSetScreenCaptureDisabled_true() throws Exception { + mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, true); + assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT)); + assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */)); + startTestActivity(); + assertNull(getInstrumentation().getUiAutomation().takeScreenshot()); + } + + public void testScreenCapturePossible() throws Exception { + assertNotNull(getInstrumentation().getUiAutomation().takeScreenshot()); + } + + // We need to launch an activity before trying to take a screen shot, because screenshots are + // only blocked on a per-user basis in the profile owner case depending on the owner of the + // foreground activity. + private void startTestActivity() throws Exception { + Intent launchIntent = new Intent(); + launchIntent.setComponent(new ComponentName(PACKAGE_NAME, + ScreenCaptureDisabledActivity.class.getName())); + launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(launchIntent); + assertTrue(mReceiver.waitForBroadcast()); + Thread.sleep(1000); + } + + private class ScreenCaptureBroadcastReceiver extends BroadcastReceiver { + private final Semaphore mSemaphore = new Semaphore(0); + + @Override + public void onReceive(Context context, Intent intent) { + Log.d(TAG, "Broadcast received"); + mSemaphore.release(); + } + + public boolean waitForBroadcast() throws Exception { + if (mSemaphore.tryAcquire(5, TimeUnit.SECONDS)) { + return true; + } + return false; + } + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionActivity.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionActivity.java new file mode 100644 index 0000000..fed1a79 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionActivity.java
@@ -0,0 +1,81 @@ +/* + * Copyright (C) 2015 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.deviceandprofileowner; + +import android.app.Activity; +import android.app.admin.DevicePolicyManager; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Process; +import android.util.Log; + +/** + * Simple activity that adds or clears a user restriction depending on the value of the extras. + */ +public class UserRestrictionActivity extends Activity { + + private static final String TAG = UserRestrictionActivity.class.getName(); + + private static final String EXTRA_RESTRICTION_KEY = "extra-restriction-key"; + private static final String EXTRA_COMMAND = "extra-command"; + + private static final String ADD_COMMAND = "add-restriction"; + private static final String CLEAR_COMMAND = "clear-restriction"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + handleIntent(getIntent()); + } + + // Overriding this method in case another intent is sent to this activity before finish() + @Override + public void onNewIntent(Intent intent) { + super.onNewIntent(intent); + handleIntent(intent); + } + + @Override + public void onPause() { + super.onPause(); + // Calling finish() here because doing it in onCreate(), onStart() or onResume() makes + // "adb shell am start" timeout if using the -W option. + finish(); + } + + private void handleIntent(Intent intent) { + DevicePolicyManager dpm = (DevicePolicyManager) + getSystemService(Context.DEVICE_POLICY_SERVICE); + String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION_KEY); + String command = intent.getStringExtra(EXTRA_COMMAND); + Log.i(TAG, "Command: \"" + command + "\". Restriction: \"" + restrictionKey + "\""); + + if (ADD_COMMAND.equals(command)) { + dpm.addUserRestriction(BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); + Log.i(TAG, "Added user restriction " + restrictionKey + + " for user " + Process.myUserHandle()); + } else if (CLEAR_COMMAND.equals(command)) { + dpm.clearUserRestriction( + BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); + Log.i(TAG, "Cleared user restriction " + restrictionKey + + " for user " + Process.myUserHandle()); + } else { + Log.e(TAG, "Invalid command: " + command); + } + } + +} \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk index e621933..314f996 100644 --- a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk +++ b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
@@ -26,6 +26,8 @@ LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit +LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner compatibility-device-util_v2 + LOCAL_SDK_VERSION := current include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceOwner/AndroidManifest.xml index dfc7e9c..e424f18 100644 --- a/hostsidetests/devicepolicy/app/DeviceOwner/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/DeviceOwner/AndroidManifest.xml
@@ -21,6 +21,8 @@ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> + <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> + <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <application> <uses-library android:name="android.test.runner" /> @@ -33,22 +35,15 @@ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> - <activity android:name="com.android.cts.deviceowner.ExampleIntentReceivingActivity1"> - <intent-filter> - <action android:name="com.android.cts.deviceowner.EXAMPLE_ACTION" /> - <category android:name="android.intent.category.DEFAULT" /> - </intent-filter> - </activity> - <activity android:name="com.android.cts.deviceowner.ExampleIntentReceivingActivity2"> - <intent-filter> - <action android:name="com.android.cts.deviceowner.EXAMPLE_ACTION" /> - <category android:name="android.intent.category.DEFAULT" /> - </intent-filter> - </activity> + <activity + android:name="com.android.cts.deviceowner.KeyManagementActivity" /> <activity android:name="com.android.cts.deviceowner.LockTaskUtilityActivity" /> + <activity + android:name="com.android.cts.deviceowner.LockTaskUtilityActivityIfWhitelisted" + android:lockTaskMode="if_whitelisted" /> <!-- we need to give a different taskAffinity so that when we use FLAG_ACTIVITY_NEW_TASK, the system tries to start it in a different task @@ -57,11 +52,9 @@ android:name="com.android.cts.deviceowner.LockTaskTest$IntentReceivingActivity" android:taskAffinity="com.android.cts.deviceowner.LockTaskTest.IntentReceivingActivity" /> - <activity - android:name="com.android.cts.deviceowner.ApplicationRestrictionActivity" /> </application> - <instrumentation android:name="android.test.InstrumentationTestRunner" + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="com.android.cts.deviceowner" android:label="Device Owner CTS tests"/> </manifest>
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionActivity.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionActivity.java deleted file mode 100644 index 4d8e4f2..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionActivity.java +++ /dev/null
@@ -1,94 +0,0 @@ -/* - * 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.deviceowner; - -import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Bundle; -import android.os.UserManager; - -/** - * Test activity for setApplicationRestrictions(). - * - * The actual test will set restrictions for this package, and the purpose of this - * activity is to listen for the ACTION_APPLICATION_RESTRICTIONS_CHANGED broadcast - * and relay the retrieved restriction bundle back to the test for validation. - */ -public class ApplicationRestrictionActivity extends Activity { - - // Incoming intent type - public static final String FINISH = "finishActivity"; - - // Outgoing broadcast - public static final String REGISTERED_ACTION = - "com.android.cts.deviceowner.APP_RESTRICTION_REGISTERED"; - public static final String RESTRICTION_ACTION = - "com.android.cts.deviceowner.APP_RESTRICTION_VALUE"; - - private UserManager mUserManager; - - private final BroadcastReceiver mAppRestrictionReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - broadcastRestriction(); - } - }; - - private void broadcastRestriction() { - Bundle restrictions = mUserManager.getApplicationRestrictions(getPackageName()); - Intent intent = new Intent(RESTRICTION_ACTION); - intent.putExtra("value", restrictions); - sendBroadcast(intent); - } - - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - handleIntent(intent); - } - - @Override - protected void onCreate(android.os.Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - handleIntent(getIntent()); - } - - @Override - protected void onResume() { - super.onResume(); - mUserManager = (UserManager) getSystemService(Context.USER_SERVICE); - IntentFilter filter = new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED); - registerReceiver(mAppRestrictionReceiver, filter); - sendBroadcast(new Intent(REGISTERED_ACTION)); - } - - @Override - protected void onPause() { - super.onPause(); - unregisterReceiver(mAppRestrictionReceiver); - } - - private void handleIntent(Intent intent) { - if (intent.getBooleanExtra(FINISH, false)) { - finish(); - } - } - -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionsTest.java deleted file mode 100644 index 5e03de9..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ApplicationRestrictionsTest.java +++ /dev/null
@@ -1,199 +0,0 @@ -/* - * 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.deviceowner; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Bundle; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -/** - * Functionality tests for setApplicationRestrictions and getApplicationRestrictions - * in DevicePolicyManager. - * - * First of all, these two APIs are executed locally to assert that what you set - * can later be retrieved via the getter. It also fires up an external activity - * (which runs in com.google.android.xts.gmscore, unlike the test code itself - * which runs in the test target package com.google.android.gms due to - * instrumentation) to observe an application's view of its restrictions. - * The activity listens to ACTION_APPLICATION_RESTRICTIONS_CHANGED broadcast - * which is fired by the system whenever its restriction is modified, - * and relays the value back to this test for verification. - */ -public class ApplicationRestrictionsTest extends BaseDeviceOwnerTest { - - private static final String[] testStrings = new String[] { - "<bad/>", - ">worse!\"£$%^&*()'<", - "<JSON>\"{ \\\"One\\\": { \\\"OneOne\\\": \\\"11\\\", \\\"" - + "OneTwo\\\": \\\"12\\\" }, \\\"Two\\\": \\\"2\\\" } <JSON/>\"" - }; - - private final Semaphore mOnRegisteredSemaphore = new Semaphore(0); - private final Semaphore mOnRestrictionSemaphore = new Semaphore(0); - private Bundle mReceivedRestrictions; - - @Override - protected void setUp() throws Exception { - super.setUp(); - IntentFilter filter = new IntentFilter(); - filter.addAction(ApplicationRestrictionActivity.REGISTERED_ACTION); - filter.addAction(ApplicationRestrictionActivity.RESTRICTION_ACTION); - mContext.registerReceiver(mReceiver, filter); - } - - @Override - protected void tearDown() throws Exception { - mContext.unregisterReceiver(mReceiver); - super.tearDown(); - } - - public void testSetApplicationRestrictions() { - final String CTS_PACKAGE = PACKAGE_NAME; - final String OTHER_PACKAGE = CTS_PACKAGE + "dummy"; - - startAndWait(); - - Bundle bundle0 = createBundle0(); - Bundle bundle1 = createBundle1(); - - // Test setting restrictions - mDevicePolicyManager.setApplicationRestrictions(getWho(), CTS_PACKAGE, bundle0); - mDevicePolicyManager.setApplicationRestrictions(getWho(), OTHER_PACKAGE, bundle1); - - // Retrieve restrictions locally and make sure they are what we put in. - assertBundle0(mDevicePolicyManager.getApplicationRestrictions(getWho(), CTS_PACKAGE)); - assertBundle1(mDevicePolicyManager.getApplicationRestrictions(getWho(), OTHER_PACKAGE)); - - // The test activity should have received a change_restriction broadcast - // and relay the value back to us. - assertBundle0(waitForChangedRestriction()); - - // Test overwriting - mDevicePolicyManager.setApplicationRestrictions(getWho(), CTS_PACKAGE, bundle1); - assertBundle1(mDevicePolicyManager.getApplicationRestrictions(getWho(), CTS_PACKAGE)); - assertBundle1(waitForChangedRestriction()); - - // Cleanup - mDevicePolicyManager.setApplicationRestrictions(getWho(), CTS_PACKAGE, new Bundle()); - assertTrue( - mDevicePolicyManager.getApplicationRestrictions(getWho(), CTS_PACKAGE).isEmpty()); - assertTrue(waitForChangedRestriction().isEmpty()); - mDevicePolicyManager.setApplicationRestrictions(getWho(), OTHER_PACKAGE, new Bundle()); - assertTrue( - mDevicePolicyManager.getApplicationRestrictions(getWho(), OTHER_PACKAGE).isEmpty()); - - finish(); - } - - // Should be consistent with assertBundle0 - private Bundle createBundle0() { - Bundle result = new Bundle(); - // Tests for four allowed types: Integer, Boolean, String and String[] - // Also test for string escaping handling - result.putBoolean("boolean_0", false); - result.putBoolean("boolean_1", true); - result.putInt("integer", 0x7fffffff); - // If a null is stored, "" will be read back - result.putString("empty", ""); - result.putString("string", "text"); - result.putStringArray("string[]", testStrings); - return result; - } - - // Should be consistent with createBundle0 - private void assertBundle0(Bundle bundle) { - assertEquals(6, bundle.size()); - assertEquals(false, bundle.getBoolean("boolean_0")); - assertEquals(true, bundle.getBoolean("boolean_1")); - assertEquals(0x7fffffff, bundle.getInt("integer")); - assertEquals("", bundle.getString("empty")); - assertEquals("text", bundle.getString("string")); - - String[] strings = bundle.getStringArray("string[]"); - assertTrue(strings != null && strings.length == testStrings.length); - for (int i = 0; i < strings.length; i++) { - assertEquals(strings[i], testStrings[i]); - } - } - - // Should be consistent with assertBundle1 - private Bundle createBundle1() { - Bundle result = new Bundle(); - result.putInt("dummy", 1); - return result; - } - - // Should be consistent with createBundle1 - private void assertBundle1(Bundle bundle) { - assertEquals(1, bundle.size()); - assertEquals(1, bundle.getInt("dummy")); - } - - private final BroadcastReceiver mReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (ApplicationRestrictionActivity.REGISTERED_ACTION.equals(action)) { - mOnRegisteredSemaphore.release(); - } else if (ApplicationRestrictionActivity.RESTRICTION_ACTION.equals(action)) { - mReceivedRestrictions = intent.getBundleExtra("value"); - mOnRestrictionSemaphore.release(); - } - } - }; - - private void startTestActivity(String command) { - Intent intent = new Intent(); - intent.setClassName(PACKAGE_NAME, ApplicationRestrictionActivity.class.getName()); - intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - - if (command != null) { - intent.putExtra(command, true); - } - mContext.startActivity(intent); - } - - private void startAndWait() { - startTestActivity(null); - // Wait until the activity has registered its broadcast receiver and ready for incoming - // restriction changes. - try { - assertTrue(mOnRegisteredSemaphore.tryAcquire(5, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - fail("Start ApplicationRestrictionActivity interrupted"); - } - } - - private Bundle waitForChangedRestriction() { - try { - assertTrue(mOnRestrictionSemaphore.tryAcquire(5, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - fail("getRestrictionsAndWait() interrupted"); - } - - return mReceivedRestrictions; - } - - private void finish() { - startTestActivity(ApplicationRestrictionActivity.FINISH); - } - -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BaseDeviceOwnerTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BaseDeviceOwnerTest.java index e4f5134b..b6815fd 100644 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BaseDeviceOwnerTest.java +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/BaseDeviceOwnerTest.java
@@ -19,6 +19,9 @@ import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Process; import android.test.AndroidTestCase; /** @@ -32,6 +35,14 @@ public class BaseDeviceOwnerTest extends AndroidTestCase { public static class BasicAdminReceiver extends DeviceAdminReceiver { + @Override + public String onChoosePrivateKeyAlias(Context context, Intent intent, int uid, Uri uri, + String suggestedAlias) { + if (uid != Process.myUid() || uri == null) { + return null; + } + return uri.getQueryParameter("alias"); + } } public static final String PACKAGE_NAME = BaseDeviceOwnerTest.class.getPackage().getName(); @@ -44,11 +55,16 @@ mDevicePolicyManager = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); - assertTrue(mDevicePolicyManager.isAdminActive(getWho())); - assertTrue(mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME)); + assertDeviceOwner(mDevicePolicyManager); } - public static ComponentName getWho() { + static void assertDeviceOwner(DevicePolicyManager dpm) { + assertNotNull(dpm); + assertTrue(dpm.isAdminActive(getWho())); + assertTrue(dpm.isDeviceOwnerApp(PACKAGE_NAME)); + } + + protected static ComponentName getWho() { return new ComponentName(PACKAGE_NAME, BasicAdminReceiver.class.getName()); } -} \ No newline at end of file +}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity1.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity1.java deleted file mode 100644 index 03ca9a4..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity1.java +++ /dev/null
@@ -1,34 +0,0 @@ -/* - * 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.deviceowner; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; - -public class ExampleIntentReceivingActivity1 extends Activity { - public static final String CONFIRM_ACTION = "com.android.cts.deviceowner.CONFIRM_1"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getIntent().getAction().equals(PersistentIntentResolvingTest.EXAMPLE_ACTION)) { - sendBroadcast(new Intent(CONFIRM_ACTION)); - } - finish(); - } -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity2.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity2.java deleted file mode 100644 index 65ccb36..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ExampleIntentReceivingActivity2.java +++ /dev/null
@@ -1,34 +0,0 @@ -/* - * 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.deviceowner; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; - -public class ExampleIntentReceivingActivity2 extends Activity { - public static final String CONFIRM_ACTION = "com.android.cts.deviceowner.CONFIRM_2"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getIntent().getAction().equals(PersistentIntentResolvingTest.EXAMPLE_ACTION)) { - sendBroadcast(new Intent(CONFIRM_ACTION)); - } - finish(); - } -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementActivity.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementActivity.java new file mode 100644 index 0000000..c108d24 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementActivity.java
@@ -0,0 +1,30 @@ +/* + * 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.deviceowner; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +public class KeyManagementActivity extends Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + finish(); + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementTest.java index fe2bdda..5774b0c 100644 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementTest.java +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/KeyManagementTest.java
@@ -15,11 +15,21 @@ */ package com.android.cts.deviceowner; +import static com.android.cts.deviceowner.BaseDeviceOwnerTest.getWho; import static com.android.cts.deviceowner.FakeKeys.FAKE_RSA_1; +import android.app.Activity; import android.app.admin.DevicePolicyManager; +import android.net.Uri; +import android.os.Handler; +import android.security.KeyChain; +import android.security.KeyChainAliasCallback; +import android.security.KeyChainException; +import android.test.ActivityInstrumentationTestCase2; import java.io.ByteArrayInputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.Certificate; @@ -28,17 +38,38 @@ import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; -public class KeyManagementTest extends BaseDeviceOwnerTest { +import android.content.ComponentName; +import android.content.Context; + +public class KeyManagementTest extends + ActivityInstrumentationTestCase2<KeyManagementActivity> { + + private static final int KEYCHAIN_TIMEOUT_MS = 8000; + private DevicePolicyManager mDevicePolicyManager; + + public KeyManagementTest() { + super(KeyManagementActivity.class); + } @Override protected void setUp() throws Exception { super.setUp(); + + // Confirm our DeviceOwner is set up + mDevicePolicyManager = (DevicePolicyManager) + getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE); + BaseDeviceOwnerTest.assertDeviceOwner(mDevicePolicyManager); + + // Enable credential storage by setting a nonempty password. assertTrue(mDevicePolicyManager.resetPassword("test", 0)); } @Override protected void tearDown() throws Exception { + // Delete all keys by resetting our password to null, which clears the keystore. mDevicePolicyManager.setPasswordQuality(getWho(), DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); mDevicePolicyManager.setPasswordMinimumLength(getWho(), 0); @@ -47,27 +78,32 @@ } public void testCanInstallValidRsaKeypair() - throws CertificateException, NoSuchAlgorithmException, InvalidKeySpecException { + throws CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, + KeyChainException, InterruptedException, UnsupportedEncodingException { final String alias = "com.android.test.valid-rsa-key-1"; final PrivateKey privKey = getPrivateKey(FAKE_RSA_1.privateKey , "RSA"); final Certificate cert = getCertificate(FAKE_RSA_1.caCertificate); assertTrue(mDevicePolicyManager.installKeyPair(getWho(), privKey, cert, alias)); + + assertEquals(alias, new KeyChainAliasFuture(alias).get()); + final PrivateKey retrievedKey = KeyChain.getPrivateKey(getActivity(), alias); + assertEquals(retrievedKey.getAlgorithm(), "RSA"); } - public void testNullKeyParamsFailGracefully() + public void testNullKeyParamsFailPredictably() throws CertificateException, NoSuchAlgorithmException, InvalidKeySpecException { final String alias = "com.android.test.null-key-1"; final PrivateKey privKey = getPrivateKey(FAKE_RSA_1.privateKey, "RSA"); final Certificate cert = getCertificate(FAKE_RSA_1.caCertificate); try { - assertFalse(mDevicePolicyManager.installKeyPair(getWho(), null, cert, alias)); - } catch (NullPointerException accept) { - // Accept either false return value or NPE + mDevicePolicyManager.installKeyPair(getWho(), null, cert, alias); + fail("Exception should have been thrown for null PrivateKey"); + } catch (NullPointerException expected) { } try { - assertFalse(mDevicePolicyManager.installKeyPair(getWho(), privKey, null, alias)); - } catch (NullPointerException accept) { - // Accept either false return value or NPE + mDevicePolicyManager.installKeyPair(getWho(), privKey, null, alias); + fail("Exception should have been thrown for null Certificate"); + } catch (NullPointerException expected) { } } @@ -77,21 +113,46 @@ final PrivateKey privKey = getPrivateKey(FAKE_RSA_1.privateKey, "RSA"); final Certificate cert = getCertificate(FAKE_RSA_1.caCertificate); try { - assertFalse(mDevicePolicyManager.installKeyPair(null, privKey, cert, alias)); + mDevicePolicyManager.installKeyPair(null, privKey, cert, alias); fail("Exception should have been thrown for null ComponentName"); - } catch (SecurityException | NullPointerException expected) { + } catch (SecurityException expected) { } } - PrivateKey getPrivateKey(final byte[] key, String type) + private static PrivateKey getPrivateKey(final byte[] key, String type) throws NoSuchAlgorithmException, InvalidKeySpecException { return KeyFactory.getInstance(type).generatePrivate( new PKCS8EncodedKeySpec(key)); } - Certificate getCertificate(byte[] cert) throws CertificateException { + private static Certificate getCertificate(byte[] cert) throws CertificateException { return CertificateFactory.getInstance("X.509").generateCertificate( new ByteArrayInputStream(cert)); } + private class KeyChainAliasFuture implements KeyChainAliasCallback { + private final CountDownLatch mLatch = new CountDownLatch(1); + private String mChosenAlias = null; + + @Override + public void alias(final String chosenAlias) { + mChosenAlias = chosenAlias; + mLatch.countDown(); + } + + public KeyChainAliasFuture(String alias) throws UnsupportedEncodingException { + /* Pass the alias as a GET to an imaginary server instead of explicitly asking for it, + * to make sure the DPC actually has to do some work to grant the cert. + */ + final Uri uri = + Uri.parse("https://example.org/?alias=" + URLEncoder.encode(alias, "UTF-8")); + KeyChain.choosePrivateKeyAlias(getActivity(), this, + null /* keyTypes */, null /* issuers */, uri, null /* alias */); + } + + public String get() throws InterruptedException { + assertTrue("Chooser timeout", mLatch.await(KEYCHAIN_TIMEOUT_MS, TimeUnit.MILLISECONDS)); + return mChosenAlias; + } + }; }
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskTest.java index 69c5bf7..f6f8dbbc 100644 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskTest.java +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskTest.java
@@ -18,6 +18,7 @@ import android.app.Activity; import android.app.ActivityManager; import android.content.BroadcastReceiver; +import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; @@ -32,12 +33,24 @@ private static final String TEST_PACKAGE = "com.google.android.example.somepackage"; + private static final String UTILITY_ACTIVITY + = "com.android.cts.deviceowner.LockTaskUtilityActivity"; + private static final String UTILITY_ACTIVITY_IF_WHITELISTED + = "com.android.cts.deviceowner.LockTaskUtilityActivityIfWhitelisted"; + + private static final String RECEIVING_ACTIVITY_PACKAGE_NAME + = "com.android.cts.intent.receiver"; + private static final String RECEIVING_ACTIVITY_NAME + = "com.android.cts.intent.receiver.IntentReceiverActivity"; + private static final String ACTION_JUST_CREATE = + "com.android.cts.action.JUST_CREATE"; + private static final int ACTIVITY_RESUMED_TIMEOUT_MILLIS = 20000; // 20 seconds private static final int ACTIVITY_RUNNING_TIMEOUT_MILLIS = 10000; // 10 seconds private static final int ACTIVITY_DESTROYED_TIMEOUT_MILLIS = 60000; // 60 seconds - + private static final int UPDATE_LOCK_TASK_TIMEOUT_MILLIS = 1000; // 1 second public static final String RECEIVING_ACTIVITY_CREATED_ACTION - = "com.android.cts.deviceowner.RECEIVER_ACTIVITY_STARTED_ACTION"; + = "com.android.cts.deviceowner.RECEIVING_ACTIVITY_CREATED_ACTION"; /** * The tests below need to keep detailed track of the state of the activity * that is started and stopped frequently. To do this it sends a number of @@ -102,9 +115,13 @@ private final Object mReceivingActivityCreatedLock = new Object(); private Boolean mIntentHandled; + private ActivityManager mActivityManager; + @Override protected void setUp() throws Exception { super.setUp(); + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[0]); + mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); IntentFilter filter = new IntentFilter(); filter.addAction(LockTaskUtilityActivity.CREATE_ACTION); filter.addAction(LockTaskUtilityActivity.DESTROY_ACTION); @@ -117,10 +134,12 @@ @Override protected void tearDown() throws Exception { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[0]); mContext.unregisterReceiver(mReceiver); super.tearDown(); } + // Setting and unsetting the lock task packages. public void testSetLockTaskPackages() { mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { TEST_PACKAGE }); assertTrue(mDevicePolicyManager.isLockTaskPermitted(TEST_PACKAGE)); @@ -132,45 +151,60 @@ // Start lock task, verify that ActivityManager knows thats what is going on. public void testStartLockTask() { mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); - startLockTask(); + startLockTask(UTILITY_ACTIVITY); waitForResume(); // Verify that activity open and activity manager is in lock task. - ActivityManager activityManager = (ActivityManager) - mContext.getSystemService(Context.ACTIVITY_SERVICE); - assertTrue(activityManager.isInLockTaskMode()); + assertLockTaskModeActive(); assertTrue(mIsActivityRunning); assertTrue(mIsActivityResumed); - stopAndFinish(activityManager); + stopAndFinish(UTILITY_ACTIVITY); } // Verifies that the act of finishing is blocked by ActivityManager in lock task. // This results in onDestroy not being called until stopLockTask is called before finish. public void testCannotFinish() { mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); - startLockTask(); + startLockTask(UTILITY_ACTIVITY); // If lock task has not exited then the activity shouldn't actually receive onDestroy. - finishAndWait(); - ActivityManager activityManager = (ActivityManager) - mContext.getSystemService(Context.ACTIVITY_SERVICE); - assertTrue(activityManager.isInLockTaskMode()); + finishAndWait(UTILITY_ACTIVITY); + assertLockTaskModeActive(); assertTrue(mIsActivityRunning); - stopAndFinish(activityManager); + stopAndFinish(UTILITY_ACTIVITY); + } + + // Verifies that updating the whitelisting during lock task mode finishes the locked task. + public void testUpdateWhitelisting() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); + startLockTask(UTILITY_ACTIVITY); + + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[0]); + + synchronized (mActivityRunningLock) { + try { + mActivityRunningLock.wait(UPDATE_LOCK_TASK_TIMEOUT_MILLIS); + } catch (InterruptedException e) { + } + } + + assertLockTaskModeInactive(); + assertFalse(mIsActivityRunning); + assertFalse(mIsActivityResumed); } // This launches an activity that is in the current task. - // this should be permitted as a part of lock task (since it isn't a new task). - public void testStartActivityWithinTask() { + // This should always be permitted as a part of lock task (since it isn't a new task). + public void testStartActivity_withinTask() { mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); - startLockTask(); + startLockTask(UTILITY_ACTIVITY); waitForResume(); mReceivingActivityWasCreated = false; - Intent launchIntent = new Intent(mContext, IntentReceivingActivity.class); - Intent lockTaskUtility = getLockTaskUtility(); + Intent launchIntent = getIntentReceivingActivityIntent(0); + Intent lockTaskUtility = getLockTaskUtility(UTILITY_ACTIVITY); lockTaskUtility.putExtra(LockTaskUtilityActivity.START_ACTIVITY, launchIntent); mContext.startActivity(lockTaskUtility); @@ -181,18 +215,19 @@ } assertTrue(mReceivingActivityWasCreated); } - stopAndFinish(null); + stopAndFinish(UTILITY_ACTIVITY); } - // This launches an activity that is not part of the current task and therefore - // should be blocked. - public void testCannotStartActivityOutsideTask() { - mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); - startLockTask(); + // This launches a whitelisted activity that is not part of the current task. + // This should be permitted as a part of lock task. + public void testStartActivity_outsideTaskWhitelisted() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME, + RECEIVING_ACTIVITY_PACKAGE_NAME }); + startLockTask(UTILITY_ACTIVITY); waitForResume(); mReceivingActivityWasCreated = false; - Intent launchIntent = new Intent(mContext, IntentReceivingActivity.class); + Intent launchIntent = getIntentReceivingActivityIntent(0); launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(launchIntent); synchronized (mReceivingActivityCreatedLock) { @@ -200,9 +235,108 @@ mReceivingActivityCreatedLock.wait(ACTIVITY_RESUMED_TIMEOUT_MILLIS); } catch (InterruptedException e) { } + assertTrue(mReceivingActivityWasCreated); + } + stopAndFinish(UTILITY_ACTIVITY); + } + + // This launches a non-whitelisted activity that is not part of the current task. + // This should be blocked. + public void testStartActivity_outsideTaskNonWhitelisted() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); + startLockTask(UTILITY_ACTIVITY); + waitForResume(); + + Intent launchIntent = getIntentReceivingActivityIntent(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(launchIntent); + synchronized (mActivityResumedLock) { + try { + mActivityResumedLock.wait(ACTIVITY_RESUMED_TIMEOUT_MILLIS); + } catch (InterruptedException e) { + } assertFalse(mReceivingActivityWasCreated); } - stopAndFinish(null); + stopAndFinish(UTILITY_ACTIVITY); + } + + // Test the lockTaskMode flag for an activity declaring if_whitelisted. + // Whitelist the activity and verify that lock task mode is started. + public void testManifestArgument_whitelisted() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); + startAndWait(getLockTaskUtility(UTILITY_ACTIVITY_IF_WHITELISTED)); + waitForResume(); + + assertLockTaskModeActive(); + assertTrue(mIsActivityRunning); + assertTrue(mIsActivityResumed); + + stopAndFinish(UTILITY_ACTIVITY_IF_WHITELISTED); + } + + // Test the lockTaskMode flag for an activity declaring if_whitelisted. + // Don't whitelist the activity and verify that lock task mode is not started. + public void testManifestArgument_nonWhitelisted() { + startAndWait(getLockTaskUtility(UTILITY_ACTIVITY_IF_WHITELISTED)); + waitForResume(); + + assertLockTaskModeInactive(); + assertTrue(mIsActivityRunning); + assertTrue(mIsActivityResumed); + + stopAndFinish(UTILITY_ACTIVITY_IF_WHITELISTED); + } + + // Test the lockTaskMode flag for an activity declaring if_whitelisted. + // An activity locked via manifest argument cannot finish without calling stopLockTask. + public void testManifestArgument_cannotFinish() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); + startAndWait(getLockTaskUtility(UTILITY_ACTIVITY_IF_WHITELISTED)); + waitForResume(); + + // If lock task has not exited then the activity shouldn't actually receive onDestroy. + finishAndWait(UTILITY_ACTIVITY_IF_WHITELISTED); + assertLockTaskModeActive(); + assertTrue(mIsActivityRunning); + + stopAndFinish(UTILITY_ACTIVITY_IF_WHITELISTED); + } + + // Test the lockTaskMode flag for an activity declaring if_whitelisted. + // Verifies that updating the whitelisting during lock task mode finishes the locked task. + public void testManifestArgument_updateWhitelisting() { + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[] { PACKAGE_NAME }); + startAndWait(getLockTaskUtility(UTILITY_ACTIVITY_IF_WHITELISTED)); + waitForResume(); + + mDevicePolicyManager.setLockTaskPackages(getWho(), new String[0]); + + synchronized (mActivityRunningLock) { + try { + mActivityRunningLock.wait(UPDATE_LOCK_TASK_TIMEOUT_MILLIS); + } catch (InterruptedException e) { + } + } + + assertLockTaskModeInactive(); + assertFalse(mIsActivityRunning); + assertFalse(mIsActivityResumed); + } + + /** + * Checks that lock task mode is active and fails the test if it isn't. + */ + private void assertLockTaskModeActive() { + assertTrue(mActivityManager.isInLockTaskMode()); + assertEquals(ActivityManager.LOCK_TASK_MODE_LOCKED, + mActivityManager.getLockTaskModeState()); + } + + /** + * Checks that lock task mode is not active and fails the test if it is. + */ + private void assertLockTaskModeInactive() { + assertFalse(mActivityManager.isInLockTaskMode()); + assertEquals(ActivityManager.LOCK_TASK_MODE_NONE, mActivityManager.getLockTaskModeState()); } /** @@ -213,12 +347,10 @@ * If activityManager is not null then verify that the ActivityManager * is no longer in lock task mode. */ - private void stopAndFinish(ActivityManager activityManager) { - stopLockTask(); - finishAndWait(); - if (activityManager != null) { - assertFalse(activityManager.isInLockTaskMode()); - } + private void stopAndFinish(String className) { + stopLockTask(className); + finishAndWait(className); + assertLockTaskModeInactive(); assertFalse(mIsActivityRunning); } @@ -226,9 +358,9 @@ * Call finish on the LockTaskUtilityActivity and wait for * onDestroy to be called. */ - private void finishAndWait() { + private void finishAndWait(String className) { synchronized (mActivityRunningLock) { - finish(); + finish(className); if (mIsActivityRunning) { try { mActivityRunningLock.wait(ACTIVITY_DESTROYED_TIMEOUT_MILLIS); @@ -256,8 +388,8 @@ /** * Calls startLockTask on the LockTaskUtilityActivity */ - private void startLockTask() { - Intent intent = getLockTaskUtility(); + private void startLockTask(String className) { + Intent intent = getLockTaskUtility(className); intent.putExtra(LockTaskUtilityActivity.START_LOCK_TASK, true); startAndWait(intent); } @@ -265,8 +397,8 @@ /** * Calls stopLockTask on the LockTaskUtilityActivity */ - private void stopLockTask() { - Intent intent = getLockTaskUtility(); + private void stopLockTask(String className) { + Intent intent = getLockTaskUtility(className); intent.putExtra(LockTaskUtilityActivity.STOP_LOCK_TASK, true); startAndWait(intent); } @@ -274,8 +406,8 @@ /** * Calls finish on the LockTaskUtilityActivity */ - private void finish() { - Intent intent = getLockTaskUtility(); + private void finish(String className) { + Intent intent = getLockTaskUtility(className); intent.putExtra(LockTaskUtilityActivity.FINISH, true); startAndWait(intent); } @@ -303,10 +435,19 @@ * * This intent includes the flags to make it act as single top. */ - private Intent getLockTaskUtility() { + private Intent getLockTaskUtility(String className) { Intent intent = new Intent(); - intent.setClassName(PACKAGE_NAME, LockTaskUtilityActivity.class.getName()); + intent.setClassName(PACKAGE_NAME, className); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } + + private Intent getIntentReceivingActivityIntent(int flags) { + Intent intent = new Intent(); + intent.setComponent( + new ComponentName(RECEIVING_ACTIVITY_PACKAGE_NAME, RECEIVING_ACTIVITY_NAME)); + intent.setAction(ACTION_JUST_CREATE); + intent.setFlags(flags); + return intent; + } }
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskUtilityActivityIfWhitelisted.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskUtilityActivityIfWhitelisted.java new file mode 100644 index 0000000..4cf6efa --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskUtilityActivityIfWhitelisted.java
@@ -0,0 +1,20 @@ +/* + * Copyright (C) 2015 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.deviceowner; + +public class LockTaskUtilityActivityIfWhitelisted extends LockTaskUtilityActivity { +}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PersistentIntentResolvingTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PersistentIntentResolvingTest.java deleted file mode 100644 index fcef05f..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PersistentIntentResolvingTest.java +++ /dev/null
@@ -1,126 +0,0 @@ -/* - * 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.deviceowner; - -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.SystemClock; - -public class PersistentIntentResolvingTest extends BaseDeviceOwnerTest { - public static final String EXAMPLE_ACTION = "com.android.cts.deviceowner.EXAMPLE_ACTION"; - - private boolean mReceivedConfirmationFrom1; - private boolean mReceivedConfirmationFrom2; - private BroadcastReceiver mReceiver; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - IntentFilter filter = new IntentFilter(); - filter.addAction(ExampleIntentReceivingActivity1.CONFIRM_ACTION); - filter.addAction(ExampleIntentReceivingActivity2.CONFIRM_ACTION); - - mReceiver = new ConfirmReceiver(); - mContext.registerReceiver(mReceiver, filter); - - synchronized(this) { - mReceivedConfirmationFrom1 = false; - mReceivedConfirmationFrom2 = false; - } - } - - @Override - protected void tearDown() throws Exception { - mDevicePolicyManager.clearPackagePersistentPreferredActivities(getWho(), PACKAGE_NAME); - mContext.unregisterReceiver(mReceiver); - - super.tearDown(); - } - - public void testNoPersistentPreferredActivityYieldsResolverActivity() { - sendExampleIntent(); - SystemClock.sleep(5000); - - // Default behavior: intent results in resolver activity, since there are two potential - // receivers. No intent is received. - synchronized(this) { - assertFalse(mReceivedConfirmationFrom1); - assertFalse(mReceivedConfirmationFrom2); - } - } - - public void testAddPersistentPreferredActivityYieldsReceptionAtTarget() { - addPersistentPreferredActivity(); - sendExampleIntent(); - SystemClock.sleep(5000); - - // Persistent preferred activity present: intent should be received by activity 2. - synchronized(this) { - assertFalse(mReceivedConfirmationFrom1); - assertTrue(mReceivedConfirmationFrom2); - } - } - - public void testAddAndClearPersistentPreferredActivitiesYieldsResolverActivity() { - addPersistentPreferredActivity(); - mDevicePolicyManager.clearPackagePersistentPreferredActivities(getWho(), PACKAGE_NAME); - - sendExampleIntent(); - SystemClock.sleep(5000); - - // Default behavior: intent results in resolver activity, since there are two potential - // receivers. No intent is received. - synchronized(this) { - assertFalse(mReceivedConfirmationFrom1); - assertFalse(mReceivedConfirmationFrom2); - } - } - - public class ConfirmReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(ExampleIntentReceivingActivity1.CONFIRM_ACTION)) { - synchronized (PersistentIntentResolvingTest.this) { - mReceivedConfirmationFrom1 = true; - } - } else if (intent.getAction().equals(ExampleIntentReceivingActivity2 - .CONFIRM_ACTION)) { - synchronized (PersistentIntentResolvingTest.this) { - mReceivedConfirmationFrom2 = true; - } - } - } - } - - private void sendExampleIntent() { - Intent exampleIntent = new Intent(EXAMPLE_ACTION); - exampleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - mContext.startActivity(exampleIntent); - } - - private void addPersistentPreferredActivity() { - IntentFilter filter = new IntentFilter(); - filter.addAction(EXAMPLE_ACTION); - filter.addCategory(Intent.CATEGORY_DEFAULT); - ComponentName targetComponent = new ComponentName(PACKAGE_NAME, - ExampleIntentReceivingActivity2.class.getName()); - mDevicePolicyManager.addPersistentPreferredActivity(getWho(), filter, targetComponent); - } -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ScreenCaptureDisabledTest.java deleted file mode 100644 index 59b9773..0000000 --- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/ScreenCaptureDisabledTest.java +++ /dev/null
@@ -1,45 +0,0 @@ -/* - * 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.deviceowner; - -import android.app.admin.DevicePolicyManager; - -/** - * Tests for {@link DevicePolicyManager#setScreenCaptureDisabled} and - * {@link DevicePolicyManager#getScreenCaptureDisabled} APIs. - */ -public class ScreenCaptureDisabledTest extends BaseDeviceOwnerTest { - - public void testSetScreenCaptureDisabled_false() throws Exception { - mDevicePolicyManager.setScreenCaptureDisabled(getWho(), false); - assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(getWho())); - } - - public void testSetScreenCaptureDisabled_true() throws Exception { - mDevicePolicyManager.setScreenCaptureDisabled(getWho(), true); - assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(getWho())); - } - - public void testSetScreenCaptureDisabled_anyAdminTrue() { - mDevicePolicyManager.setScreenCaptureDisabled(getWho(), true); - assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */)); - } - - public void testSetScreenCaptureDisabled_anyAdminFalse() { - mDevicePolicyManager.setScreenCaptureDisabled(getWho(), false); - assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */)); - } -}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java new file mode 100644 index 0000000..ac96e0b --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java
@@ -0,0 +1,141 @@ +/* + * Copyright (C) 2015 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.deviceowner; + +import android.app.admin.DevicePolicyManager; +import android.app.admin.SystemUpdatePolicy; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Build; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Test {@link SystemUpdatePolicy}, {@link DevicePolicyManager#setSystemUpdatePolicy} and + * {@link DevicePolicyManager#getSystemUpdatePolicy} + */ +public class SystemUpdatePolicyTest extends BaseDeviceOwnerTest { + + private static final int TIMEOUT_MS = 20_000; + + private final Semaphore mPolicyChangedSemaphore = new Semaphore(0); + private final BroadcastReceiver policyChangedReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context arg0, Intent arg1) { + mPolicyChangedSemaphore.release(); + } + }; + private boolean mHasFeature; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mHasFeature = Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; + + if (mHasFeature) { + IntentFilter filter = new IntentFilter(); + filter.addAction(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED); + mContext.registerReceiver(policyChangedReceiver, filter); + } + } + + @Override + protected void tearDown() throws Exception { + if (mHasFeature) { + mContext.unregisterReceiver(policyChangedReceiver); + mDevicePolicyManager.setSystemUpdatePolicy(getWho(), null); + } + super.tearDown(); + } + + public void testSetEmptytInstallPolicy() { + if (!mHasFeature) { + return; + } + testPolicy(null); + } + + public void testSetAutomaticInstallPolicy() { + if (!mHasFeature) { + return; + } + testPolicy(SystemUpdatePolicy.createAutomaticInstallPolicy()); + } + + public void testSetWindowedInstallPolicy() { + if (!mHasFeature) { + return; + } + testPolicy(SystemUpdatePolicy.createWindowedInstallPolicy(0, 720)); + } + + public void testSetPostponeInstallPolicy() { + if (!mHasFeature) { + return; + } + testPolicy(SystemUpdatePolicy.createPostponeInstallPolicy()); + } + + public void testShouldFailInvalidWindowPolicy() throws Exception { + if (!mHasFeature) { + return; + } + try { + SystemUpdatePolicy.createWindowedInstallPolicy(24 * 60 + 1, 720); + fail("Invalid window start should not be accepted."); + } catch (IllegalArgumentException expected) { } + try { + SystemUpdatePolicy.createWindowedInstallPolicy(-1, 720); + fail("Invalid window start should not be accepted."); + } catch (IllegalArgumentException expected) { } + try { + SystemUpdatePolicy.createWindowedInstallPolicy(0, 24 * 60 + 1); + fail("Invalid window end should not be accepted."); + } catch (IllegalArgumentException expected) { } + try { + SystemUpdatePolicy.createWindowedInstallPolicy(0, -1); + fail("Invalid window end should not be accepted."); + } catch (IllegalArgumentException expected) { } + } + + private void testPolicy(SystemUpdatePolicy policy) { + mDevicePolicyManager.setSystemUpdatePolicy(getWho(), policy); + waitForBroadcast(); + SystemUpdatePolicy newPolicy = mDevicePolicyManager.getSystemUpdatePolicy(); + if (policy == null) { + assertNull(newPolicy); + } else { + assertNotNull(newPolicy); + assertEquals(policy.toString(), newPolicy.toString()); + assertEquals(policy.getPolicyType(), newPolicy.getPolicyType()); + if (policy.getPolicyType() == SystemUpdatePolicy.TYPE_INSTALL_WINDOWED) { + assertEquals(policy.getInstallWindowStart(), newPolicy.getInstallWindowStart()); + assertEquals(policy.getInstallWindowEnd(), newPolicy.getInstallWindowEnd()); + } + } + } + private void waitForBroadcast() { + try { + assertTrue("Timeout while waiting for broadcast.", + mPolicyChangedSemaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS)); + } catch (InterruptedException e) { + fail("Interrupted while waiting for broadcast."); + } + } +}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java new file mode 100644 index 0000000..1627961 --- /dev/null +++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
@@ -0,0 +1,185 @@ +/* + * Copyright (C) 2015 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.deviceowner; + +import android.content.Context; +import android.content.Intent; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.provider.Settings; + +import com.android.compatibility.common.util.WifiConfigCreator; + +import java.util.List; + +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_PASSWORD; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SECURITY_TYPE; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_NONE; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_WPA; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_UPDATE_WIFI_CONFIG; + +/** + * Testing WiFi configuration lockdown by Device Owner + */ +public class WifiConfigLockdownTest extends BaseDeviceOwnerTest { + private static final String TAG = "WifiConfigLockdownTest"; + private static final String ORIGINAL_DEVICE_OWNER_SSID = "DOCTSTest"; + private static final String CHANGED_DEVICE_OWNER_SSID = "DOChangedCTSTest"; + private static final String ORIGINAL_REGULAR_SSID = "RegularCTSTest"; + private static final String CHANGED_REGULAR_SSID = "RegularChangedCTSTest"; + private static final String ORIGINAL_PASSWORD = "originalpassword"; + private WifiManager mWifiManager; + private WifiConfigCreator mConfigCreator; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); + mConfigCreator = new WifiConfigCreator(mContext); + mDevicePolicyManager.setGlobalSetting(getWho(), + Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, "1"); + mConfigCreator.addNetwork(ORIGINAL_DEVICE_OWNER_SSID, true, SECURITY_TYPE_WPA, + ORIGINAL_PASSWORD); + startRegularActivity(ACTION_CREATE_WIFI_CONFIG, -1, ORIGINAL_REGULAR_SSID, + SECURITY_TYPE_WPA, ORIGINAL_PASSWORD); + } + + @Override + protected void tearDown() throws Exception { + mDevicePolicyManager.setGlobalSetting(getWho(), + Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, "0"); + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID) || + areMatchingSsids(CHANGED_DEVICE_OWNER_SSID, config.SSID) || + areMatchingSsids(ORIGINAL_REGULAR_SSID, config.SSID) || + areMatchingSsids(CHANGED_REGULAR_SSID, config.SSID)) { + mWifiManager.removeNetwork(config.networkId); + } + } + super.tearDown(); + } + + public void testDeviceOwnerCanUpdateConfig() throws Exception { + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + int updateCount = 0; + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) { + assertFalse(-1 == mConfigCreator.updateNetwork(config, + CHANGED_DEVICE_OWNER_SSID, true, SECURITY_TYPE_NONE, null)); + ++updateCount; + } + if (areMatchingSsids(ORIGINAL_REGULAR_SSID, config.SSID)) { + assertFalse(-1 == mConfigCreator.updateNetwork(config, + CHANGED_REGULAR_SSID, true, SECURITY_TYPE_NONE, null)); + ++updateCount; + } + } + assertEquals("Expected to update two configs: the DO created one and the regular one." + + " Instead updated: " + updateCount, 2, updateCount); + } + + public void testDeviceOwnerCanRemoveConfig() throws Exception { + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + int removeCount = 0; + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID) || + areMatchingSsids(ORIGINAL_REGULAR_SSID, config.SSID)) { + assertTrue(mWifiManager.removeNetwork(config.networkId)); + ++removeCount; + } + } + assertEquals("Expected to remove two configs: the DO created one and the regular one." + + " Instead removed: " + removeCount, 2, removeCount); + } + + public void testRegularAppCannotUpdateDeviceOwnerConfig() throws Exception { + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + int updateCount = 0; + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) { + startRegularActivity(ACTION_UPDATE_WIFI_CONFIG, config.networkId, + CHANGED_DEVICE_OWNER_SSID, SECURITY_TYPE_NONE, null); + ++updateCount; + } + } + assertEquals("Expected to have tried to update one config: the DO created one" + + " Instead tried to update: " + updateCount, 1, updateCount); + + // Assert nothing has changed + configs = mWifiManager.getConfiguredNetworks(); + int notChangedCount = 0; + for (WifiConfiguration config : configs) { + assertFalse(areMatchingSsids(CHANGED_DEVICE_OWNER_SSID, config.SSID)); + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) { + ++notChangedCount; + } + } + assertEquals("Expected to see one unchanged config, saw instead: " + notChangedCount, 1, + notChangedCount); + } + + public void testRegularAppCannotRemoveDeviceOwnerConfig() throws Exception { + List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); + int removeCount = 0; + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) { + startRegularActivity(ACTION_REMOVE_WIFI_CONFIG, config.networkId, + null, SECURITY_TYPE_NONE, null); + ++removeCount; + } + } + assertEquals("Expected to try to remove one config: the DO created one." + + " Instead tried to remove: " + removeCount, 1, removeCount); + + // Assert nothing has changed + configs = mWifiManager.getConfiguredNetworks(); + int notChangedCount = 0; + for (WifiConfiguration config : configs) { + if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) { + ++notChangedCount; + } + } + assertEquals("Expected to see one unchanged config, saw instead: " + notChangedCount, 1, + notChangedCount); + } + + private void startRegularActivity(String action, int netId, String ssid, int securityType, + String password) throws InterruptedException { + Intent createRegularConfig = new Intent(action); + createRegularConfig.putExtra(EXTRA_NETID, netId); + createRegularConfig.putExtra(EXTRA_SSID, ssid); + createRegularConfig.putExtra(EXTRA_SECURITY_TYPE, securityType); + createRegularConfig.putExtra(EXTRA_PASSWORD, password); + createRegularConfig.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(createRegularConfig); + + // Give some time for the other app to finish the action + Thread.sleep(2000); + } + + private boolean areMatchingSsids(String s1, String s2) { + if (s1 == null || s2 == null) { + return false; + } + return s1.replace("\"", "").equals(s2.replace("\"", "")); + } +}
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk b/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk index 62c7f28..98cdf52 100644 --- a/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk +++ b/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk
@@ -26,6 +26,8 @@ LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 ctstestrunner + LOCAL_SDK_VERSION := current include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml b/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml index 5bbdf76..1512bb2 100644 --- a/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/IntentReceiver/AndroidManifest.xml
@@ -22,15 +22,53 @@ <uses-permission android:name="com.android.cts.managedprofile.permission.SAMPLE"/> <application> + + <uses-library android:name="android.test.runner" /> + <activity android:name="com.android.cts.intent.receiver.IntentReceiverActivity"> <intent-filter> <action android:name="com.android.cts.action.COPY_TO_CLIPBOARD" /> <action android:name="com.android.cts.action.READ_FROM_URI" /> <action android:name="com.android.cts.action.TAKE_PERSISTABLE_URI_PERMISSION" /> <action android:name="com.android.cts.action.WRITE_TO_URI" /> + <action android:name="com.android.cts.action.JUST_CREATE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> + + <activity android:name=".SimpleIntentReceiverActivity" android:exported="true"/> + + <activity-alias android:name=".BrowserActivity" + android:targetActivity=".SimpleIntentReceiverActivity"> + <intent-filter> + <action android:name="android.intent.action.VIEW"/> + <category android:name="android.intent.category.DEFAULT"/> + <category android:name="android.intent.category.BROWSABLE"/> + <data android:scheme="http"/> + </intent-filter> + </activity-alias> + + <activity-alias android:name=".AppLinkActivity" + android:targetActivity=".SimpleIntentReceiverActivity"> + <intent-filter> + <action android:name="android.intent.action.VIEW"/> + <category android:name="android.intent.category.DEFAULT"/> + <category android:name="android.intent.category.BROWSABLE"/> + <data android:scheme="http" android:host="com.android.cts.intent.receiver"/> + </intent-filter> + </activity-alias> + + <receiver android:name=".BroadcastIntentReceiver"> + <intent-filter> + <action android:name="android.app.action.DEVICE_OWNER_CHANGED"/> + </intent-filter> + </receiver> + </application> + <instrumentation + android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.intent.receiver" + android:label="Intent Receiver CTS Tests" /> + </manifest>
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/BroadcastIntentReceiver.java b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/BroadcastIntentReceiver.java new file mode 100644 index 0000000..34b8798 --- /dev/null +++ b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/BroadcastIntentReceiver.java
@@ -0,0 +1,38 @@ +/* + * Copyright (C) 2015 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.intent.receiver; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +public class BroadcastIntentReceiver extends BroadcastReceiver { + + static final String OWNER_CHANGED_BROADCAST_RECEIVED_KEY + = "owner-changed-broadcast-received"; + + static final String PREFERENCES_NAME = "BroadcastIntentReceiver"; + + @Override + public void onReceive(Context c, Intent i) { + SharedPreferences prefs = c.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = prefs.edit(); + editor.putBoolean(OWNER_CHANGED_BROADCAST_RECEIVED_KEY, true); + editor.apply(); + } +}
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/IntentReceiverActivity.java b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/IntentReceiverActivity.java index 294c678..9aa948e 100644 --- a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/IntentReceiverActivity.java +++ b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/IntentReceiverActivity.java
@@ -49,6 +49,11 @@ private static final String ACTION_WRITE_TO_URI = "com.android.cts.action.WRITE_TO_URI"; + private static final String ACTION_JUST_CREATE = + "com.android.cts.action.JUST_CREATE"; + + public static final String RECEIVING_ACTIVITY_CREATED_ACTION + = "com.android.cts.deviceowner.RECEIVING_ACTIVITY_CREATED_ACTION"; private static final String EXTRA_CAUGHT_SECURITY_EXCEPTION = "extra_caught_security_exception"; @@ -98,6 +103,8 @@ Log.i(TAG, "Caught a IOException while trying to write to " + uri, e); } setResult(Activity.RESULT_OK, result); + } else if (ACTION_JUST_CREATE.equals(action)) { + sendBroadcast(new Intent(RECEIVING_ACTIVITY_CREATED_ACTION)); } finish(); }
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/OwnerChangedBroadcastTest.java b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/OwnerChangedBroadcastTest.java new file mode 100644 index 0000000..f305e86 --- /dev/null +++ b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/OwnerChangedBroadcastTest.java
@@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 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.intent.receiver; + +import android.app.admin.DevicePolicyManager; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.test.InstrumentationTestCase; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.lang.InterruptedException; + +public class OwnerChangedBroadcastTest extends InstrumentationTestCase { + + private SharedPreferences mPreferences; + + @Override + public void setUp() throws Exception { + super.setUp(); + Context context = getInstrumentation().getTargetContext(); + mPreferences = context.getSharedPreferences( + BroadcastIntentReceiver.PREFERENCES_NAME, Context.MODE_PRIVATE); + } + + // We can't just register a broadcast receiver in the code because the broadcast + // may have been sent before this test is run. So we have a manifest receiver + // listening to the broadcast and writing to a shared preference when it receives it. + public void testOwnerChangedBroadcastReceived() throws InterruptedException { + final Semaphore mPreferenceChanged = new Semaphore(0); + + OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() { + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + if (key.equals(BroadcastIntentReceiver.OWNER_CHANGED_BROADCAST_RECEIVED_KEY)) { + mPreferenceChanged.release(); + } + } + }; + mPreferences.registerOnSharedPreferenceChangeListener(listener); + + if (mPreferences.getBoolean(BroadcastIntentReceiver.OWNER_CHANGED_BROADCAST_RECEIVED_KEY, + false)) { + // The broadcast intent has already been received? good + // Otherwise, we'll wait until we receive it. + return; + } + // We're relying on background broadcast intents, which can take a long time. + assertTrue(mPreferenceChanged.tryAcquire(2, TimeUnit.MINUTES)); + assertTrue(mPreferences.getBoolean( + BroadcastIntentReceiver.OWNER_CHANGED_BROADCAST_RECEIVED_KEY, false)); + } + + public void testOwnerChangedBroadcastNotReceived() { + assertFalse(mPreferences.getBoolean( + BroadcastIntentReceiver.OWNER_CHANGED_BROADCAST_RECEIVED_KEY, false)); + } +}
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java new file mode 100644 index 0000000..23755df --- /dev/null +++ b/hostsidetests/devicepolicy/app/IntentReceiver/src/com/android/cts/intent/receiver/SimpleIntentReceiverActivity.java
@@ -0,0 +1,52 @@ +/* + * Copyright (C) 2015 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.intent.receiver; + +import android.app.admin.DevicePolicyManager; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import android.os.Bundle; + +/** + * An activity that receives an intent and returns immediately, indicating its own name and if it is + * running in a managed profile. + */ +public class SimpleIntentReceiverActivity extends Activity { + private static final String TAG = "SimpleIntentReceiverActivity"; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + String className = getIntent().getComponent().getClassName(); + + // We try to check if we are in a managed profile or not. + // To do this, check if com.android.cts.managedprofile is the profile owner. + DevicePolicyManager dpm = + (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); + boolean inManagedProfile = dpm.isProfileOwnerApp("com.android.cts.managedprofile"); + + Log.i(TAG, "activity " + className + " started, is in managed profile: " + + inManagedProfile); + Intent result = new Intent(); + result.putExtra("extra_receiver_class", className); + result.putExtra("extra_in_managed_profile", inManagedProfile); + setResult(Activity.RESULT_OK, result); + finish(); + } +}
diff --git a/hostsidetests/devicepolicy/app/IntentSender/Android.mk b/hostsidetests/devicepolicy/app/IntentSender/Android.mk index e45ec31..e5246c5 100644 --- a/hostsidetests/devicepolicy/app/IntentSender/Android.mk +++ b/hostsidetests/devicepolicy/app/IntentSender/Android.mk
@@ -26,7 +26,7 @@ LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 +LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 ctstestrunner LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/devicepolicy/app/IntentSender/AndroidManifest.xml b/hostsidetests/devicepolicy/app/IntentSender/AndroidManifest.xml index 070ef40..cc27298 100644 --- a/hostsidetests/devicepolicy/app/IntentSender/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/IntentSender/AndroidManifest.xml
@@ -52,7 +52,7 @@ </application> <instrumentation - android:name="android.test.InstrumentationTestRunner" + android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="com.android.cts.intent.sender" android:label="Intent Sender CTS Tests" />
diff --git a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java new file mode 100644 index 0000000..51ff362 --- /dev/null +++ b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/AppLinkTest.java
@@ -0,0 +1,99 @@ +/* + * Copyright (C) 2015 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.intent.sender; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.test.InstrumentationTestCase; +import android.util.Log; + +public class AppLinkTest extends InstrumentationTestCase { + + private static final String TAG = "AppLinkTest"; + + private Context mContext; + private IntentSenderActivity mActivity; + + private static final String EXTRA_IN_MANAGED_PROFILE = "extra_in_managed_profile"; + private static final String EXTRA_RECEIVER_CLASS = "extra_receiver_class"; + private static final String APP_LINK_ACTIVITY + = "com.android.cts.intent.receiver.AppLinkActivity"; + private static final String BROWSER_ACTIVITY + = "com.android.cts.intent.receiver.BrowserActivity"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mContext = getInstrumentation().getTargetContext(); + mActivity = launchActivity(mContext.getPackageName(), IntentSenderActivity.class, null); + } + + @Override + public void tearDown() throws Exception { + mActivity.finish(); + super.tearDown(); + } + + public void testReceivedByAppLinkActivityInPrimary() throws Exception { + checkHttpIntentResult(APP_LINK_ACTIVITY, false); + } + + public void testReceivedByAppLinkActivityInManaged() throws Exception { + checkHttpIntentResult(APP_LINK_ACTIVITY, true); + } + + public void testReceivedByBrowserActivityInManaged() throws Exception { + checkHttpIntentResult(BROWSER_ACTIVITY, true); + } + + public void testTwoReceivers() { + assertNumberOfReceivers(2); + } + + public void testThreeReceivers() { + assertNumberOfReceivers(3); + } + + // Should not be called if there are several possible receivers to the intent + // (see getHttpIntent) + private void checkHttpIntentResult(String receiverClassName, boolean inManagedProfile) + throws Exception { + PackageManager pm = mContext.getPackageManager(); + + Intent result = mActivity.getResult(getHttpIntent()); + // If it is received in the other profile, we cannot check the class from the ResolveInfo + // returned by queryIntentActivities. So we rely on the receiver telling us its class. + assertEquals(receiverClassName, result.getStringExtra(EXTRA_RECEIVER_CLASS)); + assertTrue(result.hasExtra(EXTRA_IN_MANAGED_PROFILE)); + assertEquals(inManagedProfile, result.getBooleanExtra(EXTRA_IN_MANAGED_PROFILE, false)); + } + + private void assertNumberOfReceivers(int n) { + PackageManager pm = mContext.getPackageManager(); + assertEquals(n, pm.queryIntentActivities(getHttpIntent(), /* flags = */ 0).size()); + } + + private Intent getHttpIntent() { + Intent i = new Intent(Intent.ACTION_VIEW); + i.addCategory(Intent.CATEGORY_BROWSABLE); + i.setData(Uri.parse("http://com.android.cts.intent.receiver")); + return i; + } +}
diff --git a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/CopyPasteTest.java b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/CopyPasteTest.java index a5d83db..46fc0c4 100644 --- a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/CopyPasteTest.java +++ b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/CopyPasteTest.java
@@ -44,7 +44,7 @@ super.setUp(); Context context = getInstrumentation().getTargetContext(); mActivity = launchActivity(context.getPackageName(), IntentSenderActivity.class, null); - mClipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + mClipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE); } @Override
diff --git a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java index fd421ac..eb64d47 100644 --- a/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java +++ b/hostsidetests/devicepolicy/app/IntentSender/src/com/android/cts/intent/sender/IntentSenderActivity.java
@@ -66,8 +66,12 @@ } public Intent getResult(Intent intent) throws Exception { + Log.d(TAG, "Sending intent " + intent); startActivityForResult(intent, 42); final Result result = mResult.poll(30, TimeUnit.SECONDS); + if (result != null) { + Log.d(TAG, "Result intent: " + result.data); + } return (result != null) ? result.data : null; }
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk index 4517ea2..5f645b6 100644 --- a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk +++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
@@ -26,6 +26,8 @@ LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit +LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner + LOCAL_SDK_VERSION := current include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/AndroidManifest.xml b/hostsidetests/devicepolicy/app/LauncherTests/AndroidManifest.xml index a21b8c2..5ded006 100644 --- a/hostsidetests/devicepolicy/app/LauncherTests/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/LauncherTests/AndroidManifest.xml
@@ -23,7 +23,7 @@ <uses-library android:name="android.test.runner" /> </application> - <instrumentation android:name="android.test.InstrumentationTestRunner" + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="com.android.cts.launchertests" android:label="Launcher Apps CTS Tests"/> </manifest>
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java index e076fc3..35c16ea 100644 --- a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java +++ b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/LauncherAppsTests.java
@@ -38,8 +38,8 @@ import android.os.ResultReceiver; import android.os.UserHandle; import android.os.UserManager; -import android.test.InstrumentationTestCase; -import android.test.InstrumentationTestRunner; +import android.support.test.InstrumentationRegistry; +import android.test.AndroidTestCase; import android.util.Pair; import java.util.concurrent.Semaphore; @@ -49,7 +49,7 @@ /** * Tests for LauncherApps service */ -public class LauncherAppsTests extends InstrumentationTestCase { +public class LauncherAppsTests extends AndroidTestCase { public static final String SIMPLE_APP_PACKAGE = "com.android.cts.launcherapps.simpleapp"; @@ -69,7 +69,7 @@ private LauncherApps mLauncherApps; private UserHandle mUser; - private InstrumentationTestRunner mInstrumentation; + private Instrumentation mInstrumentation; private Messenger mService; private Connection mConnection; private Result mResult; @@ -78,8 +78,8 @@ @Override protected void setUp() throws Exception { super.setUp(); - mInstrumentation = (InstrumentationTestRunner) getInstrumentation(); - Bundle arguments = mInstrumentation.getArguments(); + mInstrumentation = InstrumentationRegistry.getInstrumentation(); + Bundle arguments = InstrumentationRegistry.getArguments(); UserManager userManager = (UserManager) mInstrumentation.getContext().getSystemService( Context.USER_SERVICE); mUser = getUserHandleArgument(userManager, "testUser", arguments);
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk index 46e3cf7..b31e74b 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk +++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -26,7 +26,8 @@ LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit -LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 +LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner compatibility-device-util_v2 \ + ub-uiautomator LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml index e430785..8e27e72 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -18,10 +18,12 @@ package="com.android.cts.managedprofile"> <uses-sdk android:minSdkVersion="20"/> + <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> + <uses-permission android:name="android.permission.CAMERA" /> <application> <uses-library android:name="android.test.runner" /> @@ -34,6 +36,15 @@ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> + <receiver + android:name="com.android.cts.managedprofile.PrimaryUserDeviceAdmin" + android:permission="android.permission.BIND_DEVICE_ADMIN"> + <meta-data android:name="android.app.device_admin" + android:resource="@xml/primary_device_admin" /> + <intent-filter> + <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> + </intent-filter> + </receiver> <activity android:name=".PrimaryUserFilterSetterActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> @@ -41,12 +52,7 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> - <activity android:name=".ComponentDisablingActivity" > - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.DEFAULT"/> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> + <activity android:name=".ComponentDisablingActivity" android:exported="true"> </activity> <activity android:name=".ManagedProfileActivity"> <intent-filter> @@ -66,7 +72,7 @@ <action android:name="com.android.cts.managedprofile.ACTION_TEST_ALL_ACTIVITY" /> </intent-filter> </activity> - <activity android:name=".UserRestrictionActivity" > + <activity android:name=".SetPolicyActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT"/> @@ -75,7 +81,7 @@ <activity android:name=".TestActivity" /> </application> - <instrumentation android:name="android.test.InstrumentationTestRunner" + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="com.android.cts.managedprofile" android:label="Managed Profile CTS Tests"/> </manifest>
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml index 8f39ed0..c3d5c98 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml +++ b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/device_admin.xml
@@ -15,5 +15,6 @@ <device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> <uses-policies> <wipe-data /> + <disable-camera /> </uses-policies> </device-admin>
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/primary_device_admin.xml b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/primary_device_admin.xml new file mode 100644 index 0000000..4bac8a5 --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/res/xml/primary_device_admin.xml
@@ -0,0 +1,19 @@ +<!-- Copyright (C) 2015 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. +--> +<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> + <uses-policies> + <disable-camera /> + </uses-policies> +</device-admin>
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java index 2a54d97..49754d0 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BaseManagedProfileTest.java
@@ -19,7 +19,8 @@ import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; -import android.test.AndroidTestCase; +import android.support.test.uiautomator.UiDevice; +import android.test.InstrumentationTestCase; /** * Base class for profile-owner based tests. @@ -27,7 +28,7 @@ * This class handles making sure that the test is the profile owner and that it has an active admin * registered, so that all tests may assume these are done. */ -public class BaseManagedProfileTest extends AndroidTestCase { +public class BaseManagedProfileTest extends InstrumentationTestCase { public static class BasicAdminReceiver extends DeviceAdminReceiver { } @@ -36,21 +37,23 @@ BasicAdminReceiver.class.getPackage().getName(), BasicAdminReceiver.class.getName()); protected DevicePolicyManager mDevicePolicyManager; + protected Context mContext; @Override protected void setUp() throws Exception { super.setUp(); + mContext = getInstrumentation().getContext(); - mDevicePolicyManager = (DevicePolicyManager) - mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); - assertNotNull(mDevicePolicyManager); + mDevicePolicyManager = (DevicePolicyManager) + mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + assertNotNull(mDevicePolicyManager); - // TODO: Only check the below if we are running as the profile user. If running under the - // user owner, can we check that there is a profile and that the below holds for it? If we - // don't want to do these checks every time we could get rid of this class altogether and - // just have a single test case running under the profile user that do them. - assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT)); - assertTrue(mDevicePolicyManager.isProfileOwnerApp( - ADMIN_RECEIVER_COMPONENT.getPackageName())); + // TODO: Only check the below if we are running as the profile user. If running under the + // user owner, can we check that there is a profile and that the below holds for it? If we + // don't want to do these checks every time we could get rid of this class altogether and + // just have a single test case running under the profile user that do them. + assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT)); + assertTrue(mDevicePolicyManager.isProfileOwnerApp( + ADMIN_RECEIVER_COMPONENT.getPackageName())); } }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraPolicyTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraPolicyTest.java new file mode 100644 index 0000000..25e0b94 --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraPolicyTest.java
@@ -0,0 +1,140 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.hardware.camera2.CameraManager; +import android.os.Handler; +import android.os.HandlerThread; +import android.test.AndroidTestCase; + + +public class CameraPolicyTest extends AndroidTestCase { + + protected static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile"; + + private static final String PRIMARY_ADMIN_RECEIVER_TEST_CLASS = + MANAGED_PROFILE_PKG + ".PrimaryUserDeviceAdmin"; + + private static final String MANAGED_PROFILE_ADMIN_RECEIVER_TEST_CLASS = + MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver"; + + private DevicePolicyManager mDevicePolicyManager; + + private CameraManager mCameraManager; + + private ComponentName mPrimaryAdminComponent; + + private ComponentName mManagedProfileAdminComponent; + + private HandlerThread mBackgroundThread; + + /** + * A {@link Handler} for running tasks in the background. + */ + private Handler mBackgroundHandler; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mDevicePolicyManager = (DevicePolicyManager) getContext() + .getSystemService(Context.DEVICE_POLICY_SERVICE); + mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE); + mPrimaryAdminComponent = new ComponentName(MANAGED_PROFILE_PKG, + PRIMARY_ADMIN_RECEIVER_TEST_CLASS); + mManagedProfileAdminComponent = new ComponentName(MANAGED_PROFILE_PKG, + MANAGED_PROFILE_ADMIN_RECEIVER_TEST_CLASS); + startBackgroundThread(); + } + + @Override + protected void tearDown() throws Exception { + stopBackgroundThread(); + super.tearDown(); + } + + public void testDisableCameraInManagedProfile() throws Exception { + mDevicePolicyManager.setCameraDisabled(mManagedProfileAdminComponent, true); + assertTrue(mDevicePolicyManager.getCameraDisabled(mManagedProfileAdminComponent)); + assertTrue(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(false); + } + + public void testEnableCameraInManagedProfile() throws Exception { + mDevicePolicyManager.setCameraDisabled(mManagedProfileAdminComponent, false); + assertFalse(mDevicePolicyManager.getCameraDisabled(mManagedProfileAdminComponent)); + assertFalse(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(true); + } + + public void testDisableCameraInPrimaryProfile() throws Exception { + mDevicePolicyManager.setCameraDisabled(mPrimaryAdminComponent, true); + assertTrue(mDevicePolicyManager.getCameraDisabled(mPrimaryAdminComponent)); + assertTrue(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(false); + } + + public void testEnableCameraInPrimaryProfile() throws Exception { + mDevicePolicyManager.setCameraDisabled(mPrimaryAdminComponent, false); + assertFalse(mDevicePolicyManager.getCameraDisabled(mPrimaryAdminComponent)); + assertFalse(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(true); + } + + public void testIsCameraEnabledInPrimaryProfile() throws Exception { + assertFalse(mDevicePolicyManager.getCameraDisabled(mPrimaryAdminComponent)); + assertFalse(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(true); + } + + public void testIsCameraEnabledInManagedProfile() throws Exception { + assertFalse(mDevicePolicyManager.getCameraDisabled(mManagedProfileAdminComponent)); + assertFalse(mDevicePolicyManager.getCameraDisabled(null)); + checkCanOpenCamera(true); + } + + private void checkCanOpenCamera(boolean canOpen) { + boolean successToOpen = CameraUtils + .blockUntilOpenCamera(mCameraManager, mBackgroundHandler); + assertEquals(canOpen, successToOpen); + } + + /** + * Starts a background thread and its {@link Handler}. + */ + private void startBackgroundThread() { + mBackgroundThread = new HandlerThread("CameraBackground"); + mBackgroundThread.start(); + mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); + } + + /** + * Stops the background thread and its {@link Handler}. + */ + private void stopBackgroundThread() { + mBackgroundThread.quitSafely(); + try { + mBackgroundThread.join(); + mBackgroundThread = null; + mBackgroundHandler = null; + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraUtils.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraUtils.java new file mode 100644 index 0000000..516e244 --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CameraUtils.java
@@ -0,0 +1,93 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.hardware.camera2.CameraDevice; +import android.hardware.camera2.CameraManager; +import android.os.Handler; +import android.util.Log; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A util class to help open camera in a blocking way. + */ +class CameraUtils { + + private static final String TAG = "CameraUtils"; + + /** + * @return true if success to open camera, false otherwise. + */ + public static boolean blockUntilOpenCamera(CameraManager cameraManager, Handler handler) { + try { + String[] cameraIdList = cameraManager.getCameraIdList(); + if (cameraIdList == null || cameraIdList.length == 0) { + return false; + } + String cameraId = cameraIdList[0]; + CameraCallback callback = new CameraCallback(); + cameraManager.openCamera(cameraId, callback, handler); + return callback.waitForResult(); + } catch (Exception ex) { + // No matter what is going wrong, it means fail to open camera. + ex.printStackTrace(); + return false; + } + } + + /** + * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state. + */ + private static class CameraCallback extends CameraDevice.StateCallback { + + private static final int OPEN_TIMEOUT_SECONDS = 5; + + private final CountDownLatch mLatch = new CountDownLatch(1); + + private AtomicBoolean mResult = new AtomicBoolean(false); + + @Override + public void onOpened(CameraDevice cameraDevice) { + Log.d(TAG, "open camera successfully"); + mResult.set(true); + if (cameraDevice != null) { + cameraDevice.close(); + } + mLatch.countDown(); + } + + @Override + public void onDisconnected(CameraDevice cameraDevice) { + Log.d(TAG, "disconnect camera"); + mLatch.countDown(); + } + + @Override + public void onError(CameraDevice cameraDevice, int error) { + Log.e(TAG, "Fail to open camera, error code = " + error); + mLatch.countDown(); + } + + public boolean waitForResult() throws InterruptedException { + mLatch.await(OPEN_TIMEOUT_SECONDS, TimeUnit.SECONDS); + return mResult.get(); + } + } +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ContactsTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ContactsTest.java index faee6dc..77ecfe1 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ContactsTest.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ContactsTest.java
@@ -28,13 +28,16 @@ import android.os.Build; import android.os.RemoteException; import android.provider.ContactsContract; +import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; +import android.provider.ContactsContract.Data; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.RawContacts; import android.test.AndroidTestCase; import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -44,15 +47,30 @@ private static final String TEST_ACCOUNT_NAME = "CTS"; private static final String TEST_ACCOUNT_TYPE = "com.android.cts.test"; + // details of a sample primary contact private static final String PRIMARY_CONTACT_DISPLAY_NAME = "Primary"; private static final String PRIMARY_CONTACT_PHONE = "00000001"; + private static final String PRIMARY_CONTACT_EMAIL = "one@primary.com"; + private static final String PRIMARY_CONTACT_SIP = "foo@sip"; + + // details of a sample managed contact private static final String MANAGED_CONTACT_DISPLAY_NAME = "Managed"; private static final String MANAGED_CONTACT_PHONE = "6891999"; + private static final String MANAGED_CONTACT_EMAIL = "one@managed.com"; + private static final String MANAGED_CONTACT_SIP = "bar@sip"; + + // details of a sample primary and a sample managed contact, with the same phone & email + private static final String PRIMARY_CONTACT_DISPLAY_NAME_2 = "PrimaryShared"; + private static final String MANAGED_CONTACT_DISPLAY_NAME_2 = "ManagedShared"; + private static final String SHARED_CONTACT_PHONE = "00000002"; + private static final String SHARED_CONTACT_EMAIL = "shared@shared.com"; + private static final String SHARED_CONTACT_SIP = "baz@sip"; private DevicePolicyManager mDevicePolicyManager; private ContentResolver mResolver; - private static class ContactInfo { + private class ContactInfo { // Not static to access outer world. + String contactId; String displayName; String photoUri; @@ -68,8 +86,14 @@ this.photoId = photoId; } - private boolean hasPhotoUri() { - return photoUri != null && photoThumbnailUri != null; + private void assertNoPhotoUri() { + assertNull(photoUri); + assertNull(photoThumbnailUri); + } + + private void assertPhotoUrisReadable() throws IOException { + assertPhotoUriReadable(photoUri); + assertPhotoUriReadable(photoThumbnailUri); } private boolean hasPhotoId() { @@ -85,72 +109,254 @@ .getSystemService(Context.DEVICE_POLICY_SERVICE); } - public void testPrimaryProfilePhoneLookup_insertedAndfound() throws RemoteException, + public void testPrimaryProfilePhoneAndEmailLookup_insertedAndfound() throws RemoteException, OperationApplicationException, NotFoundException, IOException { assertFalse(isManagedProfile()); // Do not insert to primary contact - insertContact(PRIMARY_CONTACT_DISPLAY_NAME, PRIMARY_CONTACT_PHONE, 0); + insertContact(PRIMARY_CONTACT_DISPLAY_NAME, PRIMARY_CONTACT_PHONE, + PRIMARY_CONTACT_EMAIL, PRIMARY_CONTACT_SIP, 0); ContactInfo contactInfo = getContactInfo(PRIMARY_CONTACT_PHONE); assertNotNull(contactInfo); assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName); - assertFalse(contactInfo.hasPhotoUri()); + contactInfo.assertNoPhotoUri(); assertFalse(contactInfo.hasPhotoId()); assertFalse(isEnterpriseContactId(contactInfo.contactId)); + + contactInfo = getContactInfoFromEmail(PRIMARY_CONTACT_EMAIL); + assertNotNull(contactInfo); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } - public void testManagedProfilePhoneLookup_insertedAndfound() throws RemoteException, + public void testManagedProfilePhoneAndEmailLookup_insertedAndfound() throws RemoteException, OperationApplicationException, NotFoundException, IOException { assertTrue(isManagedProfile()); // Insert ic_contact_picture as photo in managed contact - insertContact(MANAGED_CONTACT_DISPLAY_NAME, MANAGED_CONTACT_PHONE, + insertContact(MANAGED_CONTACT_DISPLAY_NAME, + MANAGED_CONTACT_PHONE, + MANAGED_CONTACT_EMAIL, + MANAGED_CONTACT_SIP, com.android.cts.managedprofile.R.raw.ic_contact_picture); ContactInfo contactInfo = getContactInfo(MANAGED_CONTACT_PHONE); assertNotNull(contactInfo); assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); - assertTrue(contactInfo.hasPhotoUri()); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + + contactInfo = getContactInfoFromEmail(MANAGED_CONTACT_EMAIL); + assertNotNull(contactInfo); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); assertTrue(contactInfo.hasPhotoId()); assertFalse(isEnterpriseContactId(contactInfo.contactId)); } - public void testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact() { + public void testPrimaryProfileDuplicatedPhoneEmailContact_insertedAndfound() throws + RemoteException, OperationApplicationException, NotFoundException, IOException { + assertFalse(isManagedProfile()); + insertContact(PRIMARY_CONTACT_DISPLAY_NAME_2, + SHARED_CONTACT_PHONE, + SHARED_CONTACT_EMAIL, + SHARED_CONTACT_SIP, + com.android.cts.managedprofile.R.raw.ic_contact_picture); + + ContactInfo contactInfo = getContactInfo(SHARED_CONTACT_PHONE); + assertNotNull(contactInfo); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + + contactInfo = getContactInfoFromEmail(SHARED_CONTACT_EMAIL); + assertNotNull(contactInfo); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testManagedProfileDuplicatedPhoneEmailContact_insertedAndfound() throws + RemoteException, OperationApplicationException, NotFoundException, IOException { + assertTrue(isManagedProfile()); + insertContact(MANAGED_CONTACT_DISPLAY_NAME_2, SHARED_CONTACT_PHONE, + SHARED_CONTACT_EMAIL, SHARED_CONTACT_SIP , 0); + + ContactInfo contactInfo = getContactInfo(SHARED_CONTACT_PHONE); + assertNotNull(contactInfo); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + + contactInfo = getContactInfoFromEmail(SHARED_CONTACT_EMAIL); + assertNotNull(contactInfo); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact() + throws IOException { assertFalse(isManagedProfile()); ContactInfo contactInfo = getEnterpriseContactInfo(MANAGED_CONTACT_PHONE); assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); - assertTrue(contactInfo.hasPhotoUri()); + contactInfo.assertPhotoUrisReadable(); // Cannot get photo id in ENTERPRISE_CONTENT_FILTER_URI assertFalse(contactInfo.hasPhotoId()); assertTrue(isEnterpriseContactId(contactInfo.contactId)); } - public void testPrimaryProfilePhoneLookup_canAccessPrimaryContact() { + public void testPrimaryProfileEnterpriseSipLookup_canAccessEnterpriseContact() + throws IOException { assertFalse(isManagedProfile()); - ContactInfo contactInfo = getEnterpriseContactInfo(PRIMARY_CONTACT_PHONE); - assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName); - assertFalse(contactInfo.hasPhotoUri()); + ContactInfo contactInfo = getEnterpriseContactInfoFromSipAddress(MANAGED_CONTACT_SIP); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertFalse(contactInfo.hasPhotoId()); + + // Quirk: the _id column from the SIP lookup is actually of the data id, not the contact id. + // assertTrue(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testPrimaryProfileEnterpriseEmailLookup_canAccessEnterpriseContact() + throws IOException { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(MANAGED_CONTACT_EMAIL); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + // Cannot get photo id in ENTERPRISE_CONTENT_FILTER_URI + assertFalse(contactInfo.hasPhotoId()); + assertTrue(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact() + throws IOException { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfo(SHARED_CONTACT_PHONE); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact() + throws IOException { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(SHARED_CONTACT_EMAIL); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact() { + assertTrue(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfo(SHARED_CONTACT_PHONE); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); assertFalse(contactInfo.hasPhotoId()); assertFalse(isEnterpriseContactId(contactInfo.contactId)); } - public void testManagedProfilePhoneLookup_canAccessEnterpriseContact() { + public void testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact() { assertTrue(isManagedProfile()); - ContactInfo contactInfo = getEnterpriseContactInfo(MANAGED_CONTACT_PHONE); - assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); - assertTrue(contactInfo.hasPhotoUri()); - assertTrue(contactInfo.hasPhotoId()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(SHARED_CONTACT_EMAIL); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); assertFalse(isEnterpriseContactId(contactInfo.contactId)); } public void testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact() { assertFalse(isManagedProfile()); + ContactInfo contactInfo = getContactInfo(MANAGED_CONTACT_PHONE); + assertNull(contactInfo); + } + + public void testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact() { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getContactInfoFromEmail(MANAGED_CONTACT_EMAIL); + assertNull(contactInfo); + } + + public void testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryContact() { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfo(PRIMARY_CONTACT_PHONE); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryContact() { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(PRIMARY_CONTACT_EMAIL); + assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertNoPhotoUri(); + assertFalse(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testManagedProfileEnterprisePhoneLookup_canAccessEnterpriseContact() + throws IOException { + assertTrue(isManagedProfile()); ContactInfo contactInfo = getEnterpriseContactInfo(MANAGED_CONTACT_PHONE); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testManagedProfileEnterpriseEmailLookup_canAccessEnterpriseContact() + throws IOException { + assertTrue(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(MANAGED_CONTACT_EMAIL); + assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName); + contactInfo.assertPhotoUrisReadable(); + assertTrue(contactInfo.hasPhotoId()); + assertFalse(isEnterpriseContactId(contactInfo.contactId)); + } + + public void testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact() { + assertTrue(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfo(PRIMARY_CONTACT_PHONE); + assertNull(contactInfo); + } + + public void testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact() { + assertTrue(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(PRIMARY_CONTACT_EMAIL); assertNull(contactInfo); } public void testManagedProfilePhoneLookup_canNotAccessPrimaryContact() { assertTrue(isManagedProfile()); - ContactInfo contactInfo = getEnterpriseContactInfo(PRIMARY_CONTACT_PHONE); + ContactInfo contactInfo = getContactInfo(PRIMARY_CONTACT_PHONE); + assertNull(contactInfo); + } + + public void testManagedProfileEmailLookup_canNotAccessPrimaryContact() { + assertTrue(isManagedProfile()); + ContactInfo contactInfo = getContactInfoFromEmail(PRIMARY_CONTACT_EMAIL); + assertNull(contactInfo); + } + + public void testPrimaryProfileEnterpriseEmailLookup_canNotAccessEnterpriseContact() { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfoFromEmail(MANAGED_CONTACT_EMAIL); + assertNull(contactInfo); + } + + public void testPrimaryProfileEnterprisePhoneLookup_canNotAccessEnterpriseContact() { + assertFalse(isManagedProfile()); + ContactInfo contactInfo = getEnterpriseContactInfo(MANAGED_CONTACT_PHONE); assertNull(contactInfo); } @@ -170,14 +376,25 @@ removeAllTestContactsInProfile(); } + public void testSetBluetoothContactSharingDisabled_setterAndGetter() { + mDevicePolicyManager.setBluetoothContactSharingDisabled( + BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, false); + assertFalse(mDevicePolicyManager.getBluetoothContactSharingDisabled( + BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT)); + mDevicePolicyManager.setBluetoothContactSharingDisabled( + BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, true); + assertTrue(mDevicePolicyManager.getBluetoothContactSharingDisabled( + BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT)); + } + private boolean isManagedProfile() { String adminPackage = BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT.getPackageName(); return mDevicePolicyManager.isProfileOwnerApp(adminPackage); } - private void insertContact(String displayName, String phoneNumber, int photoResId) - throws RemoteException, - OperationApplicationException, NotFoundException, IOException { + private void insertContact(String displayName, String phoneNumber, String email, + String sipAddress, int photoResId) + throws RemoteException, OperationApplicationException, NotFoundException, IOException { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation .newInsert(ContactsContract.RawContacts.CONTENT_URI) @@ -205,25 +422,61 @@ .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE) .build()); + ops.add(ContentProviderOperation + .newInsert(ContactsContract.Data.CONTENT_URI) + .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) + .withValue( + ContactsContract.Data.MIMETYPE, + ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) + .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, + email) + .withValue(ContactsContract.CommonDataKinds.Email.TYPE, + Email.TYPE_WORK) + .build()); + ops.add(ContentProviderOperation + .newInsert(ContactsContract.Data.CONTENT_URI) + .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) + .withValue( + ContactsContract.Data.MIMETYPE, + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE) + .withValue(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS, + sipAddress) + .withValue(ContactsContract.CommonDataKinds.SipAddress.TYPE, + ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK) + .build()); + if (photoResId != 0) { InputStream phoneInputStream = mContext.getResources().openRawResource(photoResId); - byte[] rawPhoto = getByteFromStream(phoneInputStream); - ops.add(ContentProviderOperation - .newInsert(ContactsContract.Data.CONTENT_URI) - .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) - .withValue( - ContactsContract.Data.MIMETYPE, - ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) - .withValue(Photo.PHOTO, rawPhoto) - .build()); + try { + byte[] rawPhoto = getByteFromStream(phoneInputStream); + ops.add(ContentProviderOperation + .newInsert(ContactsContract.Data.CONTENT_URI) + .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) + .withValue( + ContactsContract.Data.MIMETYPE, + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) + .withValue(Photo.PHOTO, rawPhoto) + .build()); + } finally { + phoneInputStream.close(); + } } mResolver.applyBatch(ContactsContract.AUTHORITY, ops); } private ContactInfo getContactInfoFromUri(Uri phoneLookupUri, String phoneNumber) { - Uri uri = Uri.withAppendedPath(phoneLookupUri, - Uri.encode(phoneNumber)); + return getContactInfoFromPhoneLookup(Uri.withAppendedPath(phoneLookupUri, + Uri.encode(phoneNumber)), /* forSip =*/ false); + } + + private ContactInfo getContactInfoFromSipUri(Uri phoneLookupUri, String sipAddress) { + return getContactInfoFromPhoneLookup( + phoneLookupUri.buildUpon().appendEncodedPath(sipAddress).appendQueryParameter( + PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, "1").build(), /* forSip =*/ true); + } + + private ContactInfo getContactInfoFromPhoneLookup(Uri uri, boolean isForSip) { Cursor cursor = mResolver.query(uri, new String[] { PhoneLookup._ID, PhoneLookup.DISPLAY_NAME, PhoneLookup.PHOTO_URI, @@ -245,17 +498,61 @@ return result; } + private ContactInfo getContactInfoFromEmailUri(Uri emailLookupUri, String email) { + Uri uri = Uri.withAppendedPath(emailLookupUri, Uri.encode(email)); + Cursor cursor = mResolver.query(uri, + new String[] { + Email.CONTACT_ID, + Email.DISPLAY_NAME_PRIMARY, + Email.PHOTO_URI, + Email.PHOTO_ID, + Email.PHOTO_THUMBNAIL_URI, + }, null, null, null); + if (cursor == null) { + return null; + } + ContactInfo result = null; + if (cursor.moveToFirst()) { + result = new ContactInfo( + cursor.getString(cursor.getColumnIndexOrThrow( + Email.CONTACT_ID)), + cursor.getString(cursor.getColumnIndexOrThrow( + Email.DISPLAY_NAME_PRIMARY)), + cursor.getString(cursor.getColumnIndexOrThrow( + Email.PHOTO_URI)), + cursor.getString(cursor.getColumnIndexOrThrow( + Email.PHOTO_THUMBNAIL_URI)), + cursor.getString(cursor.getColumnIndexOrThrow( + Email.PHOTO_ID))); + } + cursor.close(); + return result; + } + private ContactInfo getContactInfo(String phoneNumber) { return getContactInfoFromUri(PhoneLookup.CONTENT_FILTER_URI, phoneNumber); } + private ContactInfo getContactInfoFromEmail(String email) { + return getContactInfoFromEmailUri(Email.CONTENT_LOOKUP_URI, email); + } + private ContactInfo getEnterpriseContactInfo(String phoneNumber) { return getContactInfoFromUri( PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, phoneNumber); } + private ContactInfo getEnterpriseContactInfoFromSipAddress(String phoneNumber) { + return getContactInfoFromSipUri(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, + phoneNumber); + } + + private ContactInfo getEnterpriseContactInfoFromEmail(String email) { + return getContactInfoFromEmailUri(Email.ENTERPRISE_CONTENT_LOOKUP_URI, email); + } + private void removeAllTestContactsInProfile() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI) @@ -282,4 +579,18 @@ private boolean isEnterpriseContactId(String contactId) { return ContactsContract.Contacts.isEnterpriseContactId(Long.valueOf(contactId)); } + + private void assertPhotoUriReadable(String uri) throws IOException { + assertNotNull(uri); + final InputStream is = mResolver.openInputStream(Uri.parse(uri)); + try { + // Make sure it's readabe. Don't have to read all content. + is.read(); + } finally { + try { + is.close(); + } catch (IOException ignore) { + } + } + } }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java index 49001e9..6a63cea 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileUtils.java
@@ -20,9 +20,16 @@ import android.app.admin.DevicePolicyManager; import android.content.Context; +import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.net.Uri; import android.os.UserManager; import android.test.AndroidTestCase; +import android.util.Log; + +import java.util.List; /** * The methods in this class are not really tests. @@ -31,6 +38,8 @@ * device-side methods from the host. */ public class CrossProfileUtils extends AndroidTestCase { + private static final String TAG = "CrossProfileUtils"; + private static final String ACTION_READ_FROM_URI = "com.android.cts.action.READ_FROM_URI"; private static final String ACTION_WRITE_TO_URI = "com.android.cts.action.WRITE_TO_URI"; @@ -40,8 +49,8 @@ private static String ACTION_COPY_TO_CLIPBOARD = "com.android.cts.action.COPY_TO_CLIPBOARD"; - public void addParentCanAccessManagedFilters() { - removeAllFilters(); + public void testAddParentCanAccessManagedFilters() { + testRemoveAllFilters(); final DevicePolicyManager dpm = (DevicePolicyManager) getContext().getSystemService( Context.DEVICE_POLICY_SERVICE); @@ -49,8 +58,8 @@ DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED); } - public void addManagedCanAccessParentFilters() { - removeAllFilters(); + public void testAddManagedCanAccessParentFilters() { + testRemoveAllFilters(); final DevicePolicyManager dpm = (DevicePolicyManager) getContext().getSystemService( Context.DEVICE_POLICY_SERVICE); @@ -67,23 +76,37 @@ return intentFilter; } - public void removeAllFilters() { + public void testRemoveAllFilters() { final DevicePolicyManager dpm = (DevicePolicyManager) getContext().getSystemService( Context.DEVICE_POLICY_SERVICE); dpm.clearCrossProfileIntentFilters(ADMIN_RECEIVER_COMPONENT); } - public void disallowCrossProfileCopyPaste() { + public void testDisallowCrossProfileCopyPaste() { DevicePolicyManager dpm = (DevicePolicyManager) getContext().getSystemService(Context.DEVICE_POLICY_SERVICE); dpm.addUserRestriction(ADMIN_RECEIVER_COMPONENT, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE); } - public void allowCrossProfileCopyPaste() { + public void testAllowCrossProfileCopyPaste() { DevicePolicyManager dpm = (DevicePolicyManager) getContext().getSystemService(Context.DEVICE_POLICY_SERVICE); dpm.clearUserRestriction(ADMIN_RECEIVER_COMPONENT, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE); } + + // Disables all browsers in current user + public void testDisableAllBrowsers() { + PackageManager pm = (PackageManager) getContext().getPackageManager(); + DevicePolicyManager dpm = (DevicePolicyManager) + getContext().getSystemService(Context.DEVICE_POLICY_SERVICE); + Intent webIntent = new Intent(Intent.ACTION_VIEW); + webIntent.setData(Uri.parse("http://com.android.cts.intent.receiver")); + List<ResolveInfo> ris = pm.queryIntentActivities(webIntent, 0 /* no flags*/); + for (ResolveInfo ri : ris) { + Log.d(TAG, "Hiding " + ri.activityInfo.packageName); + dpm.setApplicationHidden(ADMIN_RECEIVER_COMPONENT, ri.activityInfo.packageName, true); + } + } }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetPrimaryUserTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetPrimaryUserTest.java new file mode 100644 index 0000000..bb1640b --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetPrimaryUserTest.java
@@ -0,0 +1,168 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.app.Instrumentation; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.Messenger; +import android.test.AndroidTestCase; +import android.util.Log; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * This class contains tests for cross profile widget providers that are run on the primary users. + * The tests connect to a {@link android.appwidget.AppWidgetHost} and check whether the cross + * cross-profile widget can / cannot be found from the primary user. + * The tests cannot be run independently, but are part of one hostside test. + */ +public class CrossProfileWidgetPrimaryUserTest extends AndroidTestCase { + private static final String TAG = "CrossProfileWidgetPrimaryUserTest"; + + private static final int MSG_RESULT = 0; + private static final int MSG_PROVIDER_PRESENT = 1; + private static final int MSG_PROVIDER_UPDATES = 2; + + private static final int RESULT_UNKNOWN = 0; + private static final int RESULT_PRESENT = 1; + private static final int RESULT_NOTPRESENT = 2; + private static final int RESULT_INTERRUPTED = 3; + private static final int RESULT_TIMEOUT = 4; + + private static final String PACKAGE_EXTRA = "package-extra"; + + private Messenger mService; + private Connection mConnection; + private Result mResult; + private Messenger mResultMessenger; + + @Override + protected void setUp() throws Exception { + final Intent intent = new Intent(); + intent.setComponent(new ComponentName(CrossProfileWidgetTest.WIDGET_PROVIDER_PKG, + CrossProfileWidgetTest.WIDGET_PROVIDER_PKG + ".SimpleAppWidgetHostService")); + mConnection = new Connection(); + getContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + mConnection.waitForService(); + mResult = new Result(Looper.getMainLooper()); + mResultMessenger = new Messenger(mResult); + } + + public void testHasCrossProfileWidgetProvider_false() throws Exception { + int result = sendMessageToCallbacksService(MSG_PROVIDER_PRESENT, + CrossProfileWidgetTest.WIDGET_PROVIDER_PKG); + assertEquals(RESULT_NOTPRESENT, result); + } + + public void testHostReceivesWidgetUpdates_false() throws Exception { + int result = sendMessageToCallbacksService(MSG_PROVIDER_UPDATES, + CrossProfileWidgetTest.WIDGET_PROVIDER_PKG); + assertEquals(RESULT_NOTPRESENT, result); + } + + public void testHasCrossProfileWidgetProvider_true() throws Exception { + int result = sendMessageToCallbacksService(MSG_PROVIDER_PRESENT, + CrossProfileWidgetTest.WIDGET_PROVIDER_PKG); + assertEquals(RESULT_PRESENT, result); + } + + public void testHostReceivesWidgetUpdates_true() throws Exception { + int result = sendMessageToCallbacksService(MSG_PROVIDER_UPDATES, + CrossProfileWidgetTest.WIDGET_PROVIDER_PKG); + assertEquals(RESULT_PRESENT, result); + } + + private int sendMessageToCallbacksService(int msg, String packageName) + throws Exception { + Bundle params = new Bundle(); + params.putString(PACKAGE_EXTRA, packageName); + + Message message = Message.obtain(null, msg, params); + message.replyTo = mResultMessenger; + + mService.send(message); + + return mResult.waitForResult(); + } + + private static class Result extends Handler { + + private final Semaphore mSemaphore = new Semaphore(0); + public int result = 0; + + public Result(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + if (msg.what == MSG_RESULT) { + result = msg.arg1; + mSemaphore.release(); + } else { + super.handleMessage(msg); + } + } + + public int waitForResult() { + try { + if (mSemaphore.tryAcquire(120, TimeUnit.SECONDS)) { + return result; + } + } catch (InterruptedException e) { + Log.e(TAG, "Interrupted when talking to service", e); + } + return RESULT_TIMEOUT; + } + } + + private class Connection implements ServiceConnection { + private final Semaphore mSemaphore = new Semaphore(0); + + @Override + public void onServiceConnected(ComponentName className, IBinder service) { + mService = new Messenger(service); + mSemaphore.release(); + } + + @Override + public void onServiceDisconnected(ComponentName className) { + mService = null; + } + + public void waitForService() { + try { + if (mSemaphore.tryAcquire(5, TimeUnit.SECONDS)) { + return; + } + } catch (InterruptedException e) { + Log.e(TAG, "Interrupted when connecting to service", e); + } + fail("failed to connect to service"); + } + }; + +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetTest.java new file mode 100644 index 0000000..085d56f --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/CrossProfileWidgetTest.java
@@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProviderInfo; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Process; +import android.os.UserHandle; +import android.util.Log; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * This class contains tests for cross profile widget providers that are run on the managed + * profile. Policies are set using {@link SetPolicyActivity} and then verified in these tests. + * The tests cannot be run independently, but are part of one hostside test. + */ +public class CrossProfileWidgetTest extends BaseManagedProfileTest { + static final String WIDGET_PROVIDER_PKG = "com.android.cts.widgetprovider"; + + private AppWidgetManager mAppWidgetManager; + + public void setUp() throws Exception { + super.setUp(); + mAppWidgetManager = (AppWidgetManager) mContext.getSystemService(Context.APPWIDGET_SERVICE); + } + + /** + * This test checks that the widget provider was successfully whitelisted and verifies that + * if was added successfully and can be found inside the profile. + */ + public void testCrossProfileWidgetProviderAdded() { + List<String> providers = mDevicePolicyManager.getCrossProfileWidgetProviders( + ADMIN_RECEIVER_COMPONENT); + assertEquals(1, providers.size()); + assertTrue(providers.contains(WIDGET_PROVIDER_PKG)); + // check that widget can be found inside the profile + assertTrue(containsWidgetProviderPkg(mAppWidgetManager.getInstalledProviders())); + } + + /** + * This test verifies that the widget provider was successfully removed from the whitelist. + */ + public void testCrossProfileWidgetProviderRemoved() { + List<String> providers = mDevicePolicyManager.getCrossProfileWidgetProviders( + ADMIN_RECEIVER_COMPONENT); + assertTrue(providers.isEmpty()); + // check that widget can still be found inside the profile + // This does not currently work correctly: http://b/issues/21180997 + // assertTrue(containsWidgetProviderPkg(mAppWidgetManager.getInstalledProviders())); + } + + private boolean containsWidgetProviderPkg(List<AppWidgetProviderInfo> widgets) { + for (AppWidgetProviderInfo widget : widgets) { + if (WIDGET_PROVIDER_PKG.equals(widget.provider.getPackageName())) { + return true; + } + } + return false; + } +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ManagedProfileTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ManagedProfileTest.java index 47ecfcb..e655d7b 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ManagedProfileTest.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ManagedProfileTest.java
@@ -21,6 +21,7 @@ import android.content.IntentFilter; import android.content.pm.PackageManager; import android.test.ActivityInstrumentationTestCase2; +import android.support.test.InstrumentationRegistry; import static com.android.cts.managedprofile.BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT; @@ -43,6 +44,10 @@ @Override protected void setUp() throws Exception { super.setUp(); + // As the way to access Instrumentation is changed in the new runner, we need to inject it + // manually into ActivityInstrumentationTestCase2. ActivityInstrumentationTestCase2 will + // be marked as deprecated and replaced with ActivityTestRule. + injectInstrumentation(InstrumentationRegistry.getInstrumentation()); mPackageManager = getActivity().getPackageManager(); mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserAdminHelper.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserAdminHelper.java new file mode 100644 index 0000000..47f8716 --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserAdminHelper.java
@@ -0,0 +1,51 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.test.AndroidTestCase; + +/** + * This test executes helper tasks as active device admin in the primary user. + */ +public class PrimaryUserAdminHelper extends AndroidTestCase { + + private DevicePolicyManager mDpm; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mDpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + } + + /** + * Device admin can only be deactivated by itself and this test should be executed before the + * device admin package can be uninstalled. + */ + public void testClearDeviceAdmin() throws Exception { + ComponentName cn = PrimaryUserDeviceAdmin.ADMIN_RECEIVER_COMPONENT; + if (mDpm.isAdminActive(cn)) { + mDpm.removeActiveAdmin(cn); + // Wait until device admin is not active (with 2 minutes timeout). + for (int i = 0; i < 2 * 60 && mDpm.isAdminActive(cn); i++) { + Thread.sleep(1000); // 1 second. + } + } + assertFalse(mDpm.isAdminActive(cn)); + } +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserDeviceAdmin.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserDeviceAdmin.java new file mode 100644 index 0000000..8662daf --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserDeviceAdmin.java
@@ -0,0 +1,29 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.app.admin.DeviceAdminReceiver; +import android.content.ComponentName; + +/** + * A device admin class running in the primary user. Currently used by delegated cert installer + * test to set a lockscreen password which is prerequisite of installKeyPair(). + */ +public class PrimaryUserDeviceAdmin extends DeviceAdminReceiver { + public static final ComponentName ADMIN_RECEIVER_COMPONENT = new ComponentName( + PrimaryUserDeviceAdmin.class.getPackage().getName(), + PrimaryUserDeviceAdmin.class.getName()); +} \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserTest.java index 40ff6c5..4163ba8 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserTest.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/PrimaryUserTest.java
@@ -20,6 +20,7 @@ import android.content.Intent; import android.content.pm.PackageManager; import android.test.ActivityInstrumentationTestCase2; +import android.support.test.InstrumentationRegistry; /** * Test for {@link DevicePolicyManager#addCrossProfileIntentFilter} API, for @@ -43,6 +44,10 @@ @Override protected void setUp() throws Exception { super.setUp(); + // As the way to access Instrumentation is changed in the new runner, we need to inject it + // manually into ActivityInstrumentationTestCase2. ActivityInstrumentationTestCase2 will + // be marked as deprecated and replaced with ActivityTestRule. + injectInstrumentation(InstrumentationRegistry.getInstrumentation()); mPackageManager = getActivity().getPackageManager(); }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/SetPolicyActivity.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/SetPolicyActivity.java new file mode 100644 index 0000000..f59363b --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/SetPolicyActivity.java
@@ -0,0 +1,99 @@ +/* + * 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.managedprofile; + +import android.app.Activity; +import android.app.admin.DevicePolicyManager; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Process; +import android.util.Log; + +import com.android.cts.managedprofile.BaseManagedProfileTest; + +/** + * Simple activity that adds or clears a user restriction depending on the value of the extras. + */ +public class SetPolicyActivity extends Activity { + + private static final String TAG = SetPolicyActivity.class.getName(); + + private static final String EXTRA_RESTRICTION_KEY = "extra-restriction-key"; + private static final String EXTRA_PACKAGE_NAME = "extra-package-name"; + private static final String EXTRA_COMMAND = "extra-command"; + + private static final String ADD_RESTRICTION_COMMAND = "add-restriction"; + private static final String CLEAR_RESTRICTION_COMMAND = "clear-restriction"; + private static final String ADD_CROSS_PROFILE_WIDGET_COMMAND = "add-cross-profile-widget"; + private static final String REMOVE_CROSS_PROFILE_WIDGET_COMMAND = "remove-cross-profile-widget"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + handleIntent(getIntent()); + } + + // Overriding this method in case another intent is sent to this activity before finish() + @Override + public void onNewIntent(Intent intent) { + super.onNewIntent(intent); + handleIntent(intent); + } + + @Override + public void onPause() { + super.onPause(); + // Calling finish() here because doing it in onCreate(), onStart() or onResume() makes + // "adb shell am start" timeout if using the -W option. + finish(); + } + + private void handleIntent(Intent intent) { + DevicePolicyManager dpm = (DevicePolicyManager) + getSystemService(Context.DEVICE_POLICY_SERVICE); + String command = intent.getStringExtra(EXTRA_COMMAND); + Log.i(TAG, "Command: \"" + command); + + if (ADD_RESTRICTION_COMMAND.equals(command)) { + String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION_KEY); + dpm.addUserRestriction(BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); + Log.i(TAG, "Added user restriction " + restrictionKey + + " for user " + Process.myUserHandle()); + } else if (CLEAR_RESTRICTION_COMMAND.equals(command)) { + String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION_KEY); + dpm.clearUserRestriction( + BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); + Log.i(TAG, "Cleared user restriction " + restrictionKey + + " for user " + Process.myUserHandle()); + } else if (ADD_CROSS_PROFILE_WIDGET_COMMAND.equals(command)) { + String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME); + dpm.addCrossProfileWidgetProvider(BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, + packageName); + Log.i(TAG, "Added cross-profile widget provider for package:" + packageName + + " for user " + Process.myUserHandle()); + } else if (REMOVE_CROSS_PROFILE_WIDGET_COMMAND.equals(command)) { + String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME); + dpm.removeCrossProfileWidgetProvider(BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, + packageName); + Log.i(TAG, "Removed cross-profile widget provider for package:" + packageName + + " for user " + Process.myUserHandle()); + } else { + Log.e(TAG, "Invalid command: " + command); + } + } + +} \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/UserRestrictionActivity.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/UserRestrictionActivity.java deleted file mode 100644 index e8decf8..0000000 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/UserRestrictionActivity.java +++ /dev/null
@@ -1,83 +0,0 @@ -/* - * 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.managedprofile; - -import android.app.Activity; -import android.app.admin.DevicePolicyManager; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.Process; -import android.util.Log; - -import com.android.cts.managedprofile.BaseManagedProfileTest; - -/** - * Simple activity that adds or clears a user restriction depending on the value of the extras. - */ -public class UserRestrictionActivity extends Activity { - - private static final String TAG = UserRestrictionActivity.class.getName(); - - private static final String EXTRA_RESTRICTION_KEY = "extra-restriction-key"; - private static final String EXTRA_COMMAND = "extra-command"; - - private static final String ADD_COMMAND = "add-restriction"; - private static final String CLEAR_COMMAND = "clear-restriction"; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - handleIntent(getIntent()); - } - - // Overriding this method in case another intent is sent to this activity before finish() - @Override - public void onNewIntent(Intent intent) { - super.onNewIntent(intent); - handleIntent(intent); - } - - @Override - public void onPause() { - super.onPause(); - // Calling finish() here because doing it in onCreate(), onStart() or onResume() makes - // "adb shell am start" timeout if using the -W option. - finish(); - } - - private void handleIntent(Intent intent) { - DevicePolicyManager dpm = (DevicePolicyManager) - getSystemService(Context.DEVICE_POLICY_SERVICE); - String restrictionKey = intent.getStringExtra(EXTRA_RESTRICTION_KEY); - String command = intent.getStringExtra(EXTRA_COMMAND); - Log.i(TAG, "Command: \"" + command + "\". Restriction: \"" + restrictionKey + "\""); - - if (ADD_COMMAND.equals(command)) { - dpm.addUserRestriction(BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); - Log.i(TAG, "Added user restriction " + restrictionKey - + " for user " + Process.myUserHandle()); - } else if (CLEAR_COMMAND.equals(command)) { - dpm.clearUserRestriction( - BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, restrictionKey); - Log.i(TAG, "Cleared user restriction " + restrictionKey - + " for user " + Process.myUserHandle()); - } else { - Log.e(TAG, "Invalid command: " + command); - } - } - -} \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java new file mode 100644 index 0000000..c4c02e8 --- /dev/null +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
@@ -0,0 +1,142 @@ +/* + * Copyright (C) 2015 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.managedprofile; + +import android.content.Context; +import android.content.Intent; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.os.SystemClock; +import android.test.AndroidTestCase; + +import java.util.concurrent.TimeUnit; + +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID; + +/** + * Driven by the host-side test: com.android.cts.devicepolicy.ManagedProfileTest + * + * Each of these tests can run independently but have side-effects. The side-effects are used as + * building blocks to test various cleanup routines, for example that networks belonging to one + * user are deleted + */ +public class WifiTest extends AndroidTestCase { + private static final String TAG = WifiTest.class.getSimpleName(); + + // Unique SSID to use for this test (max SSID length is 32) + private static final String NETWORK_SSID = "com.android.cts.xwde7ktvh8rmjuhr"; + + // Time duration to allow before assuming that a WiFi operation failed and ceasing to wait. + private static final long UPDATE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(30); + private static final long UPDATE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(1); + + // Shared WifiManager instance. + private WifiManager mWifiManager; + + @Override + public void setUp() throws Exception { + super.setUp(); + mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE); + } + + /** + * Add a network through the WifiManager API. Verifies that the network was actually added. + * + * <p>Side effects: + * <ul> + * <li>Network with SSID {@link WifiTest#NETWORK_SSID} is created.</li> + * </ul> + */ + public void testAddWifiNetwork() throws Exception { + Intent intent = new Intent(ACTION_CREATE_WIFI_CONFIG); + intent.putExtra(EXTRA_SSID, NETWORK_SSID); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getContext().startActivity(intent); + + // Wait for configuration to appear in networks list. + assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ true)); + } + + /** + * Remove any network through the WifiManager API with a certain SSID. Verifies that the network + * was actually removed. + * + * <p>Side effects: + * <ul> + * <li>If a network with SSID {@link WifiTest#NETWORK_SSID} exists, it will be deleted.</li> + * </ul> + */ + public void testRemoveWifiNetworkIfExists() throws Exception { + WifiConfiguration config = getNetworkForSsid(NETWORK_SSID); + + if (config != null && config.networkId != -1) { + Intent intent = new Intent(ACTION_REMOVE_WIFI_CONFIG); + intent.putExtra(EXTRA_NETID, config.networkId); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getContext().startActivity(intent); + } + + assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ false)); + } + + /** + * Verify that no network exists with a certain SSID. + * + * <p>The SSID that will be checked for is {@link WifiTest#NETWORK_SSID}. + */ + public void testWifiNetworkDoesNotExist() throws Exception { + assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ false)); + } + + /** + * Block until a network configuration with a certain SSID either exists or ceases to. + * Wait for up to {@link WifiTest#UPDATE_TIMEOUT_MS} milliseconds, in increments of + * {@link WifiTest#UPDATE_INTERVAL_MS}. + */ + private boolean awaitNetworkState(String ssid, boolean exists) { + for (int probes = 0; probes * UPDATE_INTERVAL_MS <= UPDATE_TIMEOUT_MS; probes++) { + if (probes != 0) { + SystemClock.sleep(UPDATE_INTERVAL_MS); + } + if ((getNetworkForSsid(ssid) != null) == exists) { + return true; + } + } + return false; + } + + /** + * Internal method to find an existing {@link WifiConfiguration} with the given SSID. + * + * @return A {@link WifiConfiguration} matching the specification, or {@code null} if no such + * configuration exists. + */ + private WifiConfiguration getNetworkForSsid(String ssid) { + if (!ssid.startsWith("\"")) { + ssid = '"' + ssid + '"'; + } + for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) { + if (ssid.equals(config.SSID)) { + return config; + } + } + return null; + } +}
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java index 76a9e44..9646e61 100644 --- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java +++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WipeDataTest.java
@@ -64,11 +64,4 @@ // Verify the profile is deleted assertFalse(mUserManager.getUserProfiles().contains(currentUser)); } - - // Override this test inherited from base class, as it will trigger another round of setUp() - // which would fail because the managed profile has been removed by this test. - @Override - @Ignore - public void testAndroidTestCaseSetupProperly() { - } }
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk b/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk new file mode 100644 index 0000000..e68c884 --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_PACKAGE_NAME := CtsPackageInstallerApp + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := android.test.runner + +LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 ctstestrunner ub-uiautomator + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/AndroidManifest.xml b/hostsidetests/devicepolicy/app/PackageInstaller/AndroidManifest.xml new file mode 100644 index 0000000..aaa88f2 --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/AndroidManifest.xml
@@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.packageinstaller"> + + <uses-sdk android:minSdkVersion="21"/> + + <application> + <uses-library android:name="android.test.runner" /> + + <receiver + android:name=".ClearDeviceOwnerTest$BasicAdminReceiver" + android:permission="android.permission.BIND_DEVICE_ADMIN"> + <meta-data android:name="android.app.device_admin" + android:resource="@xml/device_admin" /> + <intent-filter> + <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> + </intent-filter> + </receiver> + </application> + + <instrumentation + android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.packageinstaller" + android:label="Package Installer CTS Tests" /> + +</manifest>
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/res/xml/device_admin.xml b/hostsidetests/devicepolicy/app/PackageInstaller/res/xml/device_admin.xml new file mode 100644 index 0000000..de4a9e1 --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/res/xml/device_admin.xml
@@ -0,0 +1,3 @@ +<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> + <uses-policies /> +</device-admin>
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/BasePackageInstallTest.java b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/BasePackageInstallTest.java new file mode 100644 index 0000000..f994e9e --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/BasePackageInstallTest.java
@@ -0,0 +1,198 @@ +/* + * Copyright (C) 2015 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.packageinstaller; + +import android.app.PendingIntent; +import android.app.admin.DevicePolicyManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.IntentSender; +import android.content.pm.PackageInfo; +import android.content.pm.PackageInstaller; +import android.content.pm.PackageManager; +import android.support.test.uiautomator.UiDevice; +import android.test.InstrumentationTestCase; + +import com.android.cts.packageinstaller.ClearDeviceOwnerTest.BasicAdminReceiver; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Base test case for testing PackageInstaller. + */ +public class BasePackageInstallTest extends InstrumentationTestCase { + protected static final String TEST_APP_LOCATION = "/data/local/tmp/CtsSimpleApp.apk"; + protected static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp"; + protected static final int PACKAGE_INSTALLER_TIMEOUT_MS = 60000; // 60 seconds + private static final String ACTION_INSTALL_COMMIT = + "com.android.cts.deviceowner.INTENT_PACKAGE_INSTALL_COMMIT"; + protected static final int PACKAGE_INSTALLER_STATUS_UNDEFINED = -1000; + public static final String PACKAGE_NAME = SilentPackageInstallTest.class.getPackage().getName(); + + protected Context mContext; + protected UiDevice mDevice; + protected DevicePolicyManager mDevicePolicyManager; + private PackageManager mPackageManager; + private PackageInstaller mPackageInstaller; + private PackageInstaller.Session mSession; + protected boolean mCallbackReceived; + protected int mCallbackStatus; + protected Intent mCallbackIntent; + + protected final Object mPackageInstallerTimeoutLock = new Object(); + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + synchronized (mPackageInstallerTimeoutLock) { + mCallbackStatus = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, + PACKAGE_INSTALLER_STATUS_UNDEFINED); + if (mCallbackStatus == PackageInstaller.STATUS_SUCCESS) { + mContext.unregisterReceiver(this); + assertEquals(TEST_APP_PKG, intent.getStringExtra( + PackageInstaller.EXTRA_PACKAGE_NAME)); + } else if (mCallbackStatus == PackageInstaller.STATUS_PENDING_USER_ACTION) { + mCallbackIntent = (Intent) intent.getExtras().get(Intent.EXTRA_INTENT); + } + mCallbackReceived = true; + mPackageInstallerTimeoutLock.notify(); + } + } + }; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mContext = getInstrumentation().getContext(); + mDevice = UiDevice.getInstance(getInstrumentation()); + mDevicePolicyManager = (DevicePolicyManager) + mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); + mPackageManager = mContext.getPackageManager(); + mPackageInstaller = mPackageManager.getPackageInstaller(); + assertNotNull(mPackageInstaller); + + // check that app is not already installed + assertFalse(isPackageInstalled(TEST_APP_PKG)); + } + + @Override + protected void tearDown() throws Exception { + if (mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME) || + mDevicePolicyManager.isProfileOwnerApp(PACKAGE_NAME)) { + mDevicePolicyManager.setUninstallBlocked(getWho(), TEST_APP_PKG, false); + } + try { + mContext.unregisterReceiver(mBroadcastReceiver); + } catch (IllegalArgumentException e) { + // ignore + } + if (mSession != null) { + mSession.abandon(); + } + super.tearDown(); + } + + protected static ComponentName getWho() { + return new ComponentName(PACKAGE_NAME, BasicAdminReceiver.class.getName()); + } + + protected void assertInstallPackage() throws Exception { + assertFalse(isPackageInstalled(TEST_APP_PKG)); + synchronized (mPackageInstallerTimeoutLock) { + mCallbackReceived = false; + mCallbackStatus = PACKAGE_INSTALLER_STATUS_UNDEFINED; + } + installPackage(TEST_APP_LOCATION); + synchronized (mPackageInstallerTimeoutLock) { + try { + mPackageInstallerTimeoutLock.wait(PACKAGE_INSTALLER_TIMEOUT_MS); + } catch (InterruptedException e) { + } + assertTrue(mCallbackReceived); + assertEquals(PackageInstaller.STATUS_SUCCESS, mCallbackStatus); + } + assertTrue(isPackageInstalled(TEST_APP_PKG)); + } + + protected boolean tryUninstallPackage() throws Exception { + assertTrue(isPackageInstalled(TEST_APP_PKG)); + synchronized (mPackageInstallerTimeoutLock) { + mCallbackReceived = false; + mCallbackStatus = PACKAGE_INSTALLER_STATUS_UNDEFINED; + } + mPackageInstaller.uninstall(TEST_APP_PKG, getCommitCallback(0)); + synchronized (mPackageInstallerTimeoutLock) { + try { + mPackageInstallerTimeoutLock.wait(PACKAGE_INSTALLER_TIMEOUT_MS); + } catch (InterruptedException e) { + } + assertTrue(mCallbackReceived); + return mCallbackStatus == PackageInstaller.STATUS_SUCCESS; + } + } + + protected void installPackage(String packageLocation) throws Exception { + PackageInstaller.SessionParams params = new PackageInstaller.SessionParams( + PackageInstaller.SessionParams.MODE_FULL_INSTALL); + int sessionId = mPackageInstaller.createSession(params); + mSession = mPackageInstaller.openSession(sessionId); + + File file = new File(packageLocation); + InputStream in = new FileInputStream(file); + OutputStream out = mSession.openWrite("SilentPackageInstallerTest", 0, file.length()); + byte[] buffer = new byte[65536]; + int c; + while ((c = in.read(buffer)) != -1) { + out.write(buffer, 0, c); + } + mSession.fsync(out); + out.close(); + mSession.commit(getCommitCallback(sessionId)); + mSession.close(); + } + + private IntentSender getCommitCallback(int sessionId) { + // Create an intent-filter and register the receiver + String action = ACTION_INSTALL_COMMIT + "." + sessionId; + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(action); + mContext.registerReceiver(mBroadcastReceiver, intentFilter); + + // Create a PendingIntent and use it to generate the IntentSender + Intent broadcastIntent = new Intent(action); + PendingIntent pendingIntent = PendingIntent.getBroadcast( + mContext, + sessionId, + broadcastIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + return pendingIntent.getIntentSender(); + } + + protected boolean isPackageInstalled(String packageName) { + try { + PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0); + return pi != null; + } catch (PackageManager.NameNotFoundException e) { + return false; + } + } +}
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ClearDeviceOwnerTest.java b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ClearDeviceOwnerTest.java new file mode 100644 index 0000000..a06271b --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ClearDeviceOwnerTest.java
@@ -0,0 +1,76 @@ +/* + * Copyright (C) 2015 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.packageinstaller; + +import android.app.admin.DeviceAdminReceiver; +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.test.InstrumentationTestCase; + +/** + * Base class for profile and device based tests. + * + * This class handles making sure that the test is the profile or device owner and that it has an + * active admin registered, so that all tests may assume these are done. + */ +public class ClearDeviceOwnerTest extends InstrumentationTestCase { + + public static class BasicAdminReceiver extends DeviceAdminReceiver { + } + + public static final String PACKAGE_NAME = BasicAdminReceiver.class.getPackage().getName(); + public static final ComponentName ADMIN_RECEIVER_COMPONENT = new ComponentName( + PACKAGE_NAME, BasicAdminReceiver.class.getName()); + + private DevicePolicyManager mDevicePolicyManager; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mDevicePolicyManager = (DevicePolicyManager) + getInstrumentation().getContext().getSystemService(Context.DEVICE_POLICY_SERVICE); + assertNotNull(mDevicePolicyManager); + + assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT)); + assertTrue("App is not device owner", mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME)); + } + + @Override + protected void tearDown() throws Exception { + removeActiveAdmin(ADMIN_RECEIVER_COMPONENT); + mDevicePolicyManager.clearDeviceOwnerApp(PACKAGE_NAME); + assertFalse(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT)); + assertFalse(mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME)); + + super.tearDown(); + } + + // This test clears the device owner and active admin on tearDown(). To be called from the host + // side test once a test case is finished. + public void testClearDeviceOwner() { + } + + private void removeActiveAdmin(ComponentName cn) throws InterruptedException { + if (mDevicePolicyManager.isAdminActive(cn)) { + mDevicePolicyManager.removeActiveAdmin(cn); + for (int i = 0; i < 1000 && mDevicePolicyManager.isAdminActive(cn); i++) { + Thread.sleep(100); + } + } + } +}
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ManualPackageInstallTest.java b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ManualPackageInstallTest.java new file mode 100644 index 0000000..96affae --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/ManualPackageInstallTest.java
@@ -0,0 +1,117 @@ +/* + * Copyright (C) 2015 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.packageinstaller; + +import android.content.Intent; +import android.content.pm.PackageInstaller; +import android.support.test.uiautomator.By; +import android.support.test.uiautomator.BySelector; +import android.support.test.uiautomator.UiObject2; +import android.support.test.uiautomator.Until; + +/** + * This class tests manual package install and uninstall by a device owner. + */ +public class ManualPackageInstallTest extends BasePackageInstallTest { + private static final int AUTOMATOR_WAIT_TIMEOUT = 5000; + private static final int INSTALL_WAIT_TIME = 5000; + + private static final BySelector POPUP_BUTTON_SELECTOR = By + .clazz(android.widget.Button.class.getName()) + .res("android:id/button1") + .pkg("com.google.android.packageinstaller"); + private static final BySelector POPUP_TEXT_SELECTOR = By + .clazz(android.widget.TextView.class.getName()) + .res("android:id/alertTitle") + .pkg("com.google.android.packageinstaller"); + private static final BySelector INSTALL_BUTTON_SELECTOR = By + .clazz(android.widget.Button.class.getName()) + .res("com.android.packageinstaller:id/ok_button") + .pkg("com.google.android.packageinstaller"); + + public void testManualInstallSucceeded() throws Exception { + assertInstallPackage(); + } + + public void testManualInstallBlocked() throws Exception { + synchronized (mPackageInstallerTimeoutLock) { + mCallbackReceived = false; + mCallbackStatus = PACKAGE_INSTALLER_STATUS_UNDEFINED; + } + // Calls the original installPackage which does not click through the install button. + super.installPackage(TEST_APP_LOCATION); + synchronized (mPackageInstallerTimeoutLock) { + try { + mPackageInstallerTimeoutLock.wait(PACKAGE_INSTALLER_TIMEOUT_MS); + } catch (InterruptedException e) { + } + assertTrue(mCallbackReceived); + assertEquals(PackageInstaller.STATUS_PENDING_USER_ACTION, mCallbackStatus); + } + + mCallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(mCallbackIntent); + + automateDismissInstallBlockedDialog(); + + // Assuming installation is not synchronous, we should wait a while before checking. + Thread.sleep(INSTALL_WAIT_TIME); + assertFalse(isPackageInstalled(TEST_APP_PKG)); + } + + @Override + protected void installPackage(String packageLocation) throws Exception { + super.installPackage(packageLocation); + + synchronized (mPackageInstallerTimeoutLock) { + try { + mPackageInstallerTimeoutLock.wait(PACKAGE_INSTALLER_TIMEOUT_MS); + } catch (InterruptedException e) { + } + assertTrue(mCallbackReceived); + assertEquals(PackageInstaller.STATUS_PENDING_USER_ACTION, mCallbackStatus); + } + + // Use a receiver to listen for package install. + synchronized (mPackageInstallerTimeoutLock) { + mCallbackReceived = false; + mCallbackStatus = PACKAGE_INSTALLER_STATUS_UNDEFINED; + } + + mCallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(mCallbackIntent); + + automateInstallClick(); + } + + private void automateInstallClick() { + mDevice.wait(Until.hasObject(INSTALL_BUTTON_SELECTOR), AUTOMATOR_WAIT_TIMEOUT); + UiObject2 button = mDevice.findObject(INSTALL_BUTTON_SELECTOR); + assertNotNull("Install button not found", button); + button.click(); + } + + private void automateDismissInstallBlockedDialog() { + mDevice.wait(Until.hasObject(POPUP_TEXT_SELECTOR), AUTOMATOR_WAIT_TIMEOUT); + UiObject2 text = mDevice.findObject(POPUP_TEXT_SELECTOR); + assertNotNull("Alert dialog not found", text); + // "OK" button only present in the dialog if it is blocked by policy. + UiObject2 button = mDevice.findObject(POPUP_BUTTON_SELECTOR); + assertNotNull("OK button not found", button); + button.click(); + } +}
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/SilentPackageInstallTest.java b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/SilentPackageInstallTest.java new file mode 100644 index 0000000..f1a80b9 --- /dev/null +++ b/hostsidetests/devicepolicy/app/PackageInstaller/src/com/android/cts/packageinstaller/SilentPackageInstallTest.java
@@ -0,0 +1,48 @@ +/* + * Copyright (C) 2015 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.packageinstaller; + +/** + * This class tests silent package install and uninstall by a device owner. + */ +public class SilentPackageInstallTest extends BasePackageInstallTest { + public void testSilentInstallUninstall() throws Exception { + // install the app + assertInstallPackage(); + + // uninstall the app again + assertTrue(tryUninstallPackage()); + assertFalse(isPackageInstalled(TEST_APP_PKG)); + } + + public void testUninstallBlocked() throws Exception { + // install the app + assertInstallPackage(); + + mDevicePolicyManager.setUninstallBlocked(getWho(), TEST_APP_PKG, true); + assertTrue(mDevicePolicyManager.isUninstallBlocked(getWho(), TEST_APP_PKG)); + assertTrue(mDevicePolicyManager.isUninstallBlocked(null, TEST_APP_PKG)); + assertFalse(tryUninstallPackage()); + assertTrue(isPackageInstalled(TEST_APP_PKG)); + + mDevicePolicyManager.setUninstallBlocked(getWho(), TEST_APP_PKG, false); + assertFalse(mDevicePolicyManager.isUninstallBlocked(getWho(), TEST_APP_PKG)); + assertFalse(mDevicePolicyManager.isUninstallBlocked(null, TEST_APP_PKG)); + assertTrue(tryUninstallPackage()); + assertFalse(isPackageInstalled(TEST_APP_PKG)); + } +}
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/SimpleApp/AndroidManifest.xml index 848317c..791ae56 100644 --- a/hostsidetests/devicepolicy/app/SimpleApp/AndroidManifest.xml +++ b/hostsidetests/devicepolicy/app/SimpleApp/AndroidManifest.xml
@@ -18,6 +18,8 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.cts.launcherapps.simpleapp"> + <uses-permission android:name="android.permission.READ_CONTACTS"/> + <application> <activity android:name=".SimpleActivity" > <intent-filter> @@ -31,6 +33,18 @@ <activity android:name=".NonLauncherActivity"> android:exported="true"> </activity> + <activity android:name=".SimpleActivityImmediateExit" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + <activity android:name=".SimpleActivityChainExit" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> </application> </manifest>
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityChainExit.java b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityChainExit.java new file mode 100644 index 0000000..49f14da --- /dev/null +++ b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityChainExit.java
@@ -0,0 +1,80 @@ +/* + * Copyright (C) 2015 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.launcherapps.simpleapp; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; + +/** + * This activity starts another activity. Once the other activity gets terminated, this one will + * terminate as well. + */ +public class SimpleActivityChainExit extends Activity { + private static final String TAG = "SimpleActivityChainExit"; + // This action. + private final static String ACTIVITY_CHAIN_EXIT_ACTION = + "com.android.cts.launchertests.LauncherAppsTests.CHAIN_EXIT_ACTION"; + // The action which will be called from here and then immediately exit again. + private static final String SIMPLE_ACTIVITY_IMMEDIATE_EXIT = ".SimpleActivityImmediateExit"; + // Our package name. + private static final String SIMPLE_PACKAGE_NAME = "com.android.cts.launcherapps.simpleapp"; + // Set to true once the activity was paused. Upon next resume the activity gets finished. + private boolean mPaused = false; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + Log.i(TAG, "Created SimpleActivityChainExit."); + } + + @Override + public void onStart() { + super.onStart(); + // Start our second activity which will quit itself immediately giving back control. + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setClassName(SIMPLE_PACKAGE_NAME, + SIMPLE_PACKAGE_NAME + SIMPLE_ACTIVITY_IMMEDIATE_EXIT); + startActivityForResult(intent, 0); + } + + @Override + public void onPause() { + super.onPause(); + mPaused = true; + } + + @Override + public void onResume() { + super.onResume(); + // We ignore any resumes coming in before we got at least paused once. + if (mPaused) { + // Since we were paused once we can finish ourselves now. + finish(); + } + } + + @Override + protected void onStop() { + super.onStop(); + // Notify a listener that this activity will end now. + Intent reply = new Intent(); + reply.setAction(ACTIVITY_CHAIN_EXIT_ACTION); + sendBroadcast(reply); + } +}
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityImmediateExit.java b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityImmediateExit.java new file mode 100644 index 0000000..15cc3f6 --- /dev/null +++ b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleActivityImmediateExit.java
@@ -0,0 +1,52 @@ +/* + * Copyright (C) 2015 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.launcherapps.simpleapp; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; + +/** + * A simple activity which quits itself immediately after starting. + */ +public class SimpleActivityImmediateExit extends Activity { + private final static String ACTIVITY_EXIT_ACTION = + "com.android.cts.launchertests.LauncherAppsTests.EXIT_ACTION"; + private static final String TAG = "SimpleActivityImmediateExit"; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + Log.i(TAG, "Created SimpleActivityImmediateExit."); + } + + @Override + public void onStart() { + super.onStart(); + finish(); + } + + @Override + protected void onStop() { + super.onStop(); + // Notify any listener that this activity is about to end now. + Intent reply = new Intent(); + reply.setAction(ACTIVITY_EXIT_ACTION); + sendBroadcast(reply); + } +}
diff --git a/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk new file mode 100644 index 0000000..7460552 --- /dev/null +++ b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +# This app is meant for testing device policy permission APIs on legacy apps (pre-M) + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# Don't include this package in any target. +LOCAL_MODULE_TAGS := optional + +# When built, explicitly put it in the data partition. +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsSimplePreMApp + +LOCAL_SDK_VERSION := 21 + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/SimplePreMApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/SimplePreMApp/AndroidManifest.xml new file mode 100644 index 0000000..85962a1 --- /dev/null +++ b/hostsidetests/devicepolicy/app/SimplePreMApp/AndroidManifest.xml
@@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.launcherapps.simplepremapp"> + + <uses-sdk android:targetSdkVersion="21"/> + + <uses-permission android:name="android.permission.READ_CONTACTS"/> + + <application> + <activity android:name=".SimpleActivity" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> + +</manifest> +
diff --git a/hostsidetests/devicepolicy/app/SimplePreMApp/src/com/android/cts/launcherapps/simplepremapp/SimpleActivity.java b/hostsidetests/devicepolicy/app/SimplePreMApp/src/com/android/cts/launcherapps/simplepremapp/SimpleActivity.java new file mode 100644 index 0000000..0dba719 --- /dev/null +++ b/hostsidetests/devicepolicy/app/SimplePreMApp/src/com/android/cts/launcherapps/simplepremapp/SimpleActivity.java
@@ -0,0 +1,39 @@ +/* + * Copyright (C) 2015 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.launcherapps.simplepremapp; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; + +import java.lang.Override; + +/** + * A simple activity to install for various users to test LauncherApps. + */ +public class SimpleActivity extends Activity { + + private static final String TAG = "SimpleActivity"; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + Log.i(TAG, "Created for user " + android.os.Process.myUserHandle()); + } + +}
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk b/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk new file mode 100644 index 0000000..c0e35fa --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk
@@ -0,0 +1,29 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_PACKAGE_NAME := CtsWidgetProviderApp + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/AndroidManifest.xml b/hostsidetests/devicepolicy/app/WidgetProvider/AndroidManifest.xml new file mode 100644 index 0000000..77246b5 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/AndroidManifest.xml
@@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.widgetprovider"> + + <uses-permission android:name="android.permission.BIND_APPWIDGET"/> + + <application> + <receiver android:name="SimpleWidgetProvider" > + <intent-filter> + <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> + </intent-filter> + <meta-data android:name="android.appwidget.provider" + android:resource="@xml/simple_widget_provider_info" /> + </receiver> + <service android:name=".SimpleAppWidgetHostService" > + <intent-filter> + <action android:name="com.android.cts.widgetprovider.REGISTER_CALLBACK" /> + </intent-filter> + </service> + </application> + +</manifest> +
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/res/layout/simple_widget.xml b/hostsidetests/devicepolicy/app/WidgetProvider/res/layout/simple_widget.xml new file mode 100644 index 0000000..338c57a --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/res/layout/simple_widget.xml
@@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2015 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. +--> + +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="horizontal" + android:padding="10dip"> + + <ImageView + android:id="@+id/pkg_icon" + android:layout_width="wrap_content" + android:layout_height="match_parent"/> + + <TextView + android:id="@+id/pkg_name" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:layout_centerVertical="true" + android:paddingLeft="10dip" + android:layout_toRightOf="@id/pkg_icon"/> + +</RelativeLayout> \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/res/xml/simple_widget_provider_info.xml b/hostsidetests/devicepolicy/app/WidgetProvider/res/xml/simple_widget_provider_info.xml new file mode 100644 index 0000000..8a002d2 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/res/xml/simple_widget_provider_info.xml
@@ -0,0 +1,20 @@ +<!-- Copyright (C) 2015 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. +--> +<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" + android:minWidth="40dp" + android:minHeight="40dp" + android:resizeMode="horizontal|vertical" + android:widgetCategory="home_screen"> +</appwidget-provider> \ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleAppWidgetHostService.java b/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleAppWidgetHostService.java new file mode 100644 index 0000000..b5b6003 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleAppWidgetHostService.java
@@ -0,0 +1,246 @@ +/* + * Copyright (C) 2015 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.widgetprovider; + +import android.app.Service; +import android.appwidget.AppWidgetHost; +import android.appwidget.AppWidgetHostView; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProviderInfo; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.os.UserHandle; +import android.os.UserManager; +import android.util.Log; +import android.widget.RemoteViews; + +import java.util.List; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Service that acts as AppWidgetHost that listens to onProvidersChanged callbacks and updates the + * internally stored list of profile widgets. The service reacts to messages sent from the device + * side tests and returns whether the expected widget provider is currently present or not. + */ +public class SimpleAppWidgetHostService extends Service { + private static final String TAG = "SimpleAppWidgetHostService"; + + private static final int MSG_RESULT = 0; + private static final int MSG_PROVIDER_PRESENT = 1; + private static final int MSG_PROVIDER_UPDATES = 2; + + private static final int RESULT_UNKNOWN = 0; + private static final int RESULT_PRESENT = 1; + private static final int RESULT_NOT_PRESENT = 2; + private static final int RESULT_INTERRUPTED = 3; + private static final int RESULT_TIMEOUT = 4; + + public static final String USER_EXTRA = "user-extra"; + public static final String PACKAGE_EXTRA = "package-extra"; + public static final String REPLY_EXTRA = "reply-extra"; + + private AppWidgetManager mAppWidgetManager; + private SimpleAppWidgetHost mAppWidgetHost; + private SimpleAppWidgetHostView mAppWidgetHostView; + private int mAppWidgetId; + private Messenger mMessenger; + private UserHandle mUserHandle; + private Semaphore mWidgetUpdateSemaphore = new Semaphore(0); + private RemoteViews mRemoteViews; + + class CheckHandler extends Handler { + public CheckHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + Bundle params = null; + if (msg.obj instanceof Bundle) { + params = (Bundle) (msg.obj); + } + try { + switch (msg.what) { + case MSG_PROVIDER_PRESENT: { + Log.d(TAG, "MSG_PROVIDER_PRESENT"); + int result = RESULT_UNKNOWN; + try { + AppWidgetProviderInfo info = mAppWidgetHost.getProvider(params); + result = (info != null) ? RESULT_PRESENT : RESULT_NOT_PRESENT; + if (info != null) { + bindAppWidget(info); + } + } catch (InterruptedException e) { + result = RESULT_INTERRUPTED; + } + msg.replyTo.send(Message.obtain(null, MSG_RESULT, result + , 0 /* not used */)); + break; + } + case MSG_PROVIDER_UPDATES: { + Log.d(TAG, "MSG_PROVIDER_UPDATES"); + int result = RESULT_UNKNOWN; + try { + updateWidgetViaWidgetId(); + boolean update = waitForUpdate(); + result = update ? RESULT_PRESENT : RESULT_NOT_PRESENT; + } catch (InterruptedException e) { + result = RESULT_INTERRUPTED; + } + msg.replyTo.send(Message.obtain(null, MSG_RESULT, result + , 0 /* not used */)); + break; + } + default: + super.handleMessage(msg); + } + } catch (RemoteException e) { + Log.e(TAG, "Failed to report test status"); + } + } + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent == null) { + return START_NOT_STICKY; + } + if ("com.android.cts.widgetprovider.REGISTER_CALLBACK".equals(intent.getAction())) { + mUserHandle = getUserHandleArgument(this, USER_EXTRA, intent); + Log.d(TAG, "mUserHandle=" + mUserHandle); + setup(); + } + return START_STICKY; + } + + private void setup() { + HandlerThread handlerThread = new HandlerThread("Widget test callback handler"); + handlerThread.start(); + mMessenger = new Messenger(new CheckHandler(handlerThread.getLooper())); + mAppWidgetManager = (AppWidgetManager) getSystemService(Context.APPWIDGET_SERVICE); + mAppWidgetHost = new SimpleAppWidgetHost(this, 0); + mAppWidgetHost.deleteHost(); + mAppWidgetHost.startListening(); + } + + @Override + public IBinder onBind(Intent intent) { + return mMessenger.getBinder(); + } + + @Override + public void onDestroy() { + mAppWidgetHost.stopListening(); + mAppWidgetHost.deleteAppWidgetId(mAppWidgetId); + mAppWidgetHost.deleteHost(); + } + + private void bindAppWidget(AppWidgetProviderInfo info) { + mAppWidgetId = mAppWidgetHost.allocateAppWidgetId(); + Log.d(TAG, "Registering app widget with id:" + mAppWidgetId); + mAppWidgetManager.bindAppWidgetIdIfAllowed(mAppWidgetId, mUserHandle, info.provider, null); + mAppWidgetHostView = (SimpleAppWidgetHostView) mAppWidgetHost.createView(this, + mAppWidgetId, info); + mRemoteViews = new RemoteViews(info.provider.getPackageName(), R.layout.simple_widget); + } + + private UserHandle getUserHandleArgument(Context context, String key, + Intent intent) { + UserManager um = (UserManager) getSystemService(Context.USER_SERVICE); + int serial = intent.getIntExtra(key, 0); + Log.d(TAG, "userId=" + serial); + return um.getUserForSerialNumber(serial); + } + + private void updateWidgetViaWidgetId() { + Log.d(TAG, "Forcing widget update via widget id"); + mWidgetUpdateSemaphore.drainPermits(); + // trigger a widget update + mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews); + } + + private boolean waitForUpdate() throws InterruptedException { + // wait for updateAppWidget to arrive + return mWidgetUpdateSemaphore.tryAcquire(20, TimeUnit.SECONDS); + } + + private class SimpleAppWidgetHost extends AppWidgetHost { + private List<AppWidgetProviderInfo> mProviders; + private Semaphore mSemaphore = new Semaphore(0); + public SimpleAppWidgetHost(Context context, int hostId) { + super(context, hostId); + synchronized (this) { + mProviders = mAppWidgetManager.getInstalledProvidersForProfile(mUserHandle); + } + } + + @Override + protected void onProvidersChanged() { + super.onProvidersChanged(); + Log.d(TAG, "onProvidersChanged callback received"); + synchronized (this) { + mProviders = mAppWidgetManager.getInstalledProvidersForProfile(mUserHandle); + } + mSemaphore.release(); + } + + @Override + protected AppWidgetHostView onCreateView(Context context, int id, AppWidgetProviderInfo info) { + return new SimpleAppWidgetHostView(context); + } + + public AppWidgetProviderInfo getProvider(Bundle params) throws InterruptedException { + String packageName = params.getString(PACKAGE_EXTRA); + while (mSemaphore.tryAcquire(30, TimeUnit.SECONDS)) { + mSemaphore.drainPermits(); + Log.d(TAG, "checking for " + packageName + " " + mUserHandle); + synchronized (this) { + for (AppWidgetProviderInfo providerInfo : mProviders) { + if (providerInfo.provider.getPackageName().equals(packageName)) { + Log.d(TAG, "Provider exists " + packageName + + " for user " + mUserHandle); + return providerInfo; + } + } + } + } + return null; + } + } + + private class SimpleAppWidgetHostView extends AppWidgetHostView { + public SimpleAppWidgetHostView(Context context) { + super(context); + } + + @Override + public void updateAppWidget(RemoteViews views) { + super.updateAppWidget(views); + Log.d(TAG, "Host view received widget update"); + mWidgetUpdateSemaphore.release(); + } + } +}
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleWidgetProvider.java b/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleWidgetProvider.java new file mode 100644 index 0000000..3bd4530 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WidgetProvider/src/com/android/cts/widgetprovider/SimpleWidgetProvider.java
@@ -0,0 +1,24 @@ +/* + * Copyright (C) 2015 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.widgetprovider; + +import android.appwidget.AppWidgetProvider; + +/** + * A simple widget provider to test cross-profile widgets. + */ +public class SimpleWidgetProvider extends AppWidgetProvider {}
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk new file mode 100644 index 0000000..47db44e --- /dev/null +++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# Don't include this package in any target. +LOCAL_MODULE_TAGS := optional + +# When built, explicitly put it in the data partition. +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsWifiConfigCreator + +LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util_v2 + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/AndroidManifest.xml b/hostsidetests/devicepolicy/app/WifiConfigCreator/AndroidManifest.xml new file mode 100644 index 0000000..1b98259 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/AndroidManifest.xml
@@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.deviceowner.wificonfigcreator"> + + <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> + <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> + + <application> + <activity android:name=".WifiConfigCreatorActivity" + android:exported="true" + android:theme="@android:style/Theme.NoDisplay" + android:noHistory="true" + android:autoRemoveFromRecents="true" + android:stateNotNeeded="true" > + <intent-filter> + <action android:name="com.android.compatibility.common.util.CREATE_WIFI_CONFIG" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <intent-filter> + <action android:name="com.android.compatibility.common.util.UPDATE_WIFI_CONFIG" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <intent-filter> + <action android:name="com.android.compatibility.common.util.REMOVE_WIFI_CONFIG" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> + +</manifest> +
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java b/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java new file mode 100644 index 0000000..af31030 --- /dev/null +++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java
@@ -0,0 +1,71 @@ +/* + * Copyright (C) 2015 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.deviceowner.wificonfigcreator; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; + +import com.android.compatibility.common.util.WifiConfigCreator; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_PASSWORD; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SECURITY_TYPE; +import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG; +import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_NONE; +import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_UPDATE_WIFI_CONFIG; + +/** + * A simple activity to create and manage wifi configurations. + */ +public class WifiConfigCreatorActivity extends Activity { + private static final String TAG = "WifiConfigCreatorActivity"; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + Log.i(TAG, "Created for user " + android.os.Process.myUserHandle()); + WifiConfigCreator configCreator = new WifiConfigCreator(this); + try { + Intent intent = getIntent(); + String action = intent.getAction(); + if (ACTION_CREATE_WIFI_CONFIG.equals(action)) { + String ssid = intent.getStringExtra(EXTRA_SSID); + int securityType = intent.getIntExtra(EXTRA_SECURITY_TYPE, SECURITY_TYPE_NONE); + String password = intent.getStringExtra(EXTRA_PASSWORD); + configCreator.addNetwork(ssid, false, securityType, password); + } else if (ACTION_UPDATE_WIFI_CONFIG.equals(action)) { + int netId = intent.getIntExtra(EXTRA_NETID, -1); + String ssid = intent.getStringExtra(EXTRA_SSID); + int securityType = intent.getIntExtra(EXTRA_SECURITY_TYPE, SECURITY_TYPE_NONE); + String password = intent.getStringExtra(EXTRA_PASSWORD); + configCreator.updateNetwork(netId, ssid, false, securityType, password); + } else if (ACTION_REMOVE_WIFI_CONFIG.equals(action)) { + int netId = intent.getIntExtra(EXTRA_NETID, -1); + if (netId != -1) { + configCreator.removeNetwork(netId); + } + } else { + Log.i(TAG, "Unknown command: " + action); + } + } finally { + finish(); + } + } +}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java index 5149a74..4fc14e4 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -17,7 +17,6 @@ package com.android.cts.devicepolicy; import com.android.cts.tradefed.build.CtsBuildHelper; -import com.android.cts.util.AbiUtils; import com.android.ddmlib.Log.LogLevel; import com.android.ddmlib.testrunner.InstrumentationResultParser; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; @@ -47,15 +46,11 @@ */ public class BaseDevicePolicyTest extends DeviceTestCase implements IBuildReceiver { - protected static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile"; - protected static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk"; - protected static final String ADMIN_RECEIVER_TEST_CLASS = - MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver"; + private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner"; - private static final String RUNNER = "android.test.InstrumentationTestRunner"; + protected CtsBuildHelper mCtsBuild; - private CtsBuildHelper mCtsBuild; - + private String mPackageVerifier; private HashSet<String> mAvailableFeatures; protected boolean mHasFeature; @@ -70,6 +65,18 @@ assertNotNull(mCtsBuild); // ensure build has been set before test is run. mHasFeature = getDevice().getApiLevel() >= 21 /* Build.VERSION_CODES.L */ && hasDeviceFeature("android.software.device_admin"); + // disable the package verifier to avoid the dialog when installing an app + mPackageVerifier = getDevice().executeShellCommand( + "settings get global package_verifier_enable"); + getDevice().executeShellCommand("settings put global package_verifier_enable 0"); + } + + @Override + protected void tearDown() throws Exception { + // reset the package verifier setting to its original value + getDevice().executeShellCommand("settings put global package_verifier_enable " + + mPackageVerifier); + super.tearDown(); } protected void installApp(String fileName) @@ -91,7 +98,7 @@ } final String result = device.executeShellCommand( - "pm install --user " + userId + " " + remotePath); + "pm install -r --user " + userId + " " + remotePath); assertTrue(result, result.contains("\nSuccess")); } @@ -103,8 +110,6 @@ CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); assertTrue(commandOutput + " expected to start with \"Success:\"", commandOutput.startsWith("Success:")); - // Wait 60 seconds for intents generated to be handled. - Thread.sleep(60 * 1000); } protected int getMaxNumberOfUsersSupported() throws DeviceNotAvailableException { @@ -144,12 +149,22 @@ } protected void removeUser(int userId) throws Exception { + String stopUserCommand = "am stop-user -w " + userId; + CLog.logAndDisplay(LogLevel.INFO, "starting command \"" + stopUserCommand + "\" and waiting."); + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + stopUserCommand + ": " + + getDevice().executeShellCommand(stopUserCommand)); String removeUserCommand = "pm remove-user " + userId; CLog.logAndDisplay(LogLevel.INFO, "starting command " + removeUserCommand); CLog.logAndDisplay(LogLevel.INFO, "Output for command " + removeUserCommand + ": " + getDevice().executeShellCommand(removeUserCommand)); - // Wait 60 seconds for user to finish being removed. - Thread.sleep(60 * 1000); + } + + protected void removeTestUsers() throws Exception { + for (int userId : listUsers()) { + if (userId != 0) { + removeUser(userId); + } + } } /** Returns true if the specified tests passed. Tests are run as user owner. */ @@ -169,9 +184,6 @@ protected boolean runDeviceTestsAsUser( String pkgName, @Nullable String testClassName, String testMethodName, int userId) throws DeviceNotAvailableException { - if (testClassName.startsWith(".")) { - testClassName = pkgName + testClassName; - } return runDeviceTests(pkgName, testClassName, testMethodName, userId); } @@ -184,6 +196,9 @@ protected boolean runDeviceTests(String pkgName, @Nullable String testClassName, @Nullable String testMethodName, @Nullable Integer userId, @Nullable String params) throws DeviceNotAvailableException { + if (testClassName != null && testClassName.startsWith(".")) { + testClassName = pkgName + testClassName; + } TestRunResult runResult = (userId == null && params == null) ? doRunTests(pkgName, testClassName, testMethodName) : doRunTestsAsUser(pkgName, testClassName, testMethodName, @@ -280,8 +295,6 @@ String[] tokens = commandOutput.split("\\s+"); assertTrue(tokens.length > 0); assertEquals("Success:", tokens[0]); - // Wait 60 seconds for intents generated to be handled. - Thread.sleep(60 * 1000); return Integer.parseInt(tokens[tokens.length-1]); } @@ -300,7 +313,6 @@ return Integer.parseInt(tokens[tokens.length-1]); } - protected int getUserSerialNumber(int userId) throws DeviceNotAvailableException{ // dumpsys user return lines like "UserInfo{0:Owner:13} serialNo=0" String commandOutput = getDevice().executeShellCommand("dumpsys user"); @@ -320,12 +332,50 @@ return -1; } - protected void setProfileOwner(String componentName, int userId) + protected boolean setProfileOwner(String componentName, int userId) throws DeviceNotAvailableException { - String command = "dpm set-profile-owner '" + componentName + "' " + userId; + String command = "dpm set-profile-owner --user " + userId + " '" + componentName + "'"; + String commandOutput = getDevice().executeShellCommand(command); + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); + return commandOutput.startsWith("Success:"); + } + + protected void setProfileOwnerOrFail(String componentName, int userId) + throws Exception { + if (!setProfileOwner(componentName, userId)) { + removeUser(userId); + fail("Failed to set profile owner"); + } + } + + protected void setDeviceAdmin(String componentName) throws DeviceNotAvailableException { + String command = "dpm set-active-admin '" + componentName + "'"; String commandOutput = getDevice().executeShellCommand(command); CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); assertTrue(commandOutput + " expected to start with \"Success:\"", commandOutput.startsWith("Success:")); } + + protected boolean setDeviceOwner(String componentName) throws DeviceNotAvailableException { + String command = "dpm set-device-owner '" + componentName + "'"; + String commandOutput = getDevice().executeShellCommand(command); + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); + return commandOutput.startsWith("Success:"); + } + + protected String getSettings(String namespace, String name, int userId) + throws DeviceNotAvailableException { + String command = "settings --user " + userId + " get " + namespace + " " + name; + String commandOutput = getDevice().executeShellCommand(command); + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); + return commandOutput.replace("\n", "").replace("\r", ""); + } + + protected void putSettings(String namespace, String name, String value, int userId) + throws DeviceNotAvailableException { + String command = "settings --user " + userId + " put " + namespace + " " + name + + " " + value; + String commandOutput = getDevice().executeShellCommand(command); + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); + } }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java index dec8bd2..b106ffd 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseLauncherAppsTest.java
@@ -45,14 +45,6 @@ getDevice().uninstallPackage(SIMPLE_APP_PKG); } - protected void removeTestUsers() throws Exception { - for (int userId : listUsers()) { - if (userId != 0) { - removeUser(userId); - } - } - } - protected void startCallbackService() throws Exception { String command = "am startservice --user 0 " + "-a " + LAUNCHER_TESTS_SUPPORT_PKG + ".REGISTER_CALLBACK "
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java new file mode 100644 index 0000000..8d22638 --- /dev/null +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
@@ -0,0 +1,154 @@ +/* + * Copyright (C) 2015 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.devicepolicy; + +import java.io.File; +import java.lang.Exception; + +/** + * This class is used for tests that need to do something special before setting the device + * owner, so they cannot use the regular DeviceOwnerTest class + */ +public class CustomDeviceOwnerTest extends BaseDevicePolicyTest { + + private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner"; + private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk"; + private static final String DEVICE_OWNER_ADMIN + = DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver"; + private static final String DEVICE_OWNER_ADMIN_COMPONENT + = DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN; + private static final String DEVICE_OWNER_CLEAR + = DEVICE_OWNER_PKG + ".ClearDeviceOwnerTest"; + + private static final String DEVICE_AND_PROFILE_OWNER_PKG + = "com.android.cts.deviceandprofileowner"; + protected static final String DEVICE_AND_PROFILE_OWNER_APK = "CtsDeviceAndProfileOwnerApp.apk"; + protected static final String DEVICE_AND_PROFILE_OWNER_ADMIN + = ".BaseDeviceAdminTest$BasicAdminReceiver"; + protected static final String DEVICE_AND_PROFILE_OWNER_ADMIN_COMPONENT + = DEVICE_AND_PROFILE_OWNER_PKG + "/" + DEVICE_AND_PROFILE_OWNER_ADMIN; + protected static final String DEVICE_AND_PROFILE_OWNER_CLEAR + = DEVICE_AND_PROFILE_OWNER_PKG + ".ClearDeviceOwnerTest"; + + private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver"; + private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk"; + + private static final String TEST_APP_APK = "CtsSimpleApp.apk"; + private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp"; + private static final String TEST_APP_LOCATION = "/data/local/tmp/"; + + private static final String PACKAGE_INSTALLER_PKG = "com.android.cts.packageinstaller"; + private static final String PACKAGE_INSTALLER_APK = "CtsPackageInstallerApp.apk"; + private static final String PACKAGE_INSTALLER_ADMIN_COMPONENT = + PACKAGE_INSTALLER_PKG + "/" + ".ClearDeviceOwnerTest$BasicAdminReceiver"; + private static final String PACKAGE_INSTALLER_CLEAR_DEVICE_OWNER_TEST_CLASS = + PACKAGE_INSTALLER_PKG + ".ClearDeviceOwnerTest"; + + @Override + public void tearDown() throws Exception { + if (mHasFeature) { + getDevice().uninstallPackage(DEVICE_OWNER_PKG); + getDevice().uninstallPackage(DEVICE_AND_PROFILE_OWNER_PKG); + } + + super.tearDown(); + } + + public void testOwnerChangedBroadcast() throws Exception { + if (!mHasFeature) { + return; + } + installApp(DEVICE_OWNER_APK); + try { + installApp(INTENT_RECEIVER_APK); + + String testClass = INTENT_RECEIVER_PKG + ".OwnerChangedBroadcastTest"; + + // Running this test also gets the intent receiver app out of the stopped state, so it + // can receive broadcast intents. + assertTrue(runDeviceTests(INTENT_RECEIVER_PKG, testClass, + "testOwnerChangedBroadcastNotReceived", 0)); + + // Setting the device owner should send the owner changed broadcast. + assertTrue(setDeviceOwner(DEVICE_OWNER_ADMIN_COMPONENT)); + + assertTrue(runDeviceTests(INTENT_RECEIVER_PKG, testClass, + "testOwnerChangedBroadcastReceived", 0)); + } finally { + getDevice().uninstallPackage(INTENT_RECEIVER_PKG); + assertTrue("Failed to remove device owner.", + runDeviceTests(DEVICE_OWNER_PKG, DEVICE_OWNER_CLEAR)); + } + } + + public void testCannotSetDeviceOwnerWhenSecondaryUserPresent() throws Exception { + if (!mHasFeature || getMaxNumberOfUsersSupported() < 2) { + return; + } + int userId = -1; + installApp(DEVICE_OWNER_APK); + try { + userId = createUser(); + assertFalse(setDeviceOwner(DEVICE_OWNER_ADMIN_COMPONENT)); + } finally { + removeUser(userId); + // make sure we clean up in case we succeeded in setting the device owner + runDeviceTests(DEVICE_OWNER_PKG, DEVICE_OWNER_CLEAR); + } + } + + public void testCannotSetDeviceOwnerWhenAccountPresent() throws Exception { + if (!mHasFeature) { + return; + } + installApp(DEVICE_AND_PROFILE_OWNER_APK); + try { + assertTrue(runDeviceTestsAsUser(DEVICE_AND_PROFILE_OWNER_PKG, ".AccountUtilsTest", + "testAddAccount", 0)); + assertFalse(setDeviceOwner(DEVICE_AND_PROFILE_OWNER_ADMIN_COMPONENT)); + } finally { + // make sure we clean up in case we succeeded in setting the device owner + runDeviceTests(DEVICE_AND_PROFILE_OWNER_PKG, DEVICE_AND_PROFILE_OWNER_CLEAR); + assertTrue(runDeviceTestsAsUser(DEVICE_AND_PROFILE_OWNER_PKG, ".AccountUtilsTest", + "testRemoveAccounts", 0)); + } + } + + public void testSilentPackageInstall() throws Exception { + if (!mHasFeature) { + return; + } + final File apk = mCtsBuild.getTestApp(TEST_APP_APK); + try { + // Install the test and prepare the test apk. + installApp(PACKAGE_INSTALLER_APK); + assertTrue(setDeviceOwner(PACKAGE_INSTALLER_ADMIN_COMPONENT)); + + getDevice().uninstallPackage(TEST_APP_PKG); + assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName())); + assertTrue(runDeviceTests(PACKAGE_INSTALLER_PKG, + PACKAGE_INSTALLER_PKG + ".SilentPackageInstallTest")); + } finally { + assertTrue("Failed to remove device owner.", runDeviceTests(PACKAGE_INSTALLER_PKG, + PACKAGE_INSTALLER_CLEAR_DEVICE_OWNER_TEST_CLASS)); + String command = "rm " + TEST_APP_LOCATION + apk.getName(); + String commandOutput = getDevice().executeShellCommand(command); + getDevice().uninstallPackage(TEST_APP_PKG); + getDevice().uninstallPackage(PACKAGE_INSTALLER_PKG); + } + } +}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java new file mode 100644 index 0000000..43e6730 --- /dev/null +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -0,0 +1,284 @@ +/* + * Copyright (C) 2015 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.devicepolicy; + +import com.android.ddmlib.Log.LogLevel; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.log.LogUtil.CLog; + +import java.io.File; + +/** + * Set of tests for usecases that apply to profile and device owner. + * This class is the base class of MixedProfileOwnerTest and MixedDeviceOwnerTest and is abstract + * to avoid running spurious tests. + */ +public abstract class DeviceAndProfileOwnerTest extends BaseDevicePolicyTest { + + protected static final String DEVICE_ADMIN_PKG = "com.android.cts.deviceandprofileowner"; + protected static final String DEVICE_ADMIN_APK = "CtsDeviceAndProfileOwnerApp.apk"; + protected static final String ADMIN_RECEIVER_TEST_CLASS + = ".BaseDeviceAdminTest$BasicAdminReceiver"; + + private static final String PERMISSIONS_APP_PKG = "com.android.cts.permissionapp"; + private static final String PERMISSIONS_APP_APK = "CtsPermissionApp.apk"; + + private static final String SIMPLE_PRE_M_APP_PKG = "com.android.cts.launcherapps.simplepremapp"; + private static final String SIMPLE_PRE_M_APP_APK = "CtsSimplePreMApp.apk"; + + private static final String CERT_INSTALLER_PKG = "com.android.cts.certinstaller"; + private static final String CERT_INSTALLER_APK = "CtsCertInstallerApp.apk"; + + private static final String TEST_APP_APK = "CtsSimpleApp.apk"; + private static final String TEST_APP_PKG = "com.android.cts.launcherapps.simpleapp"; + private static final String TEST_APP_LOCATION = "/data/local/tmp/"; + + private static final String PACKAGE_INSTALLER_PKG = "com.android.cts.packageinstaller"; + private static final String PACKAGE_INSTALLER_APK = "CtsPackageInstallerApp.apk"; + + protected static final int USER_OWNER = 0; + + private static final String ADD_RESTRICTION_COMMAND = "add-restriction"; + private static final String CLEAR_RESTRICTION_COMMAND = "clear-restriction"; + + // ID of the user all tests are run as. For device owner this will be 0, for profile owner it + // is the user id of the created profile. + protected int mUserId; + + @Override + protected void tearDown() throws Exception { + if (mHasFeature) { + getDevice().uninstallPackage(DEVICE_ADMIN_PKG); + getDevice().uninstallPackage(PERMISSIONS_APP_PKG); + getDevice().uninstallPackage(SIMPLE_PRE_M_APP_PKG); + getDevice().uninstallPackage(CERT_INSTALLER_PKG); + } + super.tearDown(); + } + + public void testApplicationRestrictions() throws Exception { + if (!mHasFeature) { + return; + } + executeDeviceTestClass(".ApplicationRestrictionsTest"); + } + + public void testPermissionGrant() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantState"); + } + + public void testPermissionPolicy() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionPolicy"); + } + + public void testPermissionMixedPolicies() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionMixedPolicies"); + } + + public void testPermissionPrompts() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionPrompts"); + } + + public void testPermissionAppUpdate() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_setDeniedState"); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkDenied"); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkDenied"); + + assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG)); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_setGrantedState"); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkGranted"); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkGranted"); + + assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG)); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_setAutoDeniedPolicy"); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkDenied"); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkDenied"); + + assertNull(getDevice().uninstallPackage(PERMISSIONS_APP_PKG)); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_setAutoGrantedPolicy"); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkGranted"); + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionUpdate_checkGranted"); + } + + public void testPermissionGrantPreMApp() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(SIMPLE_PRE_M_APP_APK, mUserId); + executeDeviceTestMethod(".PermissionsTest", "testPermissionGrantStatePreMApp"); + } + + public void testPersistentIntentResolving() throws Exception { + if (!mHasFeature) { + return; + } + executeDeviceTestClass(".PersistentIntentResolvingTest"); + } + + public void testScreenCaptureDisabled() throws Exception { + if (!mHasFeature) { + return; + } + // We need to ensure that the policy is deactivated for the device owner case, so making + // sure the second test is run even if the first one fails + try { + executeDeviceTestMethod(".ScreenCaptureDisabledTest", + "testSetScreenCaptureDisabled_true"); + } finally { + executeDeviceTestMethod(".ScreenCaptureDisabledTest", + "testSetScreenCaptureDisabled_false"); + } + } + + public void testApplicationHidden() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(PERMISSIONS_APP_APK, mUserId); + executeDeviceTestClass(".ApplicationHiddenTest"); + } + + public void testAccountManagement() throws Exception { + if (!mHasFeature) { + return; + } + + executeDeviceTestClass(".AccountManagementTest"); + + // Send a home intent to dismiss an error dialog. + String command = "am start -a android.intent.action.MAIN -c android.intent.category.HOME"; + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + + getDevice().executeShellCommand(command)); + } + + public void testDelegatedCertInstaller() throws Exception { + if (!mHasFeature) { + return; + } + installAppAsUser(CERT_INSTALLER_APK, mUserId); + installAppAsUser(DEVICE_ADMIN_APK, USER_OWNER); + setDeviceAdmin(DEVICE_ADMIN_PKG + "/.PrimaryUserDeviceAdmin"); + + final String adminHelperClass = ".PrimaryUserAdminHelper"; + try { + // Set a non-empty device lockscreen password, which is a precondition for installing + // private key pairs. + assertTrue("Set lockscreen password failed", runDeviceTestsAsUser(DEVICE_ADMIN_PKG, + adminHelperClass, "testSetPassword", 0 /* user 0 */)); + assertTrue("DelegatedCertInstaller failed", runDeviceTestsAsUser(DEVICE_ADMIN_PKG, + ".DelegatedCertInstallerTest", mUserId)); + } finally { + // Reset lockscreen password and remove device admin. + assertTrue("Clear lockscreen password failed", runDeviceTestsAsUser(DEVICE_ADMIN_PKG, + adminHelperClass, "testClearPassword", 0 /* user 0 */)); + assertTrue("Clear device admin failed", runDeviceTestsAsUser(DEVICE_ADMIN_PKG, + adminHelperClass, "testClearDeviceAdmin", 0 /* user 0 */)); + } + } + + public void testPackageInstallUserRestrictions() throws Exception { + // UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + final String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources"; + final String UNKNOWN_SOURCES_SETTING = "install_non_market_apps"; + final String SECURE_SETTING_CATEGORY = "secure"; + final File apk = mCtsBuild.getTestApp(TEST_APP_APK); + String unknownSourceSetting = null; + try { + // Install the test and prepare the test apk. + installApp(PACKAGE_INSTALLER_APK); + assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName())); + + // Add restrictions and test if we can install the apk. + getDevice().uninstallPackage(TEST_APP_PKG); + changeUserRestrictionForUser(DISALLOW_INSTALL_UNKNOWN_SOURCES, + ADD_RESTRICTION_COMMAND, mUserId); + assertTrue(runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest", + "testManualInstallBlocked", mUserId)); + + // Clear restrictions and test if we can install the apk. + changeUserRestrictionForUser(DISALLOW_INSTALL_UNKNOWN_SOURCES, + CLEAR_RESTRICTION_COMMAND, mUserId); + + // Enable Unknown sources in Settings. + unknownSourceSetting = + getSettings(SECURE_SETTING_CATEGORY, UNKNOWN_SOURCES_SETTING, mUserId); + putSettings(SECURE_SETTING_CATEGORY, UNKNOWN_SOURCES_SETTING, "1", mUserId); + assertEquals("1", + getSettings(SECURE_SETTING_CATEGORY, UNKNOWN_SOURCES_SETTING, mUserId)); + assertTrue(runDeviceTestsAsUser(PACKAGE_INSTALLER_PKG, ".ManualPackageInstallTest", + "testManualInstallSucceeded", mUserId)); + } finally { + String command = "rm " + TEST_APP_LOCATION + apk.getName(); + getDevice().executeShellCommand(command); + getDevice().uninstallPackage(TEST_APP_PKG); + getDevice().uninstallPackage(PACKAGE_INSTALLER_APK); + if (unknownSourceSetting != null) { + putSettings(SECURE_SETTING_CATEGORY, UNKNOWN_SOURCES_SETTING, unknownSourceSetting, + mUserId); + } + } + } + + protected void executeDeviceTestClass(String className) throws Exception { + assertTrue(runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, mUserId)); + } + + protected void executeDeviceTestMethod(String className, String testName) throws Exception { + assertTrue(runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, testName, mUserId)); + } + + private void changeUserRestrictionForUser(String key, String command, int userId) + throws DeviceNotAvailableException { + String adbCommand = "am start -W --user " + userId + + " -c android.intent.category.DEFAULT " + + " --es extra-command " + command + + " --es extra-restriction-key " + key + + " " + DEVICE_ADMIN_PKG + "/.UserRestrictionActivity"; + String commandOutput = getDevice().executeShellCommand(adbCommand); + CLog.logAndDisplay(LogLevel.INFO, + "Output for command " + adbCommand + ": " + commandOutput); + assertTrue("Command was expected to succeed " + commandOutput, + commandOutput.contains("Status: ok")); + } +}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java index b84e9fe..96ca469 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -16,10 +16,6 @@ package com.android.cts.devicepolicy; -import com.android.ddmlib.Log.LogLevel; -import com.android.tradefed.device.DeviceNotAvailableException; -import com.android.tradefed.log.LogUtil.CLog; - /** * Set of tests for Device Owner use cases. */ @@ -28,6 +24,18 @@ private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner"; private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk"; + private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile"; + private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk"; + private static final String MANAGED_PROFILE_ADMIN = + MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver"; + + private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver"; + private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk"; + + private static final String WIFI_CONFIG_CREATOR_PKG = + "com.android.cts.deviceowner.wificonfigcreator"; + private static final String WIFI_CONFIG_CREATOR_APK = "CtsWifiConfigCreator.apk"; + private static final String ADMIN_RECEIVER_TEST_CLASS = DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver"; private static final String CLEAR_DEVICE_OWNER_TEST_CLASS = @@ -38,7 +46,8 @@ super.setUp(); if (mHasFeature) { installApp(DEVICE_OWNER_APK); - setDeviceOwner(DEVICE_OWNER_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS); + assertTrue("Failed to set device owner", + setDeviceOwner(DEVICE_OWNER_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS)); } } @@ -53,10 +62,6 @@ super.tearDown(); } - public void testApplicationRestrictions() throws Exception { - executeDeviceOwnerTest("ApplicationRestrictionsTest"); - } - public void testCaCertManagement() throws Exception { executeDeviceOwnerTest("CaCertManagementTest"); } @@ -70,15 +75,44 @@ } public void testLockTask() throws Exception { - executeDeviceOwnerTest("LockTaskTest"); + try { + installApp(INTENT_RECEIVER_APK); + executeDeviceOwnerTest("LockTaskTest"); + } finally { + getDevice().uninstallPackage(INTENT_RECEIVER_PKG); + } } - public void testPersistentIntentResolving() throws Exception { - executeDeviceOwnerTest("PersistentIntentResolvingTest"); + public void testSystemUpdatePolicy() throws Exception { + executeDeviceOwnerTest("SystemUpdatePolicyTest"); } - public void testScreenCaptureDisabled() throws Exception { - executeDeviceOwnerTest("ScreenCaptureDisabledTest"); + public void testWifiConfigLockdown() throws Exception { + final boolean hasWifi = hasDeviceFeature("android.hardware.wifi"); + if (hasWifi && mHasFeature) { + try { + installApp(WIFI_CONFIG_CREATOR_APK); + executeDeviceOwnerTest("WifiConfigLockdownTest"); + } finally { + getDevice().uninstallPackage(WIFI_CONFIG_CREATOR_PKG); + } + } + } + + public void testCannotSetDeviceOwnerAgain() throws Exception { + if (!mHasFeature) { + return; + } + // verify that we can't set the same admin receiver as device owner again + assertFalse(setDeviceOwner(DEVICE_OWNER_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS)); + + // verify that we can't set a different admin receiver as device owner + try { + installApp(MANAGED_PROFILE_APK); + assertFalse(setDeviceOwner(MANAGED_PROFILE_PKG + "/" + MANAGED_PROFILE_ADMIN)); + } finally { + getDevice().uninstallPackage(MANAGED_PROFILE_PKG); + } } private void executeDeviceOwnerTest(String testClassName) throws Exception { @@ -88,13 +122,4 @@ String testClass = DEVICE_OWNER_PKG + "." + testClassName; assertTrue(testClass + " failed.", runDeviceTests(DEVICE_OWNER_PKG, testClass)); } - - private void setDeviceOwner(String componentName) throws DeviceNotAvailableException { - String command = "dpm set-device-owner '" + componentName + "'"; - String commandOutput = getDevice().executeShellCommand(command); - CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput); - assertTrue(commandOutput + " expected to start with \"Success:\"", - commandOutput.startsWith("Success:")); - } - }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java index 8da189f..1d5dd11 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsMultiUserTest.java
@@ -25,11 +25,13 @@ * apps. */ public class LauncherAppsMultiUserTest extends BaseLauncherAppsTest { + private static final String FEATURE_LIVE_TV = "android.software.live_tv"; private int mSecondaryUserId; private int mSecondaryUserSerialNumber; private boolean mMultiUserSupported; + private boolean mHasLiveTvFeature; @Override protected void setUp() throws Exception { @@ -37,6 +39,7 @@ // We need multi user to be supported in order to create a secondary user // and api level 21 to support LauncherApps mMultiUserSupported = getMaxNumberOfUsersSupported() > 1 && getDevice().getApiLevel() >= 21; + mHasLiveTvFeature = hasDeviceFeature(FEATURE_LIVE_TV); if (mMultiUserSupported) { removeTestUsers(); @@ -58,7 +61,7 @@ } public void testGetActivitiesForNonProfileFails() throws Exception { - if (!mMultiUserSupported) { + if (!mMultiUserSupported || mHasLiveTvFeature) { return; } installApp(SIMPLE_APP_APK); @@ -73,7 +76,7 @@ } public void testNoLauncherCallbackPackageAddedSecondaryUser() throws Exception { - if (!mMultiUserSupported) { + if (!mMultiUserSupported || mHasLiveTvFeature) { return; } startCallbackService();
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java index 43f1f5a..bb26df1 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/LauncherAppsProfileTest.java
@@ -25,6 +25,11 @@ */ public class LauncherAppsProfileTest extends BaseLauncherAppsTest { + private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile"; + private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk"; + private static final String ADMIN_RECEIVER_TEST_CLASS = + MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver"; + private int mProfileUserId; private int mProfileSerialNumber; private int mMainUserSerialNumber; @@ -39,7 +44,8 @@ // Create a managed profile mProfileUserId = createManagedProfile(); installApp(MANAGED_PROFILE_APK); - setProfileOwner(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mProfileUserId); + setProfileOwnerOrFail(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, + mProfileUserId); mProfileSerialNumber = getUserSerialNumber(mProfileUserId); mMainUserSerialNumber = getUserSerialNumber(0); startUser(mProfileUserId);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java index f8fa222..214131f 100644 --- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -20,6 +20,8 @@ import com.android.tradefed.device.DeviceNotAvailableException; import com.android.tradefed.log.LogUtil.CLog; +import junit.framework.AssertionFailedError; + /** * Set of tests for Managed Profile use cases. */ @@ -28,19 +30,41 @@ private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile"; private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk"; + private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner"; + private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk"; + private static final String DEVICE_OWNER_ADMIN = + DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver"; + private static final String DEVICE_OWNER_CLEAR = DEVICE_OWNER_PKG + ".ClearDeviceOwnerTest"; + private static final String INTENT_SENDER_PKG = "com.android.cts.intent.sender"; private static final String INTENT_SENDER_APK = "CtsIntentSenderApp.apk"; private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver"; private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk"; + private static final String WIFI_CONFIG_CREATOR_PKG = "com.android.cts.wificonfigcreator"; + private static final String WIFI_CONFIG_CREATOR_APK = "CtsWifiConfigCreator.apk"; + + private static final String WIDGET_PROVIDER_APK = "CtsWidgetProviderApp.apk"; + private static final String WIDGET_PROVIDER_PKG = "com.android.cts.widgetprovider"; + private static final String ADMIN_RECEIVER_TEST_CLASS = MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver"; private static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth"; + private static final String FEATURE_CAMERA = "android.hardware.camera"; + private static final String FEATURE_WIFI = "android.hardware.wifi"; + + private static final String ADD_RESTRICTION_COMMAND = "add-restriction"; + + private static final int USER_OWNER = 0; + + // ID of the profile we'll create. This will always be a profile of USER_OWNER. private int mUserId; + private String mPackageVerifier; + private boolean mHasNfcFeature; - + @Override protected void setUp() throws Exception { super.setUp(); @@ -51,11 +75,11 @@ mHasNfcFeature = hasDeviceFeature("android.hardware.nfc"); if (mHasFeature) { + removeTestUsers(); mUserId = createManagedProfile(); + installApp(MANAGED_PROFILE_APK); - installApp(INTENT_RECEIVER_APK); - installApp(INTENT_SENDER_APK); - setProfileOwner(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mUserId); + setProfileOwnerOrFail(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mUserId); startUser(mUserId); } } @@ -94,6 +118,42 @@ assertFalse(listUsers().contains(mUserId)); } + public void testMaxOneManagedProfile() throws Exception { + int newUserId = -1; + try { + newUserId = createManagedProfile(); + } catch (AssertionFailedError expected) { + } + if (newUserId > 0) { + removeUser(newUserId); + fail(mHasFeature ? "Device must allow creating only one managed profile" + : "Device must not allow creating a managed profile"); + } + } + + /** + * Verify that removing a managed profile will remove all networks owned by that profile. + */ + public void testProfileWifiCleanup() throws Exception { + if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) { + return; + } + assertTrue("WiFi config already exists and could not be removed", runDeviceTestsAsUser( + MANAGED_PROFILE_PKG, ".WifiTest", "testRemoveWifiNetworkIfExists", USER_OWNER)); + try { + installApp(WIFI_CONFIG_CREATOR_APK); + assertTrue("Failed to add WiFi config", runDeviceTestsAsUser( + MANAGED_PROFILE_PKG, ".WifiTest", "testAddWifiNetwork", mUserId)); + + // Now delete the user - should undo the effect of testAddWifiNetwork. + removeUser(mUserId); + assertTrue("WiFi config not removed after deleting profile", runDeviceTestsAsUser( + MANAGED_PROFILE_PKG, ".WifiTest", "testWifiNetworkDoesNotExist", USER_OWNER)); + } finally { + getDevice().uninstallPackage(WIFI_CONFIG_CREATOR_APK); + } + } + public void testCrossProfileIntentFilters() throws Exception { if (!mHasFeature) { return; @@ -115,6 +175,49 @@ // TODO: Test with startActivity } + public void testAppLinks() throws Exception { + if (!mHasFeature) { + return; + } + // Disable all pre-existing browsers in the managed profile so they don't interfere with + // intents resolution. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", + "testDisableAllBrowsers", mUserId)); + installApp(INTENT_RECEIVER_APK); + installApp(INTENT_SENDER_APK); + + changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "ask"); + changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "ask"); + // We should have two receivers: IntentReceiverActivity and BrowserActivity in the + // managed profile + assertAppLinkResult("testTwoReceivers"); + + changeUserRestrictionForUser("allow_parent_profile_app_linking", ADD_RESTRICTION_COMMAND, + mUserId); + // Now we should also have one receiver in the primary user, so three receivers in total. + assertAppLinkResult("testThreeReceivers"); + + changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "never"); + // The primary user one has been set to never: we should only have the managed profile ones. + assertAppLinkResult("testTwoReceivers"); + + changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "never"); + // Now there's only the browser in the managed profile left + assertAppLinkResult("testReceivedByBrowserActivityInManaged"); + + changeVerificationStatus(USER_OWNER, INTENT_RECEIVER_PKG, "always"); + changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "ask"); + // We've set the receiver in the primary user to always: only this one should receive the + // intent. + assertAppLinkResult("testReceivedByAppLinkActivityInPrimary"); + + changeVerificationStatus(mUserId, INTENT_RECEIVER_PKG, "always"); + // We have one always in the primary user and one always in the managed profile: the managed + // profile one should have precedence. + assertAppLinkResult("testReceivedByAppLinkActivityInManaged"); + } + + public void testSettingsIntents() throws Exception { if (!mHasFeature) { return; @@ -127,19 +230,21 @@ if (!mHasFeature) { return; } + installApp(INTENT_RECEIVER_APK); + installApp(INTENT_SENDER_APK); // Test from parent to managed assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "removeAllFilters", mUserId)); + "testRemoveAllFilters", mUserId)); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "addManagedCanAccessParentFilters", mUserId)); + "testAddManagedCanAccessParentFilters", mUserId)); assertTrue(runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", 0)); // Test from managed to parent assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "removeAllFilters", mUserId)); + "testRemoveAllFilters", mUserId)); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "addParentCanAccessManagedFilters", mUserId)); + "testAddParentCanAccessManagedFilters", mUserId)); assertTrue(runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", mUserId)); } @@ -148,16 +253,18 @@ if (!mHasFeature) { return; } + installApp(INTENT_RECEIVER_APK); + installApp(INTENT_SENDER_APK); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "allowCrossProfileCopyPaste", mUserId)); + "testAllowCrossProfileCopyPaste", mUserId)); // Test that managed can see what is copied in the parent. testCrossProfileCopyPasteInternal(mUserId, true); // Test that the parent can see what is copied in managed. testCrossProfileCopyPasteInternal(0, true); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "disallowCrossProfileCopyPaste", mUserId)); + "testDisallowCrossProfileCopyPaste", mUserId)); // Test that managed can still see what is copied in the parent. testCrossProfileCopyPasteInternal(mUserId, true); // Test that the parent cannot see what is copied in managed. @@ -166,10 +273,11 @@ private void testCrossProfileCopyPasteInternal(int userId, boolean shouldSucceed) throws DeviceNotAvailableException { - final String direction = (userId == 0) ? "addManagedCanAccessParentFilters" - : "addParentCanAccessManagedFilters"; + final String direction = (userId == 0) + ? "testAddManagedCanAccessParentFilters" + : "testAddParentCanAccessManagedFilters"; assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", - "removeAllFilters", mUserId)); + "testRemoveAllFilters", mUserId)); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils", direction, mUserId)); if (shouldSucceed) { @@ -191,18 +299,25 @@ if (!mHasFeature) { return; } + // If adb is running as root, then the adb uid is 0 instead of SHELL_UID, + // so the DISALLOW_DEBUGGING_FEATURES restriction does not work and this test + // fails. + if (getDevice().isAdbRoot()) { + CLog.logAndDisplay(LogLevel.INFO, + "Cannot test testNoDebuggingFeaturesRestriction() in eng/userdebug build"); + return; + } String restriction = "no_debugging_features"; // UserManager.DISALLOW_DEBUGGING_FEATURES - String command = "add-restriction"; String addRestrictionCommandOutput = - changeUserRestrictionForUser(restriction, command, mUserId); + changeUserRestrictionForUser(restriction, ADD_RESTRICTION_COMMAND, mUserId); assertTrue("Command was expected to succeed " + addRestrictionCommandOutput, addRestrictionCommandOutput.contains("Status: ok")); // This should now fail, as the shell is not available to start activities under a different // user once the restriction is in place. addRestrictionCommandOutput = - changeUserRestrictionForUser(restriction, command, mUserId); + changeUserRestrictionForUser(restriction, ADD_RESTRICTION_COMMAND, mUserId); assertTrue( "Expected SecurityException when starting the activity " + addRestrictionCommandOutput, @@ -226,6 +341,52 @@ "testGetRemoteDevice", mUserId)); } + public void testCameraPolicy() throws Exception { + boolean hasCamera = hasDeviceFeature(FEATURE_CAMERA); + if (!mHasFeature || !hasCamera) { + return; + } + try { + setDeviceAdmin(MANAGED_PROFILE_PKG + "/.PrimaryUserDeviceAdmin"); + + // Disable managed profile camera. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testDisableCameraInManagedProfile", + mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testIsCameraEnabledInPrimaryProfile", + 0)); + + // Enable managed profile camera. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testEnableCameraInManagedProfile", + mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testIsCameraEnabledInPrimaryProfile", + 0)); + + // Disable primary profile camera. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testDisableCameraInPrimaryProfile", + 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testIsCameraEnabledInManagedProfile", + mUserId)); + + // Enable primary profile camera. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testEnableCameraInPrimaryProfile", + 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest", + "testIsCameraEnabledInManagedProfile", + mUserId)); + } finally { + final String adminHelperClass = ".PrimaryUserAdminHelper"; + assertTrue("Clear device admin failed", runDeviceTestsAsUser(MANAGED_PROFILE_PKG, + adminHelperClass, "testClearDeviceAdmin", 0 /* user 0 */)); + } + } + public void testManagedContacts() throws Exception { if (!mHasFeature) { return; @@ -234,39 +395,115 @@ try { // Insert Primary profile Contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", - "testPrimaryProfilePhoneLookup_insertedAndfound", 0)); + "testPrimaryProfilePhoneAndEmailLookup_insertedAndfound", 0)); // Insert Managed profile Contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", - "testManagedProfilePhoneLookup_insertedAndfound", mUserId)); + "testManagedProfilePhoneAndEmailLookup_insertedAndfound", mUserId)); + // Insert a primary contact with same phone & email as other enterprise contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileDuplicatedPhoneEmailContact_insertedAndfound", 0)); + // Insert a enterprise contact with same phone & email as other primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileDuplicatedPhoneEmailContact_insertedAndfound", mUserId)); + // Set cross profile caller id to enabled assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", "testSetCrossProfileCallerIdDisabled_false", mUserId)); - // Managed user can use ENTERPRISE_CONTENT_FILTER_URI - // To access managed contacts but not primary contacts + // Primary user cannot use ordinary phone/email lookup api to access managed contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", - "testManagedProfilePhoneLookup_canAccessEnterpriseContact", mUserId)); + "testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact", 0)); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", - "testManagedProfilePhoneLookup_canNotAccessPrimaryContact", mUserId)); - - // Primary user can use ENTERPRISE_CONTENT_FILTER_URI - // To access both primary and managed contacts + "testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact", 0)); + // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryContact", 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryContact", 0)); + // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access managed profile contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", "testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact", 0)); assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", - "testPrimaryProfilePhoneLookup_canAccessPrimaryContact", 0)); + "testPrimaryProfileEnterpriseEmailLookup_canAccessEnterpriseContact", 0)); + // When there exist contacts with the same phone/email in primary & enterprise, + // primary user can use ENTERPRISE_CONTENT_FILTER_URI to access the primary contact. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact", + 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact", + 0)); + + // Make sure SIP enterprise lookup works too. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterpriseSipLookup_canAccessEnterpriseContact", 0)); + + // Managed user cannot use ordinary phone/email lookup api to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfilePhoneLookup_canNotAccessPrimaryContact", mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEmailLookup_canNotAccessPrimaryContact", mUserId)); + // Managed user can use ENTERPRISE_CONTENT_FILTER_URI to access enterprise contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterprisePhoneLookup_canAccessEnterpriseContact", mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterpriseEmailLookup_canAccessEnterpriseContact", mUserId)); + // Managed user cannot use ENTERPRISE_CONTENT_FILTER_URI to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact", mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact", mUserId)); + // When there exist contacts with the same phone/email in primary & enterprise, + // managed user can use ENTERPRISE_CONTENT_FILTER_URI to access the enterprise contact. + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact", + mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact", + mUserId)); // Set cross profile caller id to disabled assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", "testSetCrossProfileCallerIdDisabled_true", mUserId)); - // Primary user cannot use ENTERPRISE_CONTENT_FILTER_URI to access managed contacts + // Primary user cannot use ordinary phone/email lookup api to access managed contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", "testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact", 0)); - // Managed user cannot use ENTERPRISE_CONTENT_FILTER_URI to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact", 0)); + // Primary user cannot use ENTERPRISE_CONTENT_FILTER_URI to access managed contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterprisePhoneLookup_canNotAccessEnterpriseContact", 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterpriseEmailLookup_canNotAccessEnterpriseContact", 0)); + // When there exist contacts with the same phone/email in primary & enterprise, + // primary user can use ENTERPRISE_CONTENT_FILTER_URI to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact", + 0)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact", + 0)); + + // Managed user cannot use ordinary phone/email lookup api to access primary contacts assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", "testManagedProfilePhoneLookup_canNotAccessPrimaryContact", mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEmailLookup_canNotAccessPrimaryContact", mUserId)); + // Managed user cannot use ENTERPRISE_CONTENT_FILTER_URI to access primary contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact", mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact", mUserId)); + // When there exist contacts with the same phone/email in primary & enterprise, + // managed user can use ENTERPRISE_CONTENT_FILTER_URI to access enterprise contacts + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact", + mUserId)); + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact", + mUserId)); } finally { // Clean up in managed profile and primary profile runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", @@ -276,6 +513,42 @@ } } + public void testBluetoothContactSharingDisabled() throws Exception { + if (!mHasFeature) { + return; + } + assertTrue(runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest", + "testSetBluetoothContactSharingDisabled_setterAndGetter", mUserId)); + } + + public void testCannotSetProfileOwnerAgain() throws Exception { + if (!mHasFeature) { + return; + } + // verify that we can't set the same admin receiver as profile owner again + assertFalse(setProfileOwner( + MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mUserId)); + + // verify that we can't set a different admin receiver as profile owner + installAppAsUser(DEVICE_OWNER_APK, mUserId); + assertFalse(setProfileOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mUserId)); + } + + public void testCannotSetDeviceOwnerWhenProfilePresent() throws Exception { + if (!mHasFeature) { + return; + } + + try { + installApp(DEVICE_OWNER_APK); + assertFalse(setDeviceOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN)); + } finally { + // make sure we clean up in case we succeeded in setting the device owner + runDeviceTests(DEVICE_OWNER_PKG, DEVICE_OWNER_CLEAR); + getDevice().uninstallPackage(DEVICE_OWNER_PKG); + } + } + public void testNfcRestriction() throws Exception { if (!mHasFeature || !mHasNfcFeature) { return; @@ -300,6 +573,47 @@ "testNfcShareEnabled", 0)); } + public void testCrossProfileWidgets() throws Exception { + if (!mHasFeature) { + return; + } + + try { + installApp(WIDGET_PROVIDER_APK); + getDevice().executeShellCommand("appwidget grantbind --user 0 --package " + + WIDGET_PROVIDER_PKG); + startWidgetHostService(); + + String commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, + "add-cross-profile-widget", mUserId); + assertTrue("Command was expected to succeed " + commandOutput, + commandOutput.contains("Status: ok")); + + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest", + "testCrossProfileWidgetProviderAdded", mUserId)); + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetPrimaryUserTest", + "testHasCrossProfileWidgetProvider_true", 0)); + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetPrimaryUserTest", + "testHostReceivesWidgetUpdates_true", 0)); + + commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, + "remove-cross-profile-widget", mUserId); + assertTrue("Command was expected to succeed " + commandOutput, + commandOutput.contains("Status: ok")); + + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest", + "testCrossProfileWidgetProviderRemoved", mUserId)); + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetPrimaryUserTest", + "testHasCrossProfileWidgetProvider_false", 0)); + assertTrue(runDeviceTests(MANAGED_PROFILE_PKG, ".CrossProfileWidgetPrimaryUserTest", + "testHostReceivesWidgetUpdates_false", 0)); + } finally { + changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, "remove-cross-profile-widget", + mUserId); + getDevice().uninstallPackage(WIDGET_PROVIDER_PKG); + } + } + private void disableActivityForUser(String activityName, int userId) throws DeviceNotAvailableException { String command = "am start -W --user " + userId @@ -316,10 +630,44 @@ + " -c android.intent.category.DEFAULT " + " --es extra-command " + command + " --es extra-restriction-key " + key - + " " + MANAGED_PROFILE_PKG + "/.UserRestrictionActivity"; + + " " + MANAGED_PROFILE_PKG + "/.SetPolicyActivity"; String commandOutput = getDevice().executeShellCommand(adbCommand); CLog.logAndDisplay(LogLevel.INFO, "Output for command " + adbCommand + ": " + commandOutput); return commandOutput; } + + private String changeCrossProfileWidgetForUser(String packageName, String command, int userId) + throws DeviceNotAvailableException { + String adbCommand = "am start -W --user " + userId + + " -c android.intent.category.DEFAULT " + + " --es extra-command " + command + + " --es extra-package-name " + packageName + + " " + MANAGED_PROFILE_PKG + "/.SetPolicyActivity"; + String commandOutput = getDevice().executeShellCommand(adbCommand); + CLog.logAndDisplay(LogLevel.INFO, + "Output for command " + adbCommand + ": " + commandOutput); + return commandOutput; + } + + // status should be one of never, undefined, ask, always + private void changeVerificationStatus(int userId, String packageName, String status) + throws DeviceNotAvailableException { + String command = "pm set-app-link --user " + userId + " " + packageName + " " + status; + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + + getDevice().executeShellCommand(command)); + } + + protected void startWidgetHostService() throws Exception { + String command = "am startservice --user 0 " + + "-a " + WIDGET_PROVIDER_PKG + ".REGISTER_CALLBACK " + + "--ei user-extra " + getUserSerialNumber(mUserId) + + " " + WIDGET_PROVIDER_PKG + "/.SimpleAppWidgetHostService"; + CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + + getDevice().executeShellCommand(command)); + } + + private void assertAppLinkResult(String methodName) throws DeviceNotAvailableException { + assertTrue(runDeviceTestsAsUser(INTENT_SENDER_PKG, ".AppLinkTest", methodName, mUserId)); + } }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java new file mode 100644 index 0000000..b996de3 --- /dev/null +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedDeviceOwnerTest.java
@@ -0,0 +1,57 @@ +/* + * Copyright (C) 2015 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.devicepolicy; + +import com.android.ddmlib.Log.LogLevel; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.log.LogUtil.CLog; + +import junit.framework.AssertionFailedError; + +/** + * Set of tests for device owner use cases that also apply to profile owners. + * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTest. + */ +public class MixedDeviceOwnerTest extends DeviceAndProfileOwnerTest { + + private static final String CLEAR_DEVICE_OWNER_TEST_CLASS = + DEVICE_ADMIN_PKG + ".ClearDeviceOwnerTest"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + if (mHasFeature) { + mUserId = USER_OWNER; + + installApp(DEVICE_ADMIN_APK); + assertTrue("Failed to set device owner", + setDeviceOwner(DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS)); + } + } + + @Override + protected void tearDown() throws Exception { + if (mHasFeature) { + assertTrue("Failed to remove device owner.", + runDeviceTests(DEVICE_ADMIN_PKG, CLEAR_DEVICE_OWNER_TEST_CLASS)); + } + super.tearDown(); + } + + // All tests for this class are defined in DeviceAndProfileOwnerTest +}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java new file mode 100644 index 0000000..bcc5bf9 --- /dev/null +++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedProfileOwnerTest.java
@@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 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.devicepolicy; + +import com.android.ddmlib.Log.LogLevel; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.log.LogUtil.CLog; + +import junit.framework.AssertionFailedError; + +/** + * Set of tests for profile owner use cases that also apply to device owners. + * Tests that should be run identically in both cases are added in DeviceAndProfileOwnerTest. + */ +public class MixedProfileOwnerTest extends DeviceAndProfileOwnerTest { + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // We need managed users to be supported in order to create a profile of the user owner. + mHasFeature &= hasDeviceFeature("android.software.managed_users"); + + if (mHasFeature) { + removeTestUsers(); + mUserId = createManagedProfile(); + + installAppAsUser(DEVICE_ADMIN_APK, mUserId); + setProfileOwnerOrFail(DEVICE_ADMIN_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mUserId); + startUser(mUserId); + } + } + + @Override + protected void tearDown() throws Exception { + if (mHasFeature) { + removeUser(mUserId); + } + super.tearDown(); + } + + // Most tests for this class are defined in DeviceAndProfileOwnerTest + + /** + * Verify that screenshots are still possible for activities in the primary user when the policy + * is set on the profile owner. + */ + public void testScreenCaptureDisabled_allowedPrimaryUser() throws Exception { + if (!mHasFeature) { + return; + } + executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testSetScreenCaptureDisabled_true"); + // start the ScreenCaptureDisabledActivity in the primary user + installAppAsUser(DEVICE_ADMIN_APK, USER_OWNER); + String command = "am start -W --user 0 " + DEVICE_ADMIN_PKG + "/" + + DEVICE_ADMIN_PKG + ".ScreenCaptureDisabledActivity"; + getDevice().executeShellCommand(command); + executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testScreenCapturePossible"); + } +}
diff --git a/hostsidetests/dumpsys/Android.mk b/hostsidetests/dumpsys/Android.mk index 51ea31f..5b63199 100644 --- a/hostsidetests/dumpsys/Android.mk +++ b/hostsidetests/dumpsys/Android.mk
@@ -18,8 +18,6 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src) -LOCAL_MODULE_TAGS := optional - # Must match the package name in CtsTestCaseList.mk LOCAL_MODULE := CtsDumpsysHostTestCases
diff --git a/hostsidetests/dumpsys/FramestatsTestApp/Android.mk b/hostsidetests/dumpsys/FramestatsTestApp/Android.mk new file mode 100644 index 0000000..1104523 --- /dev/null +++ b/hostsidetests/dumpsys/FramestatsTestApp/Android.mk
@@ -0,0 +1,28 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := tests + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_SDK_VERSION := current +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test + +LOCAL_PACKAGE_NAME := CtsFramestatsTestApp + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/dumpsys/FramestatsTestApp/AndroidManifest.xml b/hostsidetests/dumpsys/FramestatsTestApp/AndroidManifest.xml new file mode 100644 index 0000000..3a9f902 --- /dev/null +++ b/hostsidetests/dumpsys/FramestatsTestApp/AndroidManifest.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.framestatstestapp"> + <!-- + A simple app that draws at least one frame. Used by framestats + test. + --> + <application> + <activity android:name=".FramestatsTestAppActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> +</manifest>
diff --git a/hostsidetests/dumpsys/FramestatsTestApp/src/com/android/cts/framestatstestapp/FramestatsTestAppActivity.java b/hostsidetests/dumpsys/FramestatsTestApp/src/com/android/cts/framestatstestapp/FramestatsTestAppActivity.java new file mode 100644 index 0000000..7370508 --- /dev/null +++ b/hostsidetests/dumpsys/FramestatsTestApp/src/com/android/cts/framestatstestapp/FramestatsTestAppActivity.java
@@ -0,0 +1,31 @@ +/* + * Copyright (C) 2015 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.framestatstestapp; + +import android.app.Activity; +import android.os.Bundle; +import android.os.Trace; +import android.view.View; + +public class FramestatsTestAppActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + View v = new View(this); + v.setBackgroundColor(0xFF00FF00); + setContentView(v); + } +}
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java index e12135a..0daae03 100644 --- a/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java +++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/DumpsysHostTest.java
@@ -16,11 +16,15 @@ package android.dumpsys.cts; -import com.android.ddmlib.Log; +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.tradefed.build.IBuildInfo; import com.android.tradefed.device.ITestDevice; import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IBuildReceiver; import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; import java.io.StringReader; import java.util.HashSet; import java.util.Set; @@ -28,8 +32,10 @@ /** * Test to check the format of the dumps of various services (currently only procstats is tested). */ -public class DumpsysHostTest extends DeviceTestCase { +public class DumpsysHostTest extends DeviceTestCase implements IBuildReceiver { private static final String TAG = "DumpsysHostTest"; + private static final String TEST_APK = "CtsFramestatsTestApp.apk"; + private static final String TEST_PKG = "com.android.cts.framestatstestapp"; /** * A reference to the device under test. @@ -49,11 +55,6 @@ * @throws Exception */ public void testProcstatsOutput() throws Exception { - if (mDevice.getApiLevel() < 19) { - Log.i(TAG, "No Procstats output before KitKat, skipping test."); - return; - } - String procstats = mDevice.executeShellCommand("dumpsys procstats -c"); assertNotNull(procstats); assertTrue(procstats.length() > 0); @@ -338,11 +339,6 @@ * @throws Exception */ public void testBatterystatsOutput() throws Exception { - if (mDevice.getApiLevel() < 21) { - Log.i(TAG, "Batterystats output before Lollipop, skipping test."); - return; - } - String batterystats = mDevice.executeShellCommand("dumpsys batterystats --checkin"); assertNotNull(batterystats); assertTrue(batterystats.length() > 0); @@ -359,7 +355,12 @@ continue; } - String[] parts = line.split(","); + + // With a default limit of 0, empty strings at the end are discarded. + // We still consider the empty string as a valid value in some cases. + // Using any negative number for the limit will preserve a trailing empty string. + // @see String#split(String, int) + String[] parts = line.split(",", -1); assertInteger(parts[0]); // old version assertInteger(parts[1]); // UID switch (parts[2]) { // aggregation type @@ -658,23 +659,22 @@ } private void checkMisc(String[] parts) { - assertTrue(parts.length >= 20); + assertTrue(parts.length >= 19); assertInteger(parts[4]); // screenOnTime assertInteger(parts[5]); // phoneOnTime - assertInteger(parts[6]); // wifiOnTime - assertInteger(parts[7]); // wifiRunningTime - assertInteger(parts[8]); // bluetoothOnTime - assertInteger(parts[9]); // mobileRxTotalBytes - assertInteger(parts[10]); // mobileTxTotalBytes - assertInteger(parts[11]); // wifiRxTotalBytes - assertInteger(parts[12]); // wifiTxTotalBytes - assertInteger(parts[13]); // fullWakeLockTimeTotal - assertInteger(parts[14]); // partialWakeLockTimeTotal - assertEquals("0", parts[15]); // legacy input event count - assertInteger(parts[16]); // mobileRadioActiveTime - assertInteger(parts[17]); // mobileRadioActiveAdjustedTime - assertInteger(parts[18]); // interactiveTime - assertInteger(parts[19]); // lowPowerModeEnabledTime + assertInteger(parts[6]); // fullWakeLockTimeTotal + assertInteger(parts[7]); // partialWakeLockTimeTotal + assertInteger(parts[8]); // mobileRadioActiveTime + assertInteger(parts[9]); // mobileRadioActiveAdjustedTime + assertInteger(parts[10]); // interactiveTime + assertInteger(parts[11]); // lowPowerModeEnabledTime + assertInteger(parts[12]); // connChanges + assertInteger(parts[13]); // deviceIdleModeEnabledTime + assertInteger(parts[14]); // deviceIdleModeEnabledCount + assertInteger(parts[15]); // deviceIdlingTime + assertInteger(parts[16]); // deviceIdlingCount + assertInteger(parts[17]); // mobileRadioActiveCount + assertInteger(parts[18]); // mobileRadioActiveUnknownTime } private void checkGlobalNetwork(String[] parts) { @@ -794,13 +794,14 @@ } private void checkChargeDischargeStep(String[] parts) { - assertEquals(8, parts.length); + assertEquals(9, parts.length); assertInteger(parts[4]); // duration if (!parts[5].equals("?")) { assertInteger(parts[5]); // level } assertNotNull(parts[6]); // screen assertNotNull(parts[7]); // power-save + assertNotNull(parts[8]); // device-idle } private void checkDischargeTimeRemain(String[] parts) { @@ -813,11 +814,108 @@ assertInteger(parts[4]); // chargeTimeRemaining } - private static void assertInteger(String input) { + /** + * Tests the output of "dumpsys gfxinfo framestats". + * + * @throws Exception + */ + public void testGfxinfoFramestats() throws Exception { + final String MARKER = "---PROFILEDATA---"; + try { - Long.parseLong(input); + // cleanup test apps that might be installed from previous partial test run + getDevice().uninstallPackage(TEST_PKG); + + // install the test app + File testAppFile = mCtsBuild.getTestApp(TEST_APK); + String installResult = getDevice().installPackage(testAppFile, false); + assertNull( + String.format("failed to install atrace test app. Reason: %s", installResult), + installResult); + + getDevice().executeShellCommand("am start -W " + TEST_PKG); + + String frameinfo = mDevice.executeShellCommand("dumpsys gfxinfo " + + TEST_PKG + " framestats"); + assertNotNull(frameinfo); + assertTrue(frameinfo.length() > 0); + int profileStart = frameinfo.indexOf(MARKER); + int profileEnd = frameinfo.indexOf(MARKER, profileStart + 1); + assertTrue(profileStart >= 0); + assertTrue(profileEnd > profileStart); + String profileData = frameinfo.substring(profileStart + MARKER.length(), profileEnd); + assertTrue(profileData.length() > 0); + validateProfileData(profileData); + } finally { + getDevice().uninstallPackage(TEST_PKG); + } + } + + private void validateProfileData(String profileData) throws IOException { + final int TIMESTAMP_COUNT = 14; + boolean foundAtLeastOneRow = false; + try (BufferedReader reader = new BufferedReader( + new StringReader(profileData))) { + String line; + // First line needs to be the headers + while ((line = reader.readLine()) != null && line.isEmpty()) {} + + assertNotNull(line); + assertTrue("First line was not the expected header", + line.startsWith("Flags,IntendedVsync,Vsync,OldestInputEvent" + + ",NewestInputEvent,HandleInputStart,AnimationStart" + + ",PerformTraversalsStart,DrawStart,SyncQueued,SyncStart" + + ",IssueDrawCommandsStart,SwapBuffers,FrameCompleted")); + + long[] numparts = new long[TIMESTAMP_COUNT]; + while ((line = reader.readLine()) != null && !line.isEmpty()) { + + String[] parts = line.split(","); + assertTrue(parts.length >= TIMESTAMP_COUNT); + for (int i = 0; i < TIMESTAMP_COUNT; i++) { + numparts[i] = assertInteger(parts[i]); + } + if (numparts[0] != 0) { + continue; + } + // assert VSYNC >= INTENDED_VSYNC + assertTrue(numparts[2] >= numparts[1]); + // assert time is flowing forwards, skipping index 3 & 4 + // as those are input timestamps that may or may not be present + assertTrue(numparts[5] >= numparts[2]); + for (int i = 6; i < TIMESTAMP_COUNT; i++) { + assertTrue("Index " + i + " did not flow forward, " + + numparts[i] + " not larger than " + numparts[i - 1], + numparts[i] >= numparts[i-1]); + } + long totalDuration = numparts[13] - numparts[1]; + assertTrue("Frame did not take a positive amount of time to process", + totalDuration > 0); + assertTrue("Bogus frame duration, exceeds 100 seconds", + totalDuration < 100000000000L); + foundAtLeastOneRow = true; + } + } + assertTrue(foundAtLeastOneRow); + } + + private CtsBuildHelper mCtsBuild; + + /** + * {@inheritDoc} + */ + @Override + public void setBuild(IBuildInfo buildInfo) { + mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + private static long assertInteger(String input) { + try { + return Long.parseLong(input); } catch (NumberFormatException e) { fail("Expected an integer but found \"" + input + "\""); + // Won't be hit, above throws AssertException + return -1; } }
diff --git a/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java b/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java old mode 100644 new mode 100755 index 9e04274..b31a32d --- a/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java +++ b/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java
@@ -20,7 +20,7 @@ /** * Base monkey command with flags to avoid side effects like airplane mode. */ - static final String MONKEY_CMD = "monkey --pct-touch 0 --pct-motion 0 --pct-majornav 0 --pct-syskeys 0 --pct-anyevent 0 --pct-rotation 0"; + static final String MONKEY_CMD = "monkey --pct-motion 0 --pct-majornav 0 --pct-syskeys 0 --pct-anyevent 0 --pct-rotation 0"; IAbi mAbi; CtsBuildHelper mBuild;
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk index f6543fb..c04d4b2 100644 --- a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk +++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp/AndroidManifest.xml b/hostsidetests/monkey/test-apps/CtsMonkeyApp/AndroidManifest.xml index a3dfc83..efb1288 100644 --- a/hostsidetests/monkey/test-apps/CtsMonkeyApp/AndroidManifest.xml +++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp/AndroidManifest.xml
@@ -18,14 +18,18 @@ <application android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> - <activity android:name=".MonkeyActivity"> + <activity + android:name=".MonkeyActivity" + android:screenOrientation="locked"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> - - <activity android:name=".BaboonActivity"> + + <activity + android:name=".BaboonActivity" + android:screenOrientation="locked"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.MONKEY" />
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk index 29bf9d6..b3cb181 100644 --- a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk +++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/net/app/Android.mk b/hostsidetests/net/app/Android.mk index 29b620d..055287a 100644 --- a/hostsidetests/net/app/Android.mk +++ b/hostsidetests/net/app/Android.mk
@@ -29,4 +29,4 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/Android.mk b/hostsidetests/os/Android.mk new file mode 100644 index 0000000..6962e0c --- /dev/null +++ b/hostsidetests/os/Android.mk
@@ -0,0 +1,35 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +# Must match the package name in CtsTestCaseList.mk +LOCAL_MODULE := CtsOsHostTestCases + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed-prebuilt + +LOCAL_CTS_TEST_PACKAGE := android.host.os + +LOCAL_CTS_MODULE_CONFIG := $(LOCAL_PATH)/$(CTS_MODULE_TEST_CONFIG) + +include $(BUILD_CTS_HOST_JAVA_LIBRARY) + +# Build the test APKs using their own makefiles +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/os/AndroidTest.xml b/hostsidetests/os/AndroidTest.xml new file mode 100644 index 0000000..6694c30 --- /dev/null +++ b/hostsidetests/os/AndroidTest.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="CTS package preparer for install/uninstall of the apk used as a test operation target"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsDeviceOsTestApp.apk" /> +</configuration>
diff --git a/hostsidetests/os/app/Android.mk b/hostsidetests/os/app/Android.mk new file mode 100644 index 0000000..46861d69 --- /dev/null +++ b/hostsidetests/os/app/Android.mk
@@ -0,0 +1,28 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# Don't include this package in any target. +LOCAL_MODULE_TAGS := tests + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_SDK_VERSION := current + +LOCAL_PACKAGE_NAME := CtsDeviceOsTestApp + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/app/AndroidManifest.xml b/hostsidetests/os/app/AndroidManifest.xml new file mode 100755 index 0000000..103cf63 --- /dev/null +++ b/hostsidetests/os/app/AndroidManifest.xml
@@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.app.os.test"> + + <application> + <activity android:name=".TestNonExported" + android:exported="false" /> + </application> +</manifest> +
diff --git a/hostsidetests/os/app/src/com/android/cts/app/os/test/TestNonExported.java b/hostsidetests/os/app/src/com/android/cts/app/os/test/TestNonExported.java new file mode 100644 index 0000000..c865c89 --- /dev/null +++ b/hostsidetests/os/app/src/com/android/cts/app/os/test/TestNonExported.java
@@ -0,0 +1,25 @@ +/* + * Copyright (C) 2015 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.app.os.test; + +import android.app.Activity; + +/** + * Should never be launched: intentionally not exported + */ +public class TestNonExported extends Activity { +}
diff --git a/hostsidetests/os/src/com/android/cts/app/os/OsHostTests.java b/hostsidetests/os/src/com/android/cts/app/os/OsHostTests.java new file mode 100644 index 0000000..d01a521 --- /dev/null +++ b/hostsidetests/os/src/com/android/cts/app/os/OsHostTests.java
@@ -0,0 +1,63 @@ +/* + * Copyright (C) 2015 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.app.os; + +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.CollectingOutputReceiver; +import com.android.tradefed.device.ITestDevice; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IBuildReceiver; + +public class OsHostTests extends DeviceTestCase implements IBuildReceiver { + private static final String TEST_APP_PACKAGE = "com.android.cts.app.os.test"; + private static final String TEST_NON_EXPORTED_ACTIVITY_CLASS = "TestNonExported"; + + private static final String START_NON_EXPORTED_ACTIVITY_COMMAND = String.format( + "am start -n %s/%s.%s", + TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_NON_EXPORTED_ACTIVITY_CLASS); + + /** + * A reference to the device under test. + */ + private ITestDevice mDevice; + + @Override + public void setBuild(IBuildInfo buildInfo) { + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // Get the device, this gives a handle to run commands and install APKs. + mDevice = getDevice(); + } + + /** + * Test whether non-exported activities are properly not launchable. + * + * @throws Exception + */ + public void testNonExportedActivities() throws Exception { + // Attempt to launch the non-exported activity in the test app + CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver(); + mDevice.executeShellCommand(START_NON_EXPORTED_ACTIVITY_COMMAND, outputReceiver); + final String output = outputReceiver.getOutput(); + + assertTrue(output.contains("Permission Denial") && output.contains(" not exported")); + } +}
diff --git a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java index a0d3167..abb1ac4 100644 --- a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java +++ b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
@@ -589,9 +589,9 @@ assertDomainN("u:r:zygote:s0", "zygote", "zygote64"); } - /* drm server is always present */ + /* Checks drmserver for devices that require it */ public void testDrmServerDomain() throws DeviceNotAvailableException { - assertDomainOne("u:r:drmserver:s0", "/system/bin/drmserver"); + assertDomainZeroOrOne("u:r:drmserver:s0", "/system/bin/drmserver"); } /* Media server is always running */
diff --git a/hostsidetests/theme/Android.mk b/hostsidetests/theme/Android.mk index 71027c7..188bf7a 100644 --- a/hostsidetests/theme/Android.mk +++ b/hostsidetests/theme/Android.mk
@@ -29,6 +29,8 @@ LOCAL_CTS_TEST_PACKAGE := android.host.theme +LOCAL_SDK_VERSION := current + include $(BUILD_CTS_HOST_JAVA_LIBRARY) include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/theme/README b/hostsidetests/theme/README new file mode 100644 index 0000000..bce711a --- /dev/null +++ b/hostsidetests/theme/README
@@ -0,0 +1,73 @@ +* Copyright (C) 2015 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. + + +INTRODUCTION + +The Android theme tests ensure that the Holo and Material themes have not been +modified. They consist of API-specific sets of reference images representing +specific themes and widgets that must be identical across devices. To pass the +theme tests, a device must be able to generate images that are identical to the +reference images. + +NOTE: Reference images should only be updated by the CTS test maintainers. Any + modifications to the reference images will invalidate the test results. + + +INSTRUCTIONS + +I. Generating reference images (CTS maintainers only) + +Reference images are typically only generated for new API revisions. To +generate a new set of reference images, do the following: + + 1. Connect one device for each DPI bucket (ldpi, xxxhdpi, etc.) that you wish + to generate references images for. Confirm that all devices are connected + with: + + adb devices + + 2. Image generation occurs on all devices in parallel. Resulting sets of + reference images are saved in assets/<api>/<dpi>.zip and will overwrite + any existing sets. Image generation may be started using: + + .cts/hostsidetests/theme/generate_images.sh + +A complete collection of reference images for a given API revision must include +a set for each possible DPI bucket (tvdpi, xxhdpi, etc.) that may be tested. + + +II. Building theme tests + +1. If you have not already built the CTS tests, run an initial make: + + make cts -j32 + +2. Subsequent changes to the theme tests, including changes to the reference + images, may be built using mmm: + + mmm cts/hostsidetests/theme -j32 + + +III. Running theme tests + +1. Connect the device that you wish to test. Confirm that is is connected with: + + adb devices + +2. Run the theme tests using cts-tradefed: + + cts-tradefed run cts -c android.theme.cts.ThemeHostTest + +3. Wait for the tests to complete. This should take less than five minutes.
diff --git a/hostsidetests/theme/android_device.py b/hostsidetests/theme/android_device.py new file mode 100644 index 0000000..97b5fdd --- /dev/null +++ b/hostsidetests/theme/android_device.py
@@ -0,0 +1,107 @@ +#!/usr/bin/env python +# +# Copyright (C) 2015 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. +# + +import os +import re +import sys +import threading +import subprocess +import time + +# class for running android device from python +# it will fork the device processor +class androidDevice(object): + def __init__(self, adbDevice): + self._adbDevice = adbDevice + + def runAdbCommand(self, cmd): + self.waitForAdbDevice() + adbCmd = "adb -s %s %s" %(self._adbDevice, cmd) + adbProcess = subprocess.Popen(adbCmd.split(" "), bufsize = -1, stdout = subprocess.PIPE) + return adbProcess.communicate() + + def runShellCommand(self, cmd): + return self.runAdbCommand("shell " + cmd) + + def waitForAdbDevice(self): + os.system("adb -s %s wait-for-device" %self._adbDevice) + + def waitForBootComplete(self, timeout = 240): + boot_complete = False + attempts = 0 + wait_period = 5 + while not boot_complete and (attempts*wait_period) < timeout: + (output, err) = self.runShellCommand("getprop dev.bootcomplete") + output = output.strip() + if output == "1": + boot_complete = True + else: + time.sleep(wait_period) + attempts += 1 + if not boot_complete: + print "***boot not complete within timeout. will proceed to the next step" + return boot_complete + + def installApk(self, apkPath): + (out, err) = self.runAdbCommand("install -r -d -g " + apkPath) + result = out.split() + return (out, err, "Success" in result) + + def uninstallApk(self, package): + (out, err) = self.runAdbCommand("uninstall " + package) + result = out.split() + return "Success" in result + + def runInstrumentationTest(self, option): + return self.runShellCommand("am instrument -w " + option) + + def isProcessAlive(self, processName): + (out, err) = self.runShellCommand("ps") + names = out.split() + # very lazy implementation as it does not filter out things like uid + # should work mostly unless processName is too simple to overlap with + # uid. So only use name like com.android.xyz + return processName in names + + def getDensity(self): + if "emulator" in self._adbDevice: + return int(self.runShellCommand("getprop qemu.sf.lcd_density")[0]) + else: + return int(self.runShellCommand("getprop ro.sf.lcd_density")[0]) + + def getSdkLevel(self): + return int(self.runShellCommand("getprop ro.build.version.sdk")[0]) + + def getOrientation(self): + return int(self.runShellCommand("dumpsys | grep SurfaceOrientation")[0].split()[1]) + +def runAdbDevices(): + devices = subprocess.check_output(["adb", "devices"]) + devices = devices.split('\n')[1:] + + deviceSerial = [] + + for device in devices: + if device is not "": + info = device.split('\t') + if info[1] == "device": + deviceSerial.append(info[0]) + + return deviceSerial + +if __name__ == '__main__': + main(sys.argv)
diff --git a/hostsidetests/theme/app/Android.mk b/hostsidetests/theme/app/Android.mk index 70623cb..1be2983 100644 --- a/hostsidetests/theme/app/Android.mk +++ b/hostsidetests/theme/app/Android.mk
@@ -26,6 +26,8 @@ LOCAL_PROGUARD_ENABLED := disabled +LOCAL_STATIC_JAVA_LIBRARIES := android-support-test + LOCAL_SRC_FILES := $(call all-java-files-under, src) #Flags to tell the Android Asset Packaging Tool not to strip for some densities
diff --git a/hostsidetests/theme/app/AndroidManifest.xml b/hostsidetests/theme/app/AndroidManifest.xml index 81a4d9d..4e81ab0 100755 --- a/hostsidetests/theme/app/AndroidManifest.xml +++ b/hostsidetests/theme/app/AndroidManifest.xml
@@ -22,9 +22,10 @@ <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + <application> <uses-library android:name="android.test.runner" /> - <activity android:name=".HoloDeviceActivity"> + <activity android:name=".ThemeDeviceActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> @@ -37,6 +38,13 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> + <activity android:name=".GenerateImagesActivity" + android:exported="true" /> </application> + <!-- self-instrumenting test package. --> + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.theme.app" + android:label="Generates Theme reference images"/> + </manifest>
diff --git a/hostsidetests/theme/app/res/layout/holo_test.xml b/hostsidetests/theme/app/res/layout/theme_test.xml similarity index 100% rename from hostsidetests/theme/app/res/layout/holo_test.xml rename to hostsidetests/theme/app/res/layout/theme_test.xml
diff --git a/hostsidetests/theme/app/res/values/strings.xml b/hostsidetests/theme/app/res/values/strings.xml index a69a2e0..d9d66020 100644 --- a/hostsidetests/theme/app/res/values/strings.xml +++ b/hostsidetests/theme/app/res/values/strings.xml
@@ -14,8 +14,6 @@ limitations under the License. --> <resources> - <string name="holo_test_utilities">Holo Test Utilities</string> - <string name="display_info">Display Info</string> <string name="display_info_text">Density DPI: %1$d\nDensity Bucket: %2$s\nWidth DP: %3$d\nHeight DP: %4$d</string>
diff --git a/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java b/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java index f263eef..530675d 100644 --- a/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java +++ b/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java
@@ -25,7 +25,8 @@ import android.widget.TextView; /** - * An activity to display information about the device, including density bucket and dimensions. + * An activity to display information about the device, including density + * bucket and dimensions. */ public class DisplayInfoActivity extends Activity { @@ -62,9 +63,15 @@ case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; + case DisplayMetrics.DENSITY_360: + return "360dpi"; + case DisplayMetrics.DENSITY_400: return "400dpi"; + case DisplayMetrics.DENSITY_420: + return "420dpi"; + case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi";
diff --git a/hostsidetests/theme/app/src/android/theme/app/GenerateBitmapTask.java b/hostsidetests/theme/app/src/android/theme/app/GenerateBitmapTask.java new file mode 100644 index 0000000..05b6dcf --- /dev/null +++ b/hostsidetests/theme/app/src/android/theme/app/GenerateBitmapTask.java
@@ -0,0 +1,97 @@ +/* + * Copyright (C) 2015 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 android.theme.app; + +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.Canvas; +import android.os.AsyncTask; +import android.os.Environment; +import android.util.Log; +import android.view.View; + +import java.io.File; +import java.io.FileOutputStream; + +/** + * A task which gets the UI element to render to a bitmap and then saves that + * as a PNG asynchronously. + */ +class GenerateBitmapTask extends AsyncTask<Void, Void, Boolean> { + private static final String TAG = "GenerateBitmapTask"; + + private final View mView; + private final File mOutDir; + + private Bitmap mBitmap; + + protected final String mName; + + public GenerateBitmapTask(View view, File outDir, String name) { + mView = view; + mOutDir = outDir; + mName = name; + } + + @Override + protected void onPreExecute() { + if (mView.getWidth() == 0 || mView.getHeight() == 0) { + Log.e(TAG, "Unable to draw view due to incorrect size: " + mName); + return; + } + + mBitmap = Bitmap.createBitmap(mView.getWidth(), mView.getHeight(), + Bitmap.Config.ARGB_8888); + + final Canvas canvas = new Canvas(mBitmap); + mView.draw(canvas); + } + + @Override + protected Boolean doInBackground(Void... ignored) { + final Bitmap bitmap = mBitmap; + if (bitmap == null) { + return false; + } + + final File file = new File(mOutDir, mName + ".png"); + if (file.exists() && !file.canWrite()) { + Log.e(TAG, "Unable to write file: " + file.getAbsolutePath()); + return false; + } + + boolean success = false; + try { + FileOutputStream stream = null; + try { + stream = new FileOutputStream(file); + success = bitmap.compress(CompressFormat.PNG, 100, stream); + } finally { + if (stream != null) { + stream.flush(); + stream.close(); + } + } + } catch (Exception e) { + Log.e(TAG, e.getMessage()); + } finally { + bitmap.recycle(); + } + + return success; + } +}
diff --git a/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java new file mode 100644 index 0000000..e7f5aa2 --- /dev/null +++ b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
@@ -0,0 +1,200 @@ +/* + * Copyright (C) 2015 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 android.theme.app; + +import android.Manifest.permission; +import android.app.Activity; +import android.app.KeyguardManager; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build.VERSION; +import android.os.Bundle; +import android.os.Environment; +import android.os.Handler; +import android.util.Log; +import android.view.WindowManager.LayoutParams; + +import java.io.File; +import java.util.concurrent.CountDownLatch; + +/** + * Generates images by iterating through all themes and launching instances of + * {@link ThemeDeviceActivity}. + */ +public class GenerateImagesActivity extends Activity { + private static final String TAG = "GenerateImagesActivity"; + + private static final String OUT_DIR = "cts-theme-assets"; + private static final int REQUEST_CODE = 1; + + private final CountDownLatch mLatch = new CountDownLatch(1); + + private File mOutputDir; + private int mCurrentTheme; + private String mFinishReason; + private boolean mFinishSuccess; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON + | LayoutParams.FLAG_TURN_SCREEN_ON + | LayoutParams.FLAG_DISMISS_KEYGUARD); + + mOutputDir = new File(Environment.getExternalStorageDirectory(), OUT_DIR); + ThemeTestUtils.deleteDirectory(mOutputDir); + mOutputDir.mkdirs(); + + if (!mOutputDir.exists()) { + finish("Failed to create output directory " + mOutputDir.getAbsolutePath(), false); + return; + } + + final boolean canDisableKeyguard = checkCallingOrSelfPermission( + permission.DISABLE_KEYGUARD) == PackageManager.PERMISSION_GRANTED; + if (!canDisableKeyguard) { + finish("Not granted permission to disable keyguard", false); + return; + } + + new KeyguardCheck(this) { + @Override + public void onSuccess() { + generateNextImage(); + } + + @Override + public void onFailure() { + finish("Device is locked", false); + } + }.start(); + } + + private void finish(String reason, boolean success) { + mFinishSuccess = success; + mFinishReason = reason; + + Log.i(TAG, (success ? "OKAY" : "FAIL") + ":" + reason); + finish(); + } + + public boolean isFinishSuccess() { + return mFinishSuccess; + } + + public String getFinishReason() { + return mFinishReason; + } + + static abstract class KeyguardCheck implements Runnable { + private static final int MAX_RETRIES = 3; + private static final int RETRY_DELAY = 500; + + private final Handler mHandler; + private final KeyguardManager mKeyguard; + + private int mRetries; + + public KeyguardCheck(Context context) { + mHandler = new Handler(context.getMainLooper()); + mKeyguard = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE); + } + + public void start() { + mRetries = 0; + + mHandler.removeCallbacks(this); + mHandler.post(this); + } + + public void cancel() { + mHandler.removeCallbacks(this); + } + + @Override + public void run() { + if (!mKeyguard.isKeyguardLocked()) { + onSuccess(); + } else if (mRetries < MAX_RETRIES) { + mRetries++; + mHandler.postDelayed(this, RETRY_DELAY); + } else { + onFailure(); + } + + } + + public abstract void onSuccess(); + public abstract void onFailure(); + } + + public File getOutputDir() { + return mOutputDir; + } + + /** + * Starts the activity to generate the next image. + */ + private boolean generateNextImage() { + final ThemeDeviceActivity.Theme theme = ThemeDeviceActivity.THEMES[mCurrentTheme]; + if (theme.apiLevel > VERSION.SDK_INT) { + Log.v(TAG, "Skipping theme \"" + theme.name + + "\" (requires API " + theme.apiLevel + ")"); + return false; + } + + Log.v(TAG, "Generating images for theme \"" + theme.name + "\"..."); + + final Intent intent = new Intent(this, ThemeDeviceActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.putExtra(ThemeDeviceActivity.EXTRA_THEME, mCurrentTheme); + intent.putExtra(ThemeDeviceActivity.EXTRA_OUTPUT_DIR, mOutputDir.getAbsolutePath()); + startActivityForResult(intent, REQUEST_CODE); + return true; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode != RESULT_OK) { + Log.i(TAG, "FAIL:Failed to generate images for theme " + mCurrentTheme); + finish(); + return; + } + + // Keep trying themes until one works. + boolean success = false; + while (++mCurrentTheme < ThemeDeviceActivity.THEMES.length && !success) { + success = generateNextImage(); + } + + // If we ran out of themes, we're done. + if (!success) { + finish("Image generation complete!", true); + } + } + + public void finish() { + mLatch.countDown(); + super.finish(); + } + + public void waitForCompletion() throws InterruptedException { + mLatch.await(); + } +}
diff --git a/hostsidetests/theme/app/src/android/theme/app/HoloDeviceActivity.java b/hostsidetests/theme/app/src/android/theme/app/HoloDeviceActivity.java deleted file mode 100644 index 8ae9fc8..0000000 --- a/hostsidetests/theme/app/src/android/theme/app/HoloDeviceActivity.java +++ /dev/null
@@ -1,331 +0,0 @@ -/* - * 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 android.theme.app; - -import android.app.Activity; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Bitmap.CompressFormat; -import android.graphics.Canvas; -import android.os.AsyncTask; -import android.os.Environment; -import android.os.Bundle; -import android.os.Handler; -import android.theme.app.modifiers.DatePickerModifier; -import android.theme.app.modifiers.ProgressBarModifier; -import android.theme.app.modifiers.SearchViewModifier; -import android.theme.app.modifiers.TimePickerModifier; -import android.theme.app.modifiers.ViewCheckedModifier; -import android.theme.app.modifiers.ViewPressedModifier; -import android.theme.app.R; -import android.theme.app.ReferenceViewGroup; -import android.util.Log; -import android.view.View; -import android.widget.CheckBox; -import android.widget.DatePicker; -import android.widget.LinearLayout; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.Override; - -/** - * A activity which display various UI elements with Holo theme. - */ -public class HoloDeviceActivity extends Activity { - - public static final String EXTRA_THEME = "holo_theme_extra"; - - private static final String TAG = HoloDeviceActivity.class.getSimpleName(); - - /** - * The duration of the CalendarView adjustement to settle to its final position. - */ - private static final long CALENDAR_VIEW_ADJUSTMENT_DURATION = 540; - - private Theme mTheme; - - private ReferenceViewGroup mViewGroup; - - private int mLayoutIndex; - - @Override - protected void onCreate(Bundle icicle) { - super.onCreate(icicle); - - mTheme = THEMES[getIntent().getIntExtra(EXTRA_THEME, 0)]; - setTheme(mTheme.mId); - setContentView(R.layout.holo_test); - mViewGroup = (ReferenceViewGroup) findViewById(R.id.reference_view_group); - } - - @Override - protected void onResume() { - super.onResume(); - setNextLayout(); - } - - @Override - protected void onPause() { - if (!isFinishing()) { - // The Activity got paused for some reasons, for finish it as the host won't move on to - // the next theme otherwise. - Log.w(TAG, "onPause called without a call to finish()."); - finish(); - } - super.onPause(); - } - - @Override - protected void onDestroy() { - if (mLayoutIndex != LAYOUTS.length) { - Log.w(TAG, "Not all layouts got rendered: " + mLayoutIndex); - } - Log.i(TAG, "OKAY:" + mTheme.mName); - super.onDestroy(); - } - - /** - * Sets the next layout in the UI. - */ - private void setNextLayout() { - if (mLayoutIndex >= LAYOUTS.length) { - finish(); - return; - } - final Layout layout = LAYOUTS[mLayoutIndex++]; - final String layoutName = String.format("%s_%s", mTheme.mName, layout.mName); - - mViewGroup.removeAllViews(); - final View view = getLayoutInflater().inflate(layout.mId, mViewGroup, false); - if (layout.mModifier != null) { - layout.mModifier.modifyView(view); - } - mViewGroup.addView(view); - view.setFocusable(false); - - final Runnable generateBitmapRunnable = new Runnable() { - @Override - public void run() { - new GenerateBitmapTask(view, layoutName).execute(); - } - }; - - if (view instanceof DatePicker) { - // DatePicker uses a CalendarView that has a non-configurable adjustment duration of - // 540ms - view.postDelayed(generateBitmapRunnable, CALENDAR_VIEW_ADJUSTMENT_DURATION); - } else { - view.post(generateBitmapRunnable); - } - } - - /** - * A task which gets the UI element to render to a bitmap and then saves that as a png - * asynchronously - */ - private class GenerateBitmapTask extends AsyncTask<Void, Void, Boolean> { - - private final View mView; - - private final String mName; - - public GenerateBitmapTask(final View view, final String name) { - super(); - mView = view; - mName = name; - } - - @Override - protected Boolean doInBackground(Void... ignored) { - if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { - Log.i(TAG, "External storage for saving bitmaps is not mounted"); - return false; - } - if (mView.getWidth() == 0 || mView.getHeight() == 0) { - Log.w(TAG, "Unable to draw View due to incorrect size: " + mName); - return false; - } - - final Bitmap bitmap = Bitmap.createBitmap( - mView.getWidth(), mView.getHeight(), Bitmap.Config.ARGB_8888); - final Canvas canvas = new Canvas(bitmap); - - mView.draw(canvas); - final File dir = new File(Environment.getExternalStorageDirectory(), "cts-holo-assets"); - dir.mkdirs(); - boolean success = false; - try { - final File file = new File(dir, mName + ".png"); - FileOutputStream stream = null; - try { - stream = new FileOutputStream(file); - success = bitmap.compress(CompressFormat.PNG, 100, stream); - } finally { - if (stream != null) { - stream.close(); - } - } - } catch (Exception e) { - Log.e(TAG, e.getMessage()); - } finally { - bitmap.recycle(); - } - return success; - } - - @Override - protected void onPostExecute(Boolean success) { - setNextLayout(); - } - } - - /** - * A class to encapsulate information about a holo theme. - */ - private static class Theme { - - public final int mId; - - public final String mName; - - private Theme(int id, String name) { - mId = id; - mName = name; - } - } - - private static final Theme[] THEMES = { - new Theme(android.R.style.Theme_Holo, - "holo"), - new Theme(android.R.style.Theme_Holo_Dialog, - "holo_dialog"), - new Theme(android.R.style.Theme_Holo_Dialog_MinWidth, - "holo_dialog_minwidth"), - new Theme(android.R.style.Theme_Holo_Dialog_NoActionBar, - "holo_dialog_noactionbar"), - new Theme(android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth, - "holo_dialog_noactionbar_minwidth"), - new Theme(android.R.style.Theme_Holo_DialogWhenLarge, - "holo_dialogwhenlarge"), - new Theme(android.R.style.Theme_Holo_DialogWhenLarge_NoActionBar, - "holo_dialogwhenlarge_noactionbar"), - new Theme(android.R.style.Theme_Holo_InputMethod, - "holo_inputmethod"), - new Theme(android.R.style.Theme_Holo_Light, - "holo_light"), - new Theme(android.R.style.Theme_Holo_Light_DarkActionBar, - "holo_light_darkactionbar"), - new Theme(android.R.style.Theme_Holo_Light_Dialog, - "holo_light_dialog"), - new Theme(android.R.style.Theme_Holo_Light_Dialog_MinWidth, - "holo_light_dialog_minwidth"), - new Theme(android.R.style.Theme_Holo_Light_Dialog_NoActionBar, - "holo_light_dialog_noactionbar"), - new Theme(android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth, - "holo_light_dialog_noactionbar_minwidth"), - new Theme(android.R.style.Theme_Holo_Light_DialogWhenLarge, - "holo_light_dialogwhenlarge"), - new Theme(android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar, - "holo_light_dialogwhenlarge_noactionbar"), - new Theme(android.R.style.Theme_Holo_Light_NoActionBar, - "holo_light_noactionbar"), - new Theme(android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen, - "holo_light_noactionbar_fullscreen"), - new Theme(android.R.style.Theme_Holo_Light_Panel, - "holo_light_panel"), - new Theme(android.R.style.Theme_Holo_NoActionBar, - "holo_noactionbar"), - new Theme(android.R.style.Theme_Holo_NoActionBar_Fullscreen, - "holo_noactionbar_fullscreen"), - new Theme(android.R.style.Theme_Holo_Panel, - "holo_panel"), - new Theme(android.R.style.Theme_Holo_Wallpaper, - "holo_wallpaper"), - new Theme(android.R.style.Theme_Holo_Wallpaper_NoTitleBar, - "holo_wallpaper_notitlebar") - }; - - /** - * A class to encapsulate information about a holo layout. - */ - private static class Layout { - - public final int mId; - - public final String mName; - - public final LayoutModifier mModifier; - - private Layout(int id, String name, LayoutModifier modifier) { - mId = id; - mName = name; - mModifier = modifier; - } - } - - private static final Layout[] LAYOUTS = { - new Layout(R.layout.button, "button", null), - new Layout(R.layout.button, "button_pressed", new ViewPressedModifier()), - new Layout(R.layout.checkbox, "checkbox", null), - new Layout(R.layout.checkbox, "checkbox_checked", new ViewCheckedModifier()), - new Layout(R.layout.chronometer, "chronometer", null), - new Layout(R.layout.color_blue_bright, "color_blue_bright", null), - new Layout(R.layout.color_blue_dark, "color_blue_dark", null), - new Layout(R.layout.color_blue_light, "color_blue_light", null), - new Layout(R.layout.color_green_dark, "color_green_dark", null), - new Layout(R.layout.color_green_light, "color_green_light", null), - new Layout(R.layout.color_orange_dark, "color_orange_dark", null), - new Layout(R.layout.color_orange_light, "color_orange_light", null), - new Layout(R.layout.color_purple, "color_purple", null), - new Layout(R.layout.color_red_dark, "color_red_dark", null), - new Layout(R.layout.color_red_light, "color_red_light", null), - new Layout(R.layout.datepicker, "datepicker", new DatePickerModifier()), - new Layout(R.layout.display_info, "display_info", null), - new Layout(R.layout.edittext, "edittext", null), - new Layout(R.layout.progressbar_horizontal_0, "progressbar_horizontal_0", null), - new Layout(R.layout.progressbar_horizontal_100, "progressbar_horizontal_100", null), - new Layout(R.layout.progressbar_horizontal_50, "progressbar_horizontal_50", null), - new Layout(R.layout.progressbar_large, "progressbar_large", new ProgressBarModifier()), - new Layout(R.layout.progressbar_small, "progressbar_small", new ProgressBarModifier()), - new Layout(R.layout.progressbar, "progressbar", new ProgressBarModifier()), - new Layout(R.layout.radiobutton_checked, "radiobutton_checked", null), - new Layout(R.layout.radiobutton, "radiobutton", null), - new Layout(R.layout.radiogroup_horizontal, "radiogroup_horizontal", null), - new Layout(R.layout.radiogroup_vertical, "radiogroup_vertical", null), - new Layout(R.layout.ratingbar_0, "ratingbar_0", null), - new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5", null), - new Layout(R.layout.ratingbar_5, "ratingbar_5", null), - new Layout(R.layout.ratingbar_0, "ratingbar_0_pressed", new ViewPressedModifier()), - new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5_pressed", new ViewPressedModifier()), - new Layout(R.layout.ratingbar_5, "ratingbar_5_pressed", new ViewPressedModifier()), - new Layout(R.layout.searchview, "searchview_query", new SearchViewModifier(SearchViewModifier.QUERY)), - new Layout(R.layout.searchview, "searchview_query_hint", new SearchViewModifier(SearchViewModifier.QUERY_HINT)), - new Layout(R.layout.seekbar_0, "seekbar_0", null), - new Layout(R.layout.seekbar_100, "seekbar_100", null), - new Layout(R.layout.seekbar_50, "seekbar_50", null), - new Layout(R.layout.spinner, "spinner", null), - new Layout(R.layout.switch_button_checked, "switch_button_checked", null), - new Layout(R.layout.switch_button, "switch_button", null), - new Layout(R.layout.textview, "textview", null), - new Layout(R.layout.timepicker, "timepicker", new TimePickerModifier()), - new Layout(R.layout.togglebutton_checked, "togglebutton_checked", null), - new Layout(R.layout.togglebutton, "togglebutton", null), - new Layout(R.layout.zoomcontrols, "zoomcontrols", null), - }; -}
diff --git a/hostsidetests/theme/app/src/android/theme/app/ReferenceImagesTest.java b/hostsidetests/theme/app/src/android/theme/app/ReferenceImagesTest.java new file mode 100644 index 0000000..7569252 --- /dev/null +++ b/hostsidetests/theme/app/src/android/theme/app/ReferenceImagesTest.java
@@ -0,0 +1,52 @@ +/* + * Copyright (C) 2015 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 android.theme.app; + +import android.test.ActivityInstrumentationTestCase2; + +import java.io.File; + +/** + * Activity test case used to instrument generation of reference images. + */ +public class ReferenceImagesTest extends ActivityInstrumentationTestCase2<GenerateImagesActivity> { + + public ReferenceImagesTest() { + super(GenerateImagesActivity.class); + } + + public void testGenerateReferenceImages() throws Exception { + setActivityInitialTouchMode(true); + + final GenerateImagesActivity activity = getActivity(); + activity.waitForCompletion(); + + assertTrue(activity.getFinishReason(), activity.isFinishSuccess()); + + final File outputDir = activity.getOutputDir(); + final File outputZip = new File(outputDir.getParentFile(), outputDir.getName() + ".zip"); + if (outputZip.exists()) { + // Remove any old test results. + outputZip.delete(); + } + + ThemeTestUtils.compressDirectory(outputDir, outputZip); + ThemeTestUtils.deleteDirectory(outputDir); + + assertTrue("Generated reference image ZIP", outputZip.exists()); + } +}
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java new file mode 100644 index 0000000..d8b1f30 --- /dev/null +++ b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
@@ -0,0 +1,414 @@ +/* + * Copyright (C) 2015 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 android.theme.app; + +import android.app.Activity; +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.theme.app.modifiers.DatePickerModifier; +import android.theme.app.modifiers.ProgressBarModifier; +import android.theme.app.modifiers.SearchViewModifier; +import android.theme.app.modifiers.TimePickerModifier; +import android.theme.app.modifiers.ViewCheckedModifier; +import android.theme.app.modifiers.ViewPressedModifier; +import android.util.Log; +import android.view.View; +import android.view.WindowManager.LayoutParams; +import android.widget.DatePicker; + +import java.io.File; +import java.lang.Override; + +/** + * A activity which display various UI elements with non-modifiable themes. + */ +public class ThemeDeviceActivity extends Activity { + public static final String EXTRA_THEME = "theme"; + public static final String EXTRA_OUTPUT_DIR = "outputDir"; + + private static final String TAG = "ThemeDeviceActivity"; + + /** + * The duration of the CalendarView adjustment to settle to its final + * position. + */ + private static final long CALENDAR_VIEW_ADJUSTMENT_DURATION = 540; + + private Theme mTheme; + private ReferenceViewGroup mViewGroup; + private File mOutputDir; + private int mLayoutIndex; + private boolean mIsRunning; + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + final Intent intent = getIntent(); + final int themeIndex = intent.getIntExtra(EXTRA_THEME, -1); + if (themeIndex < 0) { + Log.e(TAG, "No theme specified"); + finish(); + } + + final String outputDir = intent.getStringExtra(EXTRA_OUTPUT_DIR); + if (outputDir == null) { + Log.e(TAG, "No output directory specified"); + finish(); + } + + mOutputDir = new File(outputDir); + mTheme = THEMES[themeIndex]; + + setTheme(mTheme.id); + setContentView(R.layout.theme_test); + + mViewGroup = (ReferenceViewGroup) findViewById(R.id.reference_view_group); + + getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON + | LayoutParams.FLAG_TURN_SCREEN_ON + | LayoutParams.FLAG_DISMISS_KEYGUARD ); + } + + @Override + protected void onResume() { + super.onResume(); + + mIsRunning = true; + + setNextLayout(); + } + + @Override + protected void onPause() { + mIsRunning = false; + + if (!isFinishing()) { + // The activity paused for some reason, likely a system crash + // dialog. Finish it so we can move to the next theme. + Log.w(TAG, "onPause() called without a call to finish()", new RuntimeException()); + finish(); + } + + super.onPause(); + } + + @Override + protected void onDestroy() { + if (mLayoutIndex < LAYOUTS.length) { + Log.e(TAG, "Not all layouts got rendered: " + mLayoutIndex); + setResult(RESULT_CANCELED); + } + + super.onDestroy(); + } + + /** + * Sets the next layout in the UI. + */ + private void setNextLayout() { + if (mLayoutIndex >= LAYOUTS.length) { + setResult(RESULT_OK); + finish(); + return; + } + + mViewGroup.removeAllViews(); + + final Layout layout = LAYOUTS[mLayoutIndex++]; + final String layoutName = String.format("%s_%s", mTheme.name, layout.name); + final View view = getLayoutInflater().inflate(layout.id, mViewGroup, false); + if (layout.modifier != null) { + layout.modifier.modifyView(view); + } + + mViewGroup.addView(view); + view.setFocusable(false); + + Log.v(TAG, "Rendering layout " + layoutName + + " (" + mLayoutIndex + "/" + LAYOUTS.length + ")"); + + final Runnable generateBitmapRunnable = new Runnable() { + @Override + public void run() { + new BitmapTask(view, layoutName).execute(); + } + }; + + if (view instanceof DatePicker) { + // The Holo-styled DatePicker uses a CalendarView that has a + // non-configurable adjustment duration of 540ms. + view.postDelayed(generateBitmapRunnable, CALENDAR_VIEW_ADJUSTMENT_DURATION); + } else { + view.post(generateBitmapRunnable); + } + } + + private class BitmapTask extends GenerateBitmapTask { + public BitmapTask(View view, String name) { + super(view, mOutputDir, name); + } + + @Override + protected void onPostExecute(Boolean success) { + if (success && mIsRunning) { + setNextLayout(); + } else { + Log.e(TAG, "Failed to render view to bitmap: " + mName + " (activity running? " + + mIsRunning + ")"); + finish(); + } + } + } + + /** + * A class to encapsulate information about a theme. + */ + static class Theme { + public final int id; + public final int apiLevel; + public final String name; + + private Theme(int id, int apiLevel, String name) { + this.id = id; + this.apiLevel = apiLevel; + this.name = name; + } + } + + // List of themes to verify. + static final Theme[] THEMES = { + // Holo + new Theme(android.R.style.Theme_Holo, + Build.VERSION_CODES.HONEYCOMB, "holo"), + new Theme(android.R.style.Theme_Holo_Dialog, + Build.VERSION_CODES.HONEYCOMB, "holo_dialog"), + new Theme(android.R.style.Theme_Holo_Dialog_MinWidth, + Build.VERSION_CODES.HONEYCOMB, "holo_dialog_minwidth"), + new Theme(android.R.style.Theme_Holo_Dialog_NoActionBar, + Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar"), + new Theme(android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth, + Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar_minwidth"), + new Theme(android.R.style.Theme_Holo_DialogWhenLarge, + Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge"), + new Theme(android.R.style.Theme_Holo_DialogWhenLarge_NoActionBar, + Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge_noactionbar"), + new Theme(android.R.style.Theme_Holo_InputMethod, + Build.VERSION_CODES.HONEYCOMB, "holo_inputmethod"), + new Theme(android.R.style.Theme_Holo_NoActionBar, + Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar"), + new Theme(android.R.style.Theme_Holo_NoActionBar_Fullscreen, + Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar_fullscreen"), + new Theme(android.R.style.Theme_Holo_NoActionBar_Overscan, + Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_noactionbar_overscan"), + new Theme(android.R.style.Theme_Holo_NoActionBar_TranslucentDecor, + Build.VERSION_CODES.KITKAT, "holo_noactionbar_translucentdecor"), + new Theme(android.R.style.Theme_Holo_Panel, + Build.VERSION_CODES.HONEYCOMB, "holo_panel"), + new Theme(android.R.style.Theme_Holo_Wallpaper, + Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper"), + new Theme(android.R.style.Theme_Holo_Wallpaper_NoTitleBar, + Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper_notitlebar"), + + // Holo Light + new Theme(android.R.style.Theme_Holo_Light, + Build.VERSION_CODES.HONEYCOMB, "holo_light"), + new Theme(android.R.style.Theme_Holo_Light_DarkActionBar, + Build.VERSION_CODES.ICE_CREAM_SANDWICH, "holo_light_darkactionbar"), + new Theme(android.R.style.Theme_Holo_Light_Dialog, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog"), + new Theme(android.R.style.Theme_Holo_Light_Dialog_MinWidth, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_minwidth"), + new Theme(android.R.style.Theme_Holo_Light_Dialog_NoActionBar, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar"), + new Theme(android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar_minwidth"), + new Theme(android.R.style.Theme_Holo_Light_DialogWhenLarge, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge"), + new Theme(android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar, + Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge_noactionbar"), + new Theme(android.R.style.Theme_Holo_Light_NoActionBar, + Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar"), + new Theme(android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen, + Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar_fullscreen"), + new Theme(android.R.style.Theme_Holo_Light_NoActionBar_Overscan, + Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_light_noactionbar_overscan"), + new Theme(android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor, + Build.VERSION_CODES.KITKAT, "holo_light_noactionbar_translucentdecor"), + new Theme(android.R.style.Theme_Holo_Light_Panel, + Build.VERSION_CODES.HONEYCOMB, "holo_light_panel"), + + // Material + new Theme(android.R.style.Theme_Material, + Build.VERSION_CODES.LOLLIPOP, "material"), + new Theme(android.R.style.Theme_Material_Dialog, + Build.VERSION_CODES.LOLLIPOP, "material_dialog"), + new Theme(android.R.style.Theme_Material_Dialog_Alert, + Build.VERSION_CODES.LOLLIPOP, "material_dialog_alert"), + new Theme(android.R.style.Theme_Material_Dialog_MinWidth, + Build.VERSION_CODES.LOLLIPOP, "material_dialog_minwidth"), + new Theme(android.R.style.Theme_Material_Dialog_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar"), + new Theme(android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth, + Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar_minwidth"), + new Theme(android.R.style.Theme_Material_Dialog_Presentation, + Build.VERSION_CODES.LOLLIPOP, "material_dialog_presentation"), + new Theme(android.R.style.Theme_Material_DialogWhenLarge, + Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge"), + new Theme(android.R.style.Theme_Material_DialogWhenLarge_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge_noactionbar"), + new Theme(android.R.style.Theme_Material_InputMethod, + Build.VERSION_CODES.LOLLIPOP, "material_inputmethod"), + new Theme(android.R.style.Theme_Material_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_noactionbar"), + new Theme(android.R.style.Theme_Material_NoActionBar_Fullscreen, + Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_fullscreen"), + new Theme(android.R.style.Theme_Material_NoActionBar_Overscan, + Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_overscan"), + new Theme(android.R.style.Theme_Material_NoActionBar_TranslucentDecor, + Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_translucentdecor"), + new Theme(android.R.style.Theme_Material_Panel, + Build.VERSION_CODES.LOLLIPOP, "material_panel"), + new Theme(android.R.style.Theme_Material_Settings, + Build.VERSION_CODES.LOLLIPOP, "material_settings"), + new Theme(android.R.style.Theme_Material_Voice, + Build.VERSION_CODES.LOLLIPOP, "material_voice"), + new Theme(android.R.style.Theme_Material_Wallpaper, + Build.VERSION_CODES.LOLLIPOP, "material_wallpaper"), + new Theme(android.R.style.Theme_Material_Wallpaper_NoTitleBar, + Build.VERSION_CODES.LOLLIPOP, "material_wallpaper_notitlebar"), + + // Material Light + new Theme(android.R.style.Theme_Material_Light, + Build.VERSION_CODES.LOLLIPOP, "material_light"), + new Theme(android.R.style.Theme_Material_Light_DarkActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_light_darkactionbar"), + new Theme(android.R.style.Theme_Material_Light_Dialog, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog"), + new Theme(android.R.style.Theme_Material_Light_Dialog_Alert, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_alert"), + new Theme(android.R.style.Theme_Material_Light_Dialog_MinWidth, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_minwidth"), + new Theme(android.R.style.Theme_Material_Light_Dialog_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar"), + new Theme(android.R.style.Theme_Material_Light_Dialog_NoActionBar_MinWidth, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar_minwidth"), + new Theme(android.R.style.Theme_Material_Light_Dialog_Presentation, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_presentation"), + new Theme(android.R.style.Theme_Material_Light_DialogWhenLarge, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge"), + new Theme(android.R.style.Theme_Material_Light_DialogWhenLarge_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge_noactionbar"), + new Theme(android.R.style.Theme_Material_Light_LightStatusBar, + Build.VERSION_CODES.M, "material_light_lightstatusbar"), + new Theme(android.R.style.Theme_Material_Light_NoActionBar, + Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar"), + new Theme(android.R.style.Theme_Material_Light_NoActionBar_Fullscreen, + Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_fullscreen"), + new Theme(android.R.style.Theme_Material_Light_NoActionBar_Overscan, + Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_overscan"), + new Theme(android.R.style.Theme_Material_Light_NoActionBar_TranslucentDecor, + Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_translucentdecor"), + new Theme(android.R.style.Theme_Material_Light_Panel, + Build.VERSION_CODES.LOLLIPOP, "material_light_panel"), + new Theme(android.R.style.Theme_Material_Light_Voice, + Build.VERSION_CODES.LOLLIPOP, "material_light_voice") + }; + + /** + * A class to encapsulate information about a layout. + */ + private static class Layout { + public final int id; + public final String name; + public final LayoutModifier modifier; + + private Layout(int id, String name) { + this(id, name, null); + } + + private Layout(int id, String name, LayoutModifier modifier) { + this.id = id; + this.name = name; + this.modifier = modifier; + } + } + + // List of layouts to verify for each theme. + private static final Layout[] LAYOUTS = { + new Layout(R.layout.button, "button"), + new Layout(R.layout.button, "button_pressed", + new ViewPressedModifier()), + new Layout(R.layout.checkbox, "checkbox"), + new Layout(R.layout.checkbox, "checkbox_checked", + new ViewCheckedModifier()), + new Layout(R.layout.chronometer, "chronometer"), + new Layout(R.layout.color_blue_bright, "color_blue_bright"), + new Layout(R.layout.color_blue_dark, "color_blue_dark"), + new Layout(R.layout.color_blue_light, "color_blue_light"), + new Layout(R.layout.color_green_dark, "color_green_dark"), + new Layout(R.layout.color_green_light, "color_green_light"), + new Layout(R.layout.color_orange_dark, "color_orange_dark"), + new Layout(R.layout.color_orange_light, "color_orange_light"), + new Layout(R.layout.color_purple, "color_purple"), + new Layout(R.layout.color_red_dark, "color_red_dark"), + new Layout(R.layout.color_red_light, "color_red_light"), + new Layout(R.layout.datepicker, "datepicker", + new DatePickerModifier()), + new Layout(R.layout.display_info, "display_info"), + new Layout(R.layout.edittext, "edittext"), + new Layout(R.layout.progressbar_horizontal_0, "progressbar_horizontal_0"), + new Layout(R.layout.progressbar_horizontal_100, "progressbar_horizontal_100"), + new Layout(R.layout.progressbar_horizontal_50, "progressbar_horizontal_50"), + new Layout(R.layout.progressbar_large, "progressbar_large", + new ProgressBarModifier()), + new Layout(R.layout.progressbar_small, "progressbar_small", + new ProgressBarModifier()), + new Layout(R.layout.progressbar, "progressbar", + new ProgressBarModifier()), + new Layout(R.layout.radiobutton_checked, "radiobutton_checked"), + new Layout(R.layout.radiobutton, "radiobutton"), + new Layout(R.layout.radiogroup_horizontal, "radiogroup_horizontal"), + new Layout(R.layout.radiogroup_vertical, "radiogroup_vertical"), + new Layout(R.layout.ratingbar_0, "ratingbar_0"), + new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5"), + new Layout(R.layout.ratingbar_5, "ratingbar_5"), + new Layout(R.layout.ratingbar_0, "ratingbar_0_pressed", + new ViewPressedModifier()), + new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5_pressed", + new ViewPressedModifier()), + new Layout(R.layout.ratingbar_5, "ratingbar_5_pressed", + new ViewPressedModifier()), + new Layout(R.layout.searchview, "searchview_query", + new SearchViewModifier(SearchViewModifier.QUERY)), + new Layout(R.layout.searchview, "searchview_query_hint", + new SearchViewModifier(SearchViewModifier.QUERY_HINT)), + new Layout(R.layout.seekbar_0, "seekbar_0"), + new Layout(R.layout.seekbar_100, "seekbar_100"), + new Layout(R.layout.seekbar_50, "seekbar_50"), + new Layout(R.layout.spinner, "spinner"), + new Layout(R.layout.switch_button_checked, "switch_button_checked"), + new Layout(R.layout.switch_button, "switch_button"), + new Layout(R.layout.textview, "textview"), + new Layout(R.layout.timepicker, "timepicker", + new TimePickerModifier()), + new Layout(R.layout.togglebutton_checked, "togglebutton_checked"), + new Layout(R.layout.togglebutton, "togglebutton"), + new Layout(R.layout.zoomcontrols, "zoomcontrols"), + }; +}
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeTestUtils.java b/hostsidetests/theme/app/src/android/theme/app/ThemeTestUtils.java new file mode 100644 index 0000000..4daca6c --- /dev/null +++ b/hostsidetests/theme/app/src/android/theme/app/ThemeTestUtils.java
@@ -0,0 +1,80 @@ +/* + * Copyright (C) 2015 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 android.theme.app; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ThemeTestUtils { + + /** + * Compresses the contents of a directory to a ZIP file. + * + * @param dir the directory to compress + * @return {@code true} on success, {@code false} on failure + */ + public static boolean compressDirectory(File dir, File file) throws IOException { + if (dir == null || !dir.exists() || file == null || file.exists()) { + return false; + } + + final File[] srcFiles = dir.listFiles(); + if (srcFiles.length == 0) { + return false; + } + + final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(file)); + final byte[] data = new byte[4096]; + for (int i = 0; i < srcFiles.length; i++) { + final FileInputStream fileIn = new FileInputStream(srcFiles[i]); + final ZipEntry entry = new ZipEntry(srcFiles[i].getName()); + zipOut.putNextEntry(entry); + + int count; + while ((count = fileIn.read(data, 0, data.length)) != -1) { + zipOut.write(data, 0, count); + zipOut.flush(); + } + + zipOut.closeEntry(); + fileIn.close(); + } + + zipOut.close(); + return true; + } + + /** + * Recursively deletes a directory and its contents. + * + * @param dir the directory to delete + * @return {@code true} on success, {@code false} on failure + */ + public static boolean deleteDirectory(File dir) { + final File files[] = dir.listFiles(); + if (files != null) { + for (File file : files) { + deleteDirectory(file); + } + } + return dir.delete(); + } +}
diff --git a/hostsidetests/theme/assets/23/400dpi.zip b/hostsidetests/theme/assets/23/400dpi.zip new file mode 100644 index 0000000..be0891f --- /dev/null +++ b/hostsidetests/theme/assets/23/400dpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/560dpi.zip b/hostsidetests/theme/assets/23/560dpi.zip new file mode 100644 index 0000000..cf0a559 --- /dev/null +++ b/hostsidetests/theme/assets/23/560dpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/hdpi.zip b/hostsidetests/theme/assets/23/hdpi.zip new file mode 100644 index 0000000..80c12a7 --- /dev/null +++ b/hostsidetests/theme/assets/23/hdpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/ldpi.zip b/hostsidetests/theme/assets/23/ldpi.zip new file mode 100644 index 0000000..937914a --- /dev/null +++ b/hostsidetests/theme/assets/23/ldpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/mdpi.zip b/hostsidetests/theme/assets/23/mdpi.zip new file mode 100644 index 0000000..f842676 --- /dev/null +++ b/hostsidetests/theme/assets/23/mdpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/tvdpi.zip b/hostsidetests/theme/assets/23/tvdpi.zip new file mode 100644 index 0000000..77386e5 --- /dev/null +++ b/hostsidetests/theme/assets/23/tvdpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/xhdpi.zip b/hostsidetests/theme/assets/23/xhdpi.zip new file mode 100644 index 0000000..a8310d5 --- /dev/null +++ b/hostsidetests/theme/assets/23/xhdpi.zip Binary files differ
diff --git a/hostsidetests/theme/assets/23/xxhdpi.zip b/hostsidetests/theme/assets/23/xxhdpi.zip new file mode 100644 index 0000000..f88711f --- /dev/null +++ b/hostsidetests/theme/assets/23/xxhdpi.zip Binary files differ
diff --git a/hostsidetests/theme/generate_images.sh b/hostsidetests/theme/generate_images.sh new file mode 100755 index 0000000..9bcc3e5 --- /dev/null +++ b/hostsidetests/theme/generate_images.sh
@@ -0,0 +1,55 @@ +#!/bin/sh +# Copyright (C) 2015 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. + +# This script is used to generate reference images for the CTS theme tests. +# See the accompanying README file for more information. + +# retry <command> <tries> <message> <delay> +function retry { + RETRY="0" + while true; do + if (("$RETRY" >= "$2")); then + echo $OUTPUT + exit + fi + + OUTPUT=`$1 |& grep error` + + if [ -z "$OUTPUT" ]; then + break + fi + + echo $3 + sleep $4 + RETRY=$[$RETRY + 1] + done +} + +themeApkPath="$ANDROID_HOST_OUT/cts/android-cts/repository/testcases/CtsThemeDeviceApp.apk" +outDir="$ANDROID_BUILD_TOP/cts/hostsidetests/theme/assets" +exe="$ANDROID_BUILD_TOP/cts/hostsidetests/theme/run_theme_capture_device.py" + +if [ -z "$ANDROID_BUILD_TOP" ]; then + echo "Missing environment variables. Did you run build/envsetup.sh and lunch?" + exit +fi + +if [ ! -e "$themeApkPath" ]; then + echo "Couldn't find test APK. Did you run make cts?" + exit +fi + +adb devices +python $exe $themeApkPath $outDir
diff --git a/hostsidetests/theme/run_theme_capture_device.py b/hostsidetests/theme/run_theme_capture_device.py new file mode 100755 index 0000000..23171db --- /dev/null +++ b/hostsidetests/theme/run_theme_capture_device.py
@@ -0,0 +1,170 @@ +#!/usr/bin/env python +# +# Copyright (C) 2015 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. +# + +import os +import sys +import threading +import time +import Queue +sys.path.append(sys.path[0]) +from android_device import * + +CTS_THEME_dict = { + 120 : "ldpi", + 160 : "mdpi", + 213 : "tvdpi", + 240 : "hdpi", + 320 : "xhdpi", + 400 : "400dpi", + 480 : "xxhdpi", + 560 : "560dpi", + 640 : "xxxhdpi", +} + +OUT_FILE = "/sdcard/cts-theme-assets.zip" + +# pass a function with number of instances to be executed in parallel +# each thread continues until config q is empty. +def executeParallel(tasks, setup, q, numberThreads): + class ParallelExecutor(threading.Thread): + def __init__(self, tasks, q): + threading.Thread.__init__(self) + self._q = q + self._tasks = tasks + self._setup = setup + self._result = 0 + + def run(self): + try: + while True: + config = q.get(block=True, timeout=2) + for t in self._tasks: + try: + if t(self._setup, config): + self._result += 1 + except KeyboardInterrupt: + raise + except: + print "Failed to execute thread:", sys.exc_info()[0] + q.task_done() + except KeyboardInterrupt: + raise + except Queue.Empty: + pass + + def getResult(self): + return self._result + + result = 0; + threads = [] + for i in range(numberThreads): + t = ParallelExecutor(tasks, q) + t.start() + threads.append(t) + for t in threads: + t.join() + result += t.getResult() + return result; + +def printAdbResult(device, out, err): + print "device: " + device + if out is not None: + print "out:\n" + out + if err is not None: + print "err:\n" + err + +def getResDir(outPath, resName): + resDir = outPath + "/" + resName + return resDir + +def doCapturing(setup, deviceSerial): + (themeApkPath, outPath) = setup + + print "Found device: " + deviceSerial + device = androidDevice(deviceSerial) + + # outPath = outPath + "/%d/" % (device.getSdkLevel()) + deviceSerial + outPath = outPath + "/%d" % (device.getSdkLevel()) + density = device.getDensity() + resName = CTS_THEME_dict[density] + + device.uninstallApk("android.theme.app") + + (out, err, success) = device.installApk(themeApkPath) + if not success: + print "Failed to install APK on " + deviceSerial + printAdbResult(device, out, err) + return False + + print "Generating images on " + deviceSerial + "..." + try: + (out, err) = device.runInstrumentationTest("android.theme.app/android.support.test.runner.AndroidJUnitRunner") + except KeyboardInterrupt: + raise + except: + (out, err) = device.runInstrumentationTest("android.theme.app/android.test.InstrumentationTestRunner") + + # Detect test failure and abort. + if "FAILURES!!!" in out.split(): + printAdbResult(deviceSerial, out, err) + return False + + # Make sure that the run is complete by checking the process itself + print "Waiting for " + deviceSerial + "..." + waitTime = 0 + while device.isProcessAlive("android.theme.app"): + time.sleep(1) + waitTime = waitTime + 1 + if waitTime > 180: + print "Timed out" + break + + time.sleep(10) + resDir = getResDir(outPath, resName) + + print "Pulling images from " + deviceSerial + " to " + resDir + ".zip" + device.runAdbCommand("pull " + OUT_FILE + " " + resDir + ".zip") + device.runAdbCommand("shell rm -rf " + OUT_FILE) + return True + +def main(argv): + if len(argv) < 3: + print "run_theme_capture_device.py themeApkPath outDir" + sys.exit(1) + themeApkPath = argv[1] + outPath = os.path.abspath(argv[2]) + os.system("mkdir -p " + outPath) + + tasks = [] + tasks.append(doCapturing) + + devices = runAdbDevices(); + numberThreads = len(devices) + + configQ = Queue.Queue() + for device in devices: + configQ.put(device) + setup = (themeApkPath, outPath) + result = executeParallel(tasks, setup, configQ, numberThreads) + + if result > 0: + print 'Generated reference images for %(count)d devices' % {"count": result} + else: + print 'Failed to generate reference images' + +if __name__ == '__main__': + main(sys.argv)
diff --git a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java index 7277b9f..0e11111 100755 --- a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java +++ b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
@@ -23,6 +23,7 @@ import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; +import java.io.IOException; import java.lang.String; import java.util.concurrent.Callable; @@ -32,59 +33,50 @@ * Compares the images generated by the device with the reference images. */ public class ComparisonTask implements Callable<Boolean> { - - private static final String TAG = ComparisonTask.class.getSimpleName(); + private static final String TAG = "ComparisonTask"; private static final int IMAGE_THRESHOLD = 2; - private static final String STORAGE_PATH_DEVICE = "/sdcard/cts-holo-assets/%s.png"; - private final ITestDevice mDevice; + private final File mExpected; + private final File mActual; - private final File mReference; - - private final String mName; - - public ComparisonTask(ITestDevice device, File reference, String name) { + public ComparisonTask(ITestDevice device, File expected, File actual) { mDevice = device; - mReference = reference; - mName = name; + mExpected = expected; + mActual = actual; } public Boolean call() { boolean success = false; - File generated = null; + try { - generated = File.createTempFile("gen_" + mName, ".png"); - - final String remoteGenerated = String.format(STORAGE_PATH_DEVICE, mName); - if (!mDevice.doesFileExist(remoteGenerated)) { - Log.logAndDisplay(LogLevel.ERROR, TAG, "File " + remoteGenerated + " have not been saved on device"); - return false; - } - mDevice.pullFile(remoteGenerated, generated); - - final BufferedImage ref = ImageIO.read(mReference); - final BufferedImage gen = ImageIO.read(generated); - if (compare(ref, gen, IMAGE_THRESHOLD)) { + final BufferedImage expected = ImageIO.read(mExpected); + final BufferedImage actual = ImageIO.read(mActual); + if (compare(expected, actual, IMAGE_THRESHOLD)) { success = true; } else { - File diff = File.createTempFile("diff_" + mName, ".png"); - createDiff(ref, gen, diff); + final File diff = File.createTempFile("diff_" + mExpected.getName(), ".png"); + createDiff(expected, actual, diff); Log.logAndDisplay(LogLevel.INFO, TAG, "Diff created: " + diff.getPath()); } - } catch (Exception e) { - Log.logAndDisplay(LogLevel.ERROR, TAG, String.format(STORAGE_PATH_DEVICE, mName)); + } catch (IOException e) { Log.logAndDisplay(LogLevel.ERROR, TAG, e.toString()); e.printStackTrace(); - } finally { - if (generated != null) { - generated.delete(); - } } + return success; } + /** + * Verifies that the pixels of reference and generated images are similar + * within a specified threshold. + * + * @param expected expected image + * @param actual actual image + * @param threshold maximum difference per channel + * @return {@code true} if the images are similar, false otherwise + */ private static int getAlphaScaledBlue(final int color) { return (color & 0x000000FF) * getAlpha(color) / 255; } @@ -128,45 +120,49 @@ return true; } - private static void createDiff(BufferedImage image1, BufferedImage image2, File out) - throws Exception { - final int w1 = image1.getWidth(); - final int h1 = image1.getHeight(); - final int w2 = image2.getWidth(); - final int h2 = image2.getHeight(); + private static void createDiff(BufferedImage expected, BufferedImage actual, File out) + throws IOException { + final int w1 = expected.getWidth(); + final int h1 = expected.getHeight(); + final int w2 = actual.getWidth(); + final int h2 = actual.getHeight(); final int width = Math.max(w1, w2); final int height = Math.max(h1, h2); + // The diff will contain image1, image2 and the difference between the two. - final BufferedImage diff = new BufferedImage(width * 3, height, BufferedImage.TYPE_INT_ARGB); + final BufferedImage diff = new BufferedImage( + width * 3, height, BufferedImage.TYPE_INT_ARGB); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { final boolean inBounds1 = i < w1 && j < h1; final boolean inBounds2 = i < w2 && j < h2; - int color1 = Color.WHITE.getRGB(); - int color2 = Color.WHITE.getRGB(); - int color3; + int colorExpected = Color.WHITE.getRGB(); + int colorActual = Color.WHITE.getRGB(); + int colorDiff; if (inBounds1 && inBounds2) { - color1 = image1.getRGB(i, j); - color2 = image2.getRGB(i, j); - color3 = color1 == color2 ? color1 : Color.RED.getRGB(); + colorExpected = expected.getRGB(i, j); + colorActual = actual.getRGB(i, j); + colorDiff = colorExpected == colorActual ? colorExpected : Color.RED.getRGB(); } else if (inBounds1 && !inBounds2) { - color1 = image1.getRGB(i, j); - color3 = Color.BLUE.getRGB(); + colorExpected = expected.getRGB(i, j); + colorDiff = Color.BLUE.getRGB(); } else if (!inBounds1 && inBounds2) { - color2 = image2.getRGB(i, j); - color3 = Color.GREEN.getRGB(); + colorActual = actual.getRGB(i, j); + colorDiff = Color.GREEN.getRGB(); } else { - color3 = Color.MAGENTA.getRGB(); + colorDiff = Color.MAGENTA.getRGB(); } + int x = i; - diff.setRGB(x, j, color1); + diff.setRGB(x, j, colorExpected); x += width; - diff.setRGB(x, j, color2); + diff.setRGB(x, j, colorActual); x += width; - diff.setRGB(x, j, color3); + diff.setRGB(x, j, colorDiff); } } + ImageIO.write(diff, "png", out); }
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java index 8326b1f..b4bb748 100644 --- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java +++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -21,8 +21,8 @@ import com.android.cts.util.TimeoutReq; import com.android.ddmlib.Log; import com.android.ddmlib.Log.LogLevel; -import com.android.ddmlib.IShellOutputReceiver; import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.DeviceNotAvailableException; import com.android.tradefed.device.ITestDevice; import com.android.tradefed.testtype.DeviceTestCase; import com.android.tradefed.testtype.IAbi; @@ -30,145 +30,44 @@ import com.android.tradefed.testtype.IBuildReceiver; import java.io.File; +import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.lang.String; -import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; -import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** - * Test to check the Holo theme has not been changed. + * Test to check non-modifiable themes have not been changed. */ public class ThemeHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { + private static final String LOG_TAG = "ThemeHostTest"; + private static final String APK_NAME = "CtsThemeDeviceApp"; + private static final String APP_PACKAGE_NAME = "android.theme.app"; - private static final String TAG = ThemeHostTest.class.getSimpleName(); - - private static final int ADB_TIMEOUT = 60 * 60 * 1000;//60mins in ms - - /** The package name of the APK. */ - private static final String PACKAGE = "android.theme.app"; - - /** The file name of the APK. */ - private static final String APK = "CtsThemeDeviceApp.apk"; + private static final String GENERATED_ASSETS_ZIP = "/sdcard/cts-theme-assets.zip"; /** The class name of the main activity in the APK. */ - private static final String CLASS = "HoloDeviceActivity"; + private static final String CLASS = "GenerateImagesActivity"; /** The command to launch the main activity. */ private static final String START_CMD = String.format( - "am start -W -a android.intent.action.MAIN -n %s/%s.%s", PACKAGE, PACKAGE, CLASS); + "am start -W -a android.intent.action.MAIN -n %s/%s.%s", APP_PACKAGE_NAME, + APP_PACKAGE_NAME, CLASS); - private static final String CLEAR_GENERATED_CMD = "rm -rf /sdcard/cts-holo-assets/*.png"; - - private static final String STOP_CMD = String.format("am force-stop %s", PACKAGE); - + private static final String CLEAR_GENERATED_CMD = "rm -rf %s/*.png"; + private static final String STOP_CMD = String.format("am force-stop %s", APP_PACKAGE_NAME); private static final String HARDWARE_TYPE_CMD = "dumpsys | grep android.hardware.type"; - private static final String DENSITY_PROP_DEVICE = "ro.sf.lcd_density"; - private static final String DENSITY_PROP_EMULATOR = "qemu.sf.lcd_density"; - // Intent extras - protected final static String INTENT_STRING_EXTRA = " --es %s %s"; - - protected final static String INTENT_BOOLEAN_EXTRA = " --ez %s %b"; - - protected final static String INTENT_INTEGER_EXTRA = " --ei %s %d"; - - // Intent extra keys - private static final String EXTRA_THEME = "holo_theme_extra"; - - private static final String[] THEMES = { - "holo", - "holo_dialog", - "holo_dialog_minwidth", - "holo_dialog_noactionbar", - "holo_dialog_noactionbar_minwidth", - "holo_dialogwhenlarge", - "holo_dialogwhenlarge_noactionbar", - "holo_inputmethod", - "holo_light", - "holo_light_darkactionbar", - "holo_light_dialog", - "holo_light_dialog_minwidth", - "holo_light_dialog_noactionbar", - "holo_light_dialog_noactionbar_minwidth", - "holo_light_dialogwhenlarge", - "holo_light_dialogwhenlarge_noactionbar", - "holo_light_noactionbar", - "holo_light_noactionbar_fullscreen", - "holo_light_panel", - "holo_noactionbar", - "holo_noactionbar_fullscreen", - "holo_panel", - "holo_wallpaper", - "holo_wallpaper_notitlebar", - }; - - private final int NUM_THEMES = THEMES.length; - - private static final String[] LAYOUTS = { - "button", - "button_pressed", - "checkbox", - "checkbox_checked", - "chronometer", - "color_blue_bright", - "color_blue_dark", - "color_blue_light", - "color_green_dark", - "color_green_light", - "color_orange_dark", - "color_orange_light", - "color_purple", - "color_red_dark", - "color_red_light", - "datepicker", - "display_info", - "edittext", - "progressbar_horizontal_0", - "progressbar_horizontal_100", - "progressbar_horizontal_50", - "progressbar_large", - "progressbar_small", - "progressbar", - "radiobutton_checked", - "radiobutton", - "radiogroup_horizontal", - "radiogroup_vertical", - "ratingbar_0", - "ratingbar_2point5", - "ratingbar_5", - "ratingbar_0_pressed", - "ratingbar_2point5_pressed", - "ratingbar_5_pressed", - "searchview_query", - "searchview_query_hint", - "seekbar_0", - "seekbar_100", - "seekbar_50", - "spinner", - "switch_button_checked", - "switch_button", - "textview", - "timepicker", - "togglebutton_checked", - "togglebutton", - "zoomcontrols", - }; - - private final int NUM_LAYOUTS = LAYOUTS.length; - - private final HashMap<String, File> mReferences = new HashMap<String, File>(); + private final HashMap<String, File> mReferences = new HashMap<>(); /** The ABI to use. */ private IAbi mAbi; @@ -197,32 +96,21 @@ @Override protected void setUp() throws Exception { super.setUp(); - // Get the device, this gives a handle to run commands and install APKs. + mDevice = getDevice(); - // Remove any previously installed versions of this APK. - mDevice.uninstallPackage(PACKAGE); + mDevice.uninstallPackage(APP_PACKAGE_NAME); + // Get the APK from the build. - File app = mBuild.getTestApp(APK); - // Get the ABI flag. - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - // Install the APK on the device. + final File app = mBuild.getTestApp(String.format("%s.apk", APK_NAME)); + final String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; + mDevice.installPackage(app, false, options); - // Remove previously generated images. - mDevice.executeShellCommand(CLEAR_GENERATED_CMD); - final String densityProp; - if (mDevice.getSerialNumber().startsWith("emulator-")) { - densityProp = DENSITY_PROP_EMULATOR; - } else { - densityProp = DENSITY_PROP_DEVICE; - } + final String density = getDensityBucketForDevice(mDevice); + final String zipFile = String.format("/%s.zip", density); + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Loading resources from " + zipFile); - final String zip = String.format("/%s.zip", - getDensityBucket(Integer.parseInt(mDevice.getProperty(densityProp)))); - Log.logAndDisplay(LogLevel.INFO, TAG, "Loading resources from " + zip); - - - final InputStream zipStream = this.getClass().getResourceAsStream(zip); + final InputStream zipStream = ThemeHostTest.class.getResourceAsStream(zipFile); if (zipStream != null) { final ZipInputStream in = new ZipInputStream(zipStream); try { @@ -232,21 +120,28 @@ final String name = ze.getName(); final File tmp = File.createTempFile("ref_" + name, ".png"); final FileOutputStream out = new FileOutputStream(tmp); + int count; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } + out.flush(); out.close(); mReferences.put(name, tmp); } + } catch (IOException e) { + Log.logAndDisplay(LogLevel.ERROR, LOG_TAG, "Failed to unzip assets: " + zipFile); } finally { in.close(); } + } else { + Log.logAndDisplay(LogLevel.ERROR, LOG_TAG, "Failed to get resource: " + zipFile); } - mExecutionService = Executors.newFixedThreadPool(2);// 2 worker threads - mCompletionService = new ExecutorCompletionService<Boolean>(mExecutionService); + final int numCores = Runtime.getRuntime().availableProcessors(); + mExecutionService = Executors.newFixedThreadPool(numCores * 2); + mCompletionService = new ExecutorCompletionService<>(mExecutionService); } @Override @@ -255,86 +150,148 @@ for (File ref : mReferences.values()) { ref.delete(); } + mExecutionService.shutdown(); + // Remove the APK. - mDevice.uninstallPackage(PACKAGE); + mDevice.uninstallPackage(APP_PACKAGE_NAME); + // Remove generated images. mDevice.executeShellCommand(CLEAR_GENERATED_CMD); + super.tearDown(); } @TimeoutReq(minutes = 60) - public void testHoloThemes() throws Exception { - if (checkHardwareTypeSkipTest( - mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) { - Log.logAndDisplay(LogLevel.INFO, TAG, "Skipped HoloThemes test for watch and TV"); + public void testThemes() throws Exception { + if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) { + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch"); return; } if (mReferences.isEmpty()) { - Log.logAndDisplay(LogLevel.INFO, TAG, - "Skipped HoloThemes test due to no reference images"); + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test due to no reference images"); return; } + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Generating device images..."); + + assertTrue("Aborted image generation", generateDeviceImages()); + + // Pull ZIP file from remote device. + final File localZip = File.createTempFile("generated", ".zip"); + mDevice.pullFile(GENERATED_ASSETS_ZIP, localZip); + int numTasks = 0; - for (int i = 0; i < NUM_THEMES; i++) { - final String themeName = THEMES[i]; - runCapture(i, themeName); - for (int j = 0; j < NUM_LAYOUTS; j++) { - final String name = String.format("%s_%s", themeName, LAYOUTS[j]); - final File ref = mReferences.get(name + ".png"); - if (!ref.exists()) { - Log.logAndDisplay(LogLevel.INFO, TAG, - "Skipping theme test due to missing reference for reference image " + - name); - continue; + + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Extracting generated images..."); + + // Extract generated images to temporary files. + final byte[] data = new byte[4096]; + final ZipInputStream zipInput = new ZipInputStream(new FileInputStream(localZip)); + ZipEntry entry; + while ((entry = zipInput.getNextEntry()) != null) { + final String name = entry.getName(); + final File expected = mReferences.get(name); + if (expected != null && expected.exists()) { + final File actual = File.createTempFile("actual_" + name, ".png"); + final FileOutputStream pngOutput = new FileOutputStream(actual); + + int count; + while ((count = zipInput.read(data, 0, data.length)) != -1) { + pngOutput.write(data, 0, count); } - mCompletionService.submit(new ComparisonTask(mDevice, ref, name)); + + pngOutput.flush(); + pngOutput.close(); + + mCompletionService.submit(new ComparisonTask(mDevice, expected, actual)); numTasks++; + } else { + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Missing reference image for " + name); } + + zipInput.closeEntry(); } + + zipInput.close(); + + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Waiting for comparison tasks..."); + int failures = 0; - for (int i = 0; i < numTasks; i++) { + for (int i = numTasks; i > 0; i--) { failures += mCompletionService.take().get() ? 0 : 1; } + assertTrue(failures + " failures in theme test", failures == 0); + + Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Finished!"); } - private void runCapture(int themeId, String themeName) throws Exception { - final StringBuilder sb = new StringBuilder(START_CMD); - sb.append(String.format(INTENT_INTEGER_EXTRA, EXTRA_THEME, themeId)); - final String startCommand = sb.toString(); + private boolean generateDeviceImages() throws Exception { // Clear logcat mDevice.executeAdbCommand("logcat", "-c"); + // Stop any existing instances mDevice.executeShellCommand(STOP_CMD); - // Start activity - mDevice.executeShellCommand(startCommand); + // Start activity + mDevice.executeShellCommand(START_CMD); + + Log.logAndDisplay(LogLevel.VERBOSE, LOG_TAG, "Starting image generation..."); + + boolean aborted = false; boolean waiting = true; do { // Dump logcat. final String logs = mDevice.executeAdbCommand( "logcat", "-v", "brief", "-d", CLASS + ":I", "*:S"); + // Search for string. final Scanner in = new Scanner(logs); while (in.hasNextLine()) { final String line = in.nextLine(); if (line.startsWith("I/" + CLASS)) { final String[] lineSplit = line.split(":"); - final String s = lineSplit[1].trim(); - final String themeNameGenerated = lineSplit[2].trim(); - if (s.equals("OKAY") && themeNameGenerated.equals(themeName)) { - waiting = false; + if (lineSplit.length >= 3) { + final String cmd = lineSplit[1].trim(); + final String arg = lineSplit[2].trim(); + switch (cmd) { + case "FAIL": + Log.logAndDisplay(LogLevel.WARN, LOG_TAG, line); + Log.logAndDisplay(LogLevel.WARN, LOG_TAG, "Aborting! Check host logs for details."); + aborted = true; + // fall-through + case "OKAY": + waiting = false; + break; + } } } } in.close(); - } while (waiting); + } while (waiting && !aborted); + + Log.logAndDisplay(LogLevel.VERBOSE, LOG_TAG, "Image generation completed!"); + + return !aborted; } - private static String getDensityBucket(int density) { + private static String getDensityBucketForDevice(ITestDevice device) { + final String densityProp; + if (device.getSerialNumber().startsWith("emulator-")) { + densityProp = DENSITY_PROP_EMULATOR; + } else { + densityProp = DENSITY_PROP_DEVICE; + } + + final int density; + try { + density = Integer.parseInt(device.getProperty(densityProp)); + } catch (DeviceNotAvailableException e) { + return "unknown"; + } + switch (density) { case 120: return "ldpi"; @@ -363,9 +320,7 @@ if (hardwareTypeString.contains("android.hardware.type.watch")) { return true; } - if (hardwareTypeString.contains("android.hardware.type.television")) { - return true; - } + return false; } }
diff --git a/hostsidetests/usage/Android.mk b/hostsidetests/usage/Android.mk new file mode 100644 index 0000000..1d4e36d --- /dev/null +++ b/hostsidetests/usage/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +# Must match the package name in CtsTestCaseList.mk +LOCAL_MODULE := CtsUsageHostTestCases + +LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed-prebuilt + +LOCAL_CTS_TEST_PACKAGE := android.host.app.usage + +include $(BUILD_CTS_HOST_JAVA_LIBRARY) + +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/usage/app/Android.mk b/hostsidetests/usage/app/Android.mk new file mode 100644 index 0000000..b23efbc --- /dev/null +++ b/hostsidetests/usage/app/Android.mk
@@ -0,0 +1,28 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# Don't include this package in any target. +LOCAL_MODULE_TAGS := tests + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_SDK_VERSION := current + +LOCAL_PACKAGE_NAME := CtsDeviceAppUsageTestApp + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/usage/app/AndroidManifest.xml b/hostsidetests/usage/app/AndroidManifest.xml new file mode 100755 index 0000000..bad453f --- /dev/null +++ b/hostsidetests/usage/app/AndroidManifest.xml
@@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.app.usage.test"> + + <application> + <activity android:name=".TestActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> +</manifest> +
diff --git a/hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java b/hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java new file mode 100644 index 0000000..9432477 --- /dev/null +++ b/hostsidetests/usage/app/src/com/android/cts/app/usage/test/TestActivity.java
@@ -0,0 +1,22 @@ +/* + * Copyright (C) 2015 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.app.usage.test; + +import android.app.Activity; + +public class TestActivity extends Activity { +} \ No newline at end of file
diff --git a/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java b/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java new file mode 100644 index 0000000..b94d086 --- /dev/null +++ b/hostsidetests/usage/src/com/android/cts/app/usage/AppIdleHostTest.java
@@ -0,0 +1,146 @@ +/* + * Copyright (C) 2015 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.app.usage; + +import com.android.cts.tradefed.build.CtsBuildHelper; +import com.android.tradefed.build.IBuildInfo; +import com.android.tradefed.device.DeviceNotAvailableException; +import com.android.tradefed.device.ITestDevice; +import com.android.tradefed.testtype.DeviceTestCase; +import com.android.tradefed.testtype.IBuildReceiver; + +public class AppIdleHostTest extends DeviceTestCase implements IBuildReceiver { + private static final String SETTINGS_APP_IDLE_CONSTANTS = "app_idle_constants"; + + private static final String TEST_APP_PACKAGE = "com.android.cts.app.usage.test"; + private static final String TEST_APP_APK = "CtsDeviceAppUsageTestApp.apk"; + private static final String TEST_APP_CLASS = "TestActivity"; + + private static final long ACTIVITY_LAUNCH_WAIT_MILLIS = 500; + + /** + * A reference to the build. + */ + private CtsBuildHelper mBuild; + + /** + * A reference to the device under test. + */ + private ITestDevice mDevice; + + @Override + public void setBuild(IBuildInfo buildInfo) { + // Get the build, this is used to access the APK. + mBuild = CtsBuildHelper.createBuildHelper(buildInfo); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + // Get the device, this gives a handle to run commands and install APKs. + mDevice = getDevice(); + + // Remove any previously installed versions of this APK. + mDevice.uninstallPackage(TEST_APP_PACKAGE); + + // Install the APK on the device. + mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), false); + } + + @Override + protected void tearDown() throws Exception { + // Remove the package once complete. + mDevice.uninstallPackage(TEST_APP_PACKAGE); + super.tearDown(); + } + + /** + * Checks whether an package is idle. + * @param appPackage The package to check for idleness. + * @return true if the package is idle + * @throws DeviceNotAvailableException + */ + private boolean isAppIdle(String appPackage) throws DeviceNotAvailableException { + String result = mDevice.executeShellCommand(String.format("am get-inactive %s", appPackage)); + return result.contains("Idle=true"); + } + + /** + * Set the app idle settings. + * @param settingsStr The settings string, a comma separated key=value list. + * @throws DeviceNotAvailableException + */ + private void setAppIdleSettings(String settingsStr) throws DeviceNotAvailableException { + mDevice.executeShellCommand(String.format("settings put global %s \"%s\"", + SETTINGS_APP_IDLE_CONSTANTS, settingsStr)); + } + + /** + * Get the current app idle settings. + * @throws DeviceNotAvailableException + */ + private String getAppIdleSettings() throws DeviceNotAvailableException { + String result = mDevice.executeShellCommand(String.format("settings get global %s", + SETTINGS_APP_IDLE_CONSTANTS)); + return result.trim(); + } + + /** + * Launch the test app for a few hundred milliseconds then launch home. + * @throws DeviceNotAvailableException + */ + private void startAndStopTestApp() throws DeviceNotAvailableException { + // Launch the app. + mDevice.executeShellCommand( + String.format("am start -W -a android.intent.action.MAIN -n %s/%s.%s", + TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_APP_CLASS)); + + // Wait for some time. + sleepUninterrupted(ACTIVITY_LAUNCH_WAIT_MILLIS); + + // Launch home. + mDevice.executeShellCommand( + "am start -W -a android.intent.action.MAIN -c android.intent.category.HOME"); + } + + /** + * Tests that the app is not idle right after it is launched. + */ + public void testAppIsNotIdleAfterBeingLaunched() throws Exception { + final String previousState = getAppIdleSettings(); + try { + // Set the app idle time to something large. + setAppIdleSettings("idle_duration=10000,wallclock_threshold=10000"); + startAndStopTestApp(); + assertFalse(isAppIdle(TEST_APP_PACKAGE)); + } finally { + setAppIdleSettings(previousState); + } + } + + private static void sleepUninterrupted(long timeMillis) { + boolean interrupted; + do { + try { + Thread.sleep(timeMillis); + interrupted = false; + } catch (InterruptedException e) { + interrupted = true; + } + } while (interrupted); + } +}
diff --git a/libs/commonutil/src/com/android/cts/util/ReportLog.java b/libs/commonutil/src/com/android/cts/util/ReportLog.java index 56b431a..dd4b414 100644 --- a/libs/commonutil/src/com/android/cts/util/ReportLog.java +++ b/libs/commonutil/src/com/android/cts/util/ReportLog.java
@@ -42,26 +42,55 @@ /** * print array of values to output log + * <p>Note: test identifier is inferred from call stack trace based on class and method name */ public void printArray(String message, double[] values, ResultType type, ResultUnit unit) { doPrintArray(message, values, type, unit); } /** + * print array of values to output log + */ + public void printArray(String testId, String message, + double[] values, ResultType type, ResultUnit unit) { + doPrintArray(testId, message, values, type, unit); + } + + /** * Print a value to output log + * <p>Note: test identifier is inferred from call stack trace based on class and method name */ public void printValue(String message, double value, ResultType type, ResultUnit unit) { double[] vals = { value }; doPrintArray(message, vals, type, unit); } + /** + * Print a value to output log + */ + public void printValue(String testId, String message, + double value, ResultType type, ResultUnit unit) { + double[] vals = { value }; + doPrintArray(testId, message, vals, type, unit); + } + private void doPrintArray(String message, double[] values, ResultType type, ResultUnit unit) { + doPrintArray(getClassMethodNames(mDepth + 1, true), message, values, type, unit); + } + + private void doPrintArray(String testId, String message, + double[] values, ResultType type, ResultUnit unit) { StringBuilder builder = new StringBuilder(); // note mDepth + 1 as this function will be called by printVaue or printArray // and we need caller of printValue / printArray - builder.append(getClassMethodNames(mDepth + 1, true) + LOG_ELEM_SEPARATOR + message + - LOG_ELEM_SEPARATOR + type.getXmlString() + LOG_ELEM_SEPARATOR + - unit.getXmlString() + LOG_ELEM_SEPARATOR); + builder.append(testId); + builder.append(LOG_ELEM_SEPARATOR); + builder.append(message); + builder.append(LOG_ELEM_SEPARATOR); + builder.append(type.getXmlString()); + builder.append(LOG_ELEM_SEPARATOR); + builder.append(unit.getXmlString()); + builder.append(LOG_ELEM_SEPARATOR); for (double v : values) { builder.append(v); builder.append(" ");
diff --git a/libs/deviceutil/src/android/cts/util/LocationUtils.java b/libs/deviceutil/src/android/cts/util/LocationUtils.java new file mode 100644 index 0000000..1f7af86 --- /dev/null +++ b/libs/deviceutil/src/android/cts/util/LocationUtils.java
@@ -0,0 +1,40 @@ +/* + * Copyright (C) 2015 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 android.cts.util; + +import android.app.Instrumentation; +import android.util.Log; + +import java.io.IOException; + +public class LocationUtils { + private static String TAG = "LocationUtils"; + + public static void registerMockLocationProvider(Instrumentation instrumentation, + boolean enable) { + StringBuilder command = new StringBuilder(); + command.append("appops set "); + command.append(instrumentation.getContext().getPackageName()); + command.append(" android:mock_location "); + command.append(enable ? "allow" : "deny"); + try { + SystemUtil.runShellCommand(instrumentation, command.toString()); + } catch (IOException e) { + Log.e(TAG, "Error managing mock location app. Command: " + command, e); + } + } +}
diff --git a/libs/deviceutil/src/android/cts/util/MediaUtils.java b/libs/deviceutil/src/android/cts/util/MediaUtils.java index 2ae7b13..b3ebbad 100755 --- a/libs/deviceutil/src/android/cts/util/MediaUtils.java +++ b/libs/deviceutil/src/android/cts/util/MediaUtils.java
@@ -19,13 +19,22 @@ import android.content.res.AssetFileDescriptor; import android.media.MediaCodec; import android.media.MediaCodecInfo; +import android.media.MediaCodecInfo.CodecCapabilities; +import android.media.MediaCodecInfo.VideoCapabilities; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.net.Uri; +import android.util.Range; + +import com.android.cts.util.ReportLog; +import com.android.cts.util.ResultType; +import com.android.cts.util.ResultUnit; + import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; +import java.util.Arrays; import java.util.Map; import android.util.Log; @@ -159,6 +168,40 @@ return true; } + public static boolean supports(String codecName, String mime, int w, int h) { + MediaCodec codec; + try { + codec = MediaCodec.createByCodecName(codecName); + } catch (IOException e) { + return false; + } + + CodecCapabilities cap = null; + try { + cap = codec.getCodecInfo().getCapabilitiesForType(mime); + } catch (IllegalArgumentException e) { + Log.w(TAG, "not supported mime: " + mime); + codec.release(); + return false; + } + + VideoCapabilities vidCap = cap.getVideoCapabilities(); + if (vidCap == null) { + Log.w(TAG, "not a video codec: " + codecName); + codec.release(); + return false; + } + try { + Range<Double> fps = vidCap.getSupportedFrameRatesFor(w, h); + } catch (IllegalArgumentException e) { + Log.w(TAG, "unsupported size " + w + "x" + h); + codec.release(); + return false; + } + codec.release(); + return true; + } + public static boolean hasCodecForTrack(MediaExtractor ex, int track) { int count = ex.getTrackCount(); if (track < 0 || track >= count) { @@ -294,6 +337,27 @@ return check(hasCodecsForPath(context, path), "no decoder found"); } + public static boolean hasCodecForDomain(boolean encoder, String domain) { + for (MediaCodecInfo info : sMCL.getCodecInfos()) { + if (encoder != info.isEncoder()) { + continue; + } + + for (String type : info.getSupportedTypes()) { + if (type.toLowerCase().startsWith(domain.toLowerCase() + "/")) { + Log.i(TAG, "found codec " + info.getName() + " for mime " + type); + return true; + } + } + } + return false; + } + + public static boolean checkCodecForDomain(boolean encoder, String domain) { + return check(hasCodecForDomain(encoder, domain), + "no " + domain + (encoder ? " encoder" : " decoder") + " found"); + } + private static boolean hasCodecForMime(boolean encoder, String mime) { for (MediaCodecInfo info : sMCL.getCodecInfos()) { if (encoder != info.isEncoder()) { @@ -346,4 +410,152 @@ public static boolean checkDecoderForFormat(MediaFormat format) { return check(canDecode(format), "no decoder for " + format); } + + public static MediaExtractor createMediaExtractorForMimeType( + Context context, int resourceId, String mimeTypePrefix) + throws IOException { + MediaExtractor extractor = new MediaExtractor(); + AssetFileDescriptor afd = context.getResources().openRawResourceFd(resourceId); + try { + extractor.setDataSource( + afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); + } finally { + afd.close(); + } + int trackIndex; + for (trackIndex = 0; trackIndex < extractor.getTrackCount(); trackIndex++) { + MediaFormat trackMediaFormat = extractor.getTrackFormat(trackIndex); + if (trackMediaFormat.getString(MediaFormat.KEY_MIME).startsWith(mimeTypePrefix)) { + extractor.selectTrack(trackIndex); + break; + } + } + if (trackIndex == extractor.getTrackCount()) { + extractor.release(); + throw new IllegalStateException("couldn't get a track for " + mimeTypePrefix); + } + + return extractor; + } + + /** + * return the average value of the passed array. + */ + public static double getAverage(double[] data) { + int num = data.length; + if (num == 0) { + return 0; + } + + double sum = data[0]; + for (int i = 1; i < num; i++) { + sum += data[i]; + } + return sum / num; + } + + /** + * return the standard deviation value of the passed array + */ + public static double getStdev(double[] data) { + double average = getAverage(data); + int num = data.length; + if (num == 0) { + return 0; + } + double variance = 0; + for (int i = 0; i < num; ++i) { + variance += (data[i] - average) * (data[i] - average); + } + variance /= num; + return Math.sqrt(variance); + } + + public static double[] calculateMovingAverage(double[] array, int n) { + int num = array.length; + if (num < n) { + return null; + } + int avgsNum = num - n + 1; + double[] avgs = new double[avgsNum]; + double sum = array[0]; + for (int i = 1; i < n; ++i) { + sum += array[i]; + } + avgs[0] = sum / n; + + for (int i = n; i < num; ++i) { + sum = sum - array[i - n] + array[i]; + avgs[i - n + 1] = sum / n; + } + return avgs; + } + + public static String logResults(ReportLog log, String prefix, + double min, double max, double avg, double stdev) { + String msg = prefix; + msg += " min=" + Math.round(min / 1000) + " max=" + Math.round(max / 1000) + + " avg=" + Math.round(avg / 1000) + " stdev=" + Math.round(stdev / 1000); + log.printValue(msg, 1000000000 / min, ResultType.HIGHER_BETTER, ResultUnit.FPS); + return msg; + } + + public static VideoCapabilities getVideoCapabilities(String codecName, String mime) { + for (MediaCodecInfo info : sMCL.getCodecInfos()) { + if (!info.getName().equalsIgnoreCase(codecName)) { + continue; + } + CodecCapabilities caps; + try { + caps = info.getCapabilitiesForType(mime); + } catch (IllegalArgumentException e) { + // mime is not supported + continue; + } + return caps.getVideoCapabilities(); + } + return null; + } + + public static Range<Double> getAchievableFrameRatesFor( + String codecName, String mimeType, int width, int height) { + VideoCapabilities cap = getVideoCapabilities(codecName, mimeType); + if (cap == null) { + return null; + } + return cap.getAchievableFrameRatesFor(width, height); + } + + private static final double FRAMERATE_TOLERANCE = Math.sqrt(12.1); + public static boolean verifyResults(String name, String mime, int w, int h, double measured) { + Range<Double> reported = getAchievableFrameRatesFor(name, mime, w, h); + if (reported == null) { + Log.d(TAG, "Failed to getAchievableFrameRatesFor " + + name + " " + mime + " " + w + "x" + h); + return false; + } + double lowerBoundary1 = reported.getLower() / FRAMERATE_TOLERANCE; + double upperBoundary1 = reported.getUpper() * FRAMERATE_TOLERANCE; + double lowerBoundary2 = reported.getUpper() / Math.pow(FRAMERATE_TOLERANCE, 2); + double upperBoundary2 = reported.getLower() * Math.pow(FRAMERATE_TOLERANCE, 2); + Log.d(TAG, name + " " + mime + " " + w + "x" + h + " " + + "lowerBoundary1 " + lowerBoundary1 + " upperBoundary1 " + upperBoundary1 + + " lowerBoundary2 " + lowerBoundary2 + " upperBoundary2 " + upperBoundary2 + + " measured " + measured); + return (measured >= lowerBoundary1 && measured <= upperBoundary1 && + measured >= lowerBoundary2 && measured <= upperBoundary2); + } + + public static String getErrorMessage( + Range<Double> reportedRange, double[] measuredFps, String[] rawData) { + String msg = ""; + if (reportedRange == null) { + msg += "Failed to get achievable frame rate.\n"; + } else { + msg += "Expected achievable frame rate range: " + reportedRange + ".\n"; + } + msg += "Measured frame rate: " + Arrays.toString(measuredFps) + ".\n"; + msg += "Raw data: " + Arrays.toString(rawData) + ".\n"; + return msg; + } }
diff --git a/libs/deviceutil/src/android/cts/util/SystemUtil.java b/libs/deviceutil/src/android/cts/util/SystemUtil.java index e6222cb..6e7fd38 100644 --- a/libs/deviceutil/src/android/cts/util/SystemUtil.java +++ b/libs/deviceutil/src/android/cts/util/SystemUtil.java
@@ -18,9 +18,14 @@ import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; +import android.app.Instrumentation; import android.content.Context; +import android.os.ParcelFileDescriptor; import android.os.StatFs; +import java.io.FileInputStream; +import java.io.IOException; + public class SystemUtil { public static long getFreeDiskSize(Context context) { StatFs statFs = new StatFs(context.getFilesDir().getAbsolutePath()); @@ -40,4 +45,28 @@ activityManager.getMemoryInfo(info); return info.totalMem; // TODO totalMem N/A in ICS. } + + /** + * Executes a shell command using shell user identity, and return the standard output in string + * <p>Note: calling this function requires API level 21 or above + * @param instrumentation {@link Instrumentation} instance, obtained from a test running in + * instrumentation framework + * @param cmd the command to run + * @return the standard output of the command + * @throws Exception + */ + public static String runShellCommand(Instrumentation instrumentation, String cmd) + throws IOException { + ParcelFileDescriptor pfd = instrumentation.getUiAutomation().executeShellCommand(cmd); + byte[] buf = new byte[512]; + int bytesRead; + FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd); + StringBuffer stdout = new StringBuffer(); + while ((bytesRead = fis.read(buf)) != -1) { + stdout.append(new String(buf, 0, bytesRead)); + } + fis.close(); + return stdout.toString(); + } + }
diff --git a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java index b9d3af1..2933b0b 100644 --- a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java +++ b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
@@ -21,6 +21,7 @@ import android.graphics.Bitmap; import android.graphics.Picture; import android.graphics.Rect; +import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.os.Message; @@ -36,9 +37,12 @@ import android.webkit.ValueCallback; import android.webkit.WebBackForwardList; import android.webkit.WebChromeClient; +import android.webkit.WebMessage; +import android.webkit.WebMessagePort; import android.webkit.WebSettings; import android.webkit.WebView.HitTestResult; import android.webkit.WebView.PictureListener; +import android.webkit.WebView.VisualStateCallback; import android.webkit.WebView; import android.webkit.WebViewClient; @@ -306,6 +310,24 @@ }); } + public WebMessagePort[] createWebMessageChannel() { + return getValue(new ValueGetter<WebMessagePort[]>() { + @Override + public WebMessagePort[] capture() { + return mWebView.createWebMessageChannel(); + } + }); + } + + public void postWebMessage(final WebMessage message, final Uri targetOrigin) { + runOnUiThread(new Runnable() { + @Override + public void run() { + mWebView.postWebMessage(message, targetOrigin); + } + }); + } + public void addJavascriptInterface(final Object object, final String name) { runOnUiThread(new Runnable() { @Override @@ -628,6 +650,15 @@ }); } + public void postVisualStateCallback(final long requestId, final VisualStateCallback callback) { + runOnUiThread(new Runnable() { + @Override + public void run() { + mWebView.postVisualStateCallback(requestId, callback); + } + }); + } + public int[] getLocationOnScreen() { final int[] location = new int[2]; return getValue(new ValueGetter<int[]>() {
diff --git a/libs/testserver/Android.mk b/libs/testserver/Android.mk index dfe357b..488af53 100644 --- a/libs/testserver/Android.mk +++ b/libs/testserver/Android.mk
@@ -22,4 +22,6 @@ LOCAL_MODULE := ctstestserver +LOCAL_SDK_VERSION := 16 + include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/libs/testserver/src/android/webkit/cts/CtsTestServer.java b/libs/testserver/src/android/webkit/cts/CtsTestServer.java index 22cbb7b..de88f3b 100644 --- a/libs/testserver/src/android/webkit/cts/CtsTestServer.java +++ b/libs/testserver/src/android/webkit/cts/CtsTestServer.java
@@ -15,7 +15,6 @@ */ package android.webkit.cts; -import libcore.io.Base64; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; @@ -44,6 +43,7 @@ import android.content.res.Resources; import android.net.Uri; import android.os.Environment; +import android.util.Base64; import android.util.Log; import android.webkit.MimeTypeMap; @@ -229,12 +229,30 @@ // request for shutdown and having the server's one thread // sequentially call accept() and close(). URL url = new URL(mServerUri + SHUTDOWN_PREFIX); - URLConnection connection = openConnection(url); - connection.connect(); + if (url.getProtocol().equalsIgnoreCase("http")) { + // Use Socket instead of HttpURLConnection when the server is in cleartext HTTP mode + // to avoid the request being blocked by NetworkSecurityPolicy. + Socket socket = null; + try { + socket = new Socket(url.getHost(), url.getPort()); + socket.getOutputStream().write( + ("GET " + SHUTDOWN_PREFIX + " HTTP/1.0\r\n\r\n").getBytes("US-ASCII")); + socket.getOutputStream().flush(); + } finally { + if (socket != null) { + try { + socket.close(); + } catch (Exception ignored) {} + } + } + } else { + URLConnection connection = openConnection(url); + connection.connect(); - // Read the input from the stream to send the request. - InputStream is = connection.getInputStream(); - is.close(); + // Read the input from the stream to send the request. + InputStream is = connection.getInputStream(); + is.close(); + } // Block until the server thread is done shutting down. mServerThread.join(); @@ -947,7 +965,7 @@ * for the result. */ private static KeyManager[] getKeyManagers() throws Exception { - byte[] bytes = Base64.decode(SERVER_KEYS_BKS.getBytes()); + byte[] bytes = Base64.decode(SERVER_KEYS_BKS.getBytes(), Base64.DEFAULT); InputStream inputStream = new ByteArrayInputStream(bytes); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); @@ -1014,7 +1032,7 @@ conn.receiveRequestEntity( (HttpEntityEnclosingRequest) request); } - mExecutorService.submit(new HandleResponseTask(conn, request)); + mExecutorService.execute(new HandleResponseTask(conn, request)); } catch (IOException e) { // normal during shutdown, ignore Log.w(TAG, e); @@ -1045,7 +1063,7 @@ return path.equals(SHUTDOWN_PREFIX); } - private class HandleResponseTask implements Callable<Void> { + private class HandleResponseTask implements Runnable { private DefaultHttpServerConnection mConnection; @@ -1058,12 +1076,15 @@ } @Override - public Void call() throws Exception { - HttpResponse response = mServer.getResponse(mRequest); - mConnection.sendResponseHeader(response); - mConnection.sendResponseEntity(response); - mConnection.close(); - return null; + public void run() { + try { + HttpResponse response = mServer.getResponse(mRequest); + mConnection.sendResponseHeader(response); + mConnection.sendResponseEntity(response); + mConnection.close(); + } catch (Exception e) { + Log.e(TAG, "Error handling request:", e); + } } } }
diff --git a/libs/vogar-expect/src/vogar/Expectation.java b/libs/vogar-expect/src/vogar/Expectation.java index f065f42..ddbc233 100644 --- a/libs/vogar-expect/src/vogar/Expectation.java +++ b/libs/vogar-expect/src/vogar/Expectation.java
@@ -16,7 +16,6 @@ package vogar; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; @@ -37,14 +36,6 @@ */ public final class Expectation { - /** The pattern to use when no expected output is specified */ - public static final Pattern MATCH_ALL_PATTERN - = Pattern.compile(".*", Pattern.MULTILINE | Pattern.DOTALL); - - /** The expectation of a general successful run. */ - public static final Expectation SUCCESS = new Expectation(Result.SUCCESS, MATCH_ALL_PATTERN, - Collections.<String>emptySet(), "", -1); - /** Justification for this expectation */ private final String description;
diff --git a/libs/vogar-expect/src/vogar/ExpectationStore.java b/libs/vogar-expect/src/vogar/ExpectationStore.java index cfa20e9..090322d 100644 --- a/libs/vogar-expect/src/vogar/ExpectationStore.java +++ b/libs/vogar-expect/src/vogar/ExpectationStore.java
@@ -26,6 +26,7 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -50,7 +51,17 @@ * expectation, the outcome expectation will be returned. */ public final class ExpectationStore { + + /** The pattern to use when no expected output is specified */ + private static final Pattern MATCH_ALL_PATTERN + = Pattern.compile(".*", Pattern.MULTILINE | Pattern.DOTALL); + + /** The expectation of a general successful run. */ + private static final Expectation SUCCESS = new Expectation(Result.SUCCESS, MATCH_ALL_PATTERN, + Collections.<String>emptySet(), "", -1); + private static final int PATTERN_FLAGS = Pattern.MULTILINE | Pattern.DOTALL; + private final Map<String, Expectation> outcomes = new LinkedHashMap<String, Expectation>(); private final Map<String, Expectation> failures = new LinkedHashMap<String, Expectation>(); @@ -62,7 +73,7 @@ */ public Expectation get(String name) { Expectation byName = getByNameOrPackage(name); - return byName != null ? byName : Expectation.SUCCESS; + return byName != null ? byName : SUCCESS; } /** @@ -87,7 +98,7 @@ } Expectation byName = getByNameOrPackage(outcome.getName()); - return byName != null ? byName : Expectation.SUCCESS; + return byName != null ? byName : SUCCESS; } private Expectation getByNameOrPackage(String name) { @@ -141,8 +152,8 @@ private void readExpectation(JsonReader reader, ModeId mode) throws IOException { boolean isFailure = false; - Result result = Result.SUCCESS; - Pattern pattern = Expectation.MATCH_ALL_PATTERN; + Result result = Result.EXEC_FAILED; + Pattern pattern = MATCH_ALL_PATTERN; Set<String> names = new LinkedHashSet<String>(); Set<String> tags = new LinkedHashSet<String>(); Set<ModeId> modes = null; @@ -159,6 +170,12 @@ } else if (name.equals("names")) { readStrings(reader, names); } else if (name.equals("failure")) { + // isFailure is somewhat arbitrarily keyed on the existence of a "failure" + // element instead of looking at the "result" field. There are only about 5 + // expectations in our entire expectation store that have this tag. + // + // TODO: Get rid of it and the "failures" map and just use the outcomes + // map for everything. Both uses seem useless. isFailure = true; names.add(reader.nextString()); } else if (name.equals("pattern")) {
diff --git a/suite/cts/deviceTests/jank2/Android.mk b/suite/cts/deviceTests/jank2/Android.mk new file mode 100644 index 0000000..346297e --- /dev/null +++ b/suite/cts/deviceTests/jank2/Android.mk
@@ -0,0 +1,29 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsJankTestCases + +LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner ub-uiautomator ub-janktesthelper + +include $(BUILD_CTS_PACKAGE)
diff --git a/suite/cts/deviceTests/jank2/AndroidManifest.xml b/suite/cts/deviceTests/jank2/AndroidManifest.xml new file mode 100644 index 0000000..a4c8337 --- /dev/null +++ b/suite/cts/deviceTests/jank2/AndroidManifest.xml
@@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.cts.jank"> + + <application> + <uses-library android:name="android.test.runner"/> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.cts.jank" + android:label="Jank tests"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> + +</manifest>
diff --git a/suite/cts/deviceTests/jank2/AndroidTest.xml b/suite/cts/deviceTests/jank2/AndroidTest.xml new file mode 100644 index 0000000..2fbbac7 --- /dev/null +++ b/suite/cts/deviceTests/jank2/AndroidTest.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="CTS Jank test config"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsDeviceUi.apk" /> +</configuration>
diff --git a/suite/cts/deviceTests/jank2/src/android/cts/jank/CtsJankTestBase.java b/suite/cts/deviceTests/jank2/src/android/cts/jank/CtsJankTestBase.java new file mode 100644 index 0000000..cb5c122 --- /dev/null +++ b/suite/cts/deviceTests/jank2/src/android/cts/jank/CtsJankTestBase.java
@@ -0,0 +1,70 @@ +/* + * Copyright (C) 2015 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 android.cts.jank; + +import android.cts.util.DeviceReportLog; +import android.os.Bundle; +import android.support.test.jank.JankTestBase; +import android.support.test.jank.WindowContentFrameStatsMonitor; +import android.support.test.uiautomator.UiDevice; + +import com.android.cts.util.ResultType; +import com.android.cts.util.ResultUnit; + +public abstract class CtsJankTestBase extends JankTestBase { + + private UiDevice mDevice; + private DeviceReportLog mLog; + + @Override + public void afterTest(Bundle metrics) { + String source = String.format("%s#%s", getClass().getCanonicalName(), getName()); + mLog.printValue(source, WindowContentFrameStatsMonitor.KEY_AVG_FPS, + metrics.getDouble(WindowContentFrameStatsMonitor.KEY_AVG_FPS), + ResultType.HIGHER_BETTER, ResultUnit.FPS); + mLog.printValue(source, WindowContentFrameStatsMonitor.KEY_AVG_LONGEST_FRAME, + metrics.getDouble(WindowContentFrameStatsMonitor.KEY_AVG_LONGEST_FRAME), + ResultType.LOWER_BETTER, ResultUnit.MS); + mLog.printValue(source, WindowContentFrameStatsMonitor.KEY_MAX_NUM_JANKY, + metrics.getInt(WindowContentFrameStatsMonitor.KEY_MAX_NUM_JANKY), + ResultType.LOWER_BETTER, ResultUnit.COUNT); + mLog.printSummary(WindowContentFrameStatsMonitor.KEY_AVG_NUM_JANKY, + metrics.getDouble(WindowContentFrameStatsMonitor.KEY_AVG_NUM_JANKY), + ResultType.LOWER_BETTER, ResultUnit.COUNT); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mLog = new DeviceReportLog(); + // fix device orientation + mDevice = UiDevice.getInstance(getInstrumentation()); + mDevice.setOrientationNatural(); + } + + @Override + protected void tearDown() throws Exception { + mLog.deliverReportToHost(getInstrumentation()); + // restore device orientation + mDevice.unfreezeRotation(); + super.tearDown(); + } + + protected UiDevice getUiDevice() { + return mDevice; + } +}
diff --git a/suite/cts/deviceTests/jank2/src/android/cts/jank/ui/CtsDeviceJankUi.java b/suite/cts/deviceTests/jank2/src/android/cts/jank/ui/CtsDeviceJankUi.java new file mode 100644 index 0000000..884f83c --- /dev/null +++ b/suite/cts/deviceTests/jank2/src/android/cts/jank/ui/CtsDeviceJankUi.java
@@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.ui; + +import android.content.ComponentName; +import android.content.Intent; +import android.cts.jank.CtsJankTestBase; +import android.os.SystemClock; +import android.support.test.jank.JankTest; +import android.support.test.jank.WindowContentFrameStatsMonitor; +import android.support.test.uiautomator.By; +import android.support.test.uiautomator.Direction; +import android.support.test.uiautomator.Until; +import android.widget.ListView; + +import java.io.IOException; + +public class CtsDeviceJankUi extends CtsJankTestBase { + private final static int NUM_ELEMENTS = 1000; + private static final long DEFAULT_ANIMATION_TIME = 2 * 1000; + private static final long POST_SCROLL_IDLE_TIME = 2 *1000; + private final static String PACKAGE = "com.android.cts.ui"; + private final static String CLASS = PACKAGE + ".ScrollingActivity"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + // launch the activity as part of the set up + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setComponent(new ComponentName(PACKAGE, CLASS)); + intent.putExtra("num_elements", NUM_ELEMENTS); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getInstrumentation().getTargetContext().startActivity(intent); + getUiDevice().wait(Until.hasObject(By.pkg(PACKAGE)), DEFAULT_ANIMATION_TIME); + } + + @Override + protected void tearDown() throws Exception { + getUiDevice().pressHome(); + super.tearDown(); + } + + @JankTest(expectedFrames=50, defaultIterationCount=5) + @WindowContentFrameStatsMonitor + public void testScrolling() throws IOException { + getUiDevice().findObject(By.clazz(ListView.class)).fling(Direction.DOWN); + SystemClock.sleep(POST_SCROLL_IDLE_TIME); + } +}
diff --git a/suite/cts/deviceTests/opengl/jni/graphics/Renderer.cpp b/suite/cts/deviceTests/opengl/jni/graphics/Renderer.cpp index b8e2acf..16504fd 100644 --- a/suite/cts/deviceTests/opengl/jni/graphics/Renderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/graphics/Renderer.cpp
@@ -22,6 +22,14 @@ // Used to center the grid on the screen. #define CENTER_GRID(x) ((((x) * 2.0 + 1) - OFFSCREEN_GRID_SIZE) / OFFSCREEN_GRID_SIZE) +// Leave a good error message if something fails. +#define EGL_RESULT_CHECK(X) do { \ + EGLint error = eglGetError(); \ + if (!(X) || error != EGL_SUCCESS) { \ + ALOGE("EGL error '%d' at %s:%d", error, __FILE__, __LINE__);\ + return false; \ + } \ + } while (0) static const int FBO_NUM_VERTICES = 6; @@ -66,7 +74,7 @@ EGL_NONE }; static const EGLint configAttribs[] = { - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, @@ -78,53 +86,60 @@ static const int FBO_SIZE = 128; -Renderer::Renderer(ANativeWindow* window, bool offscreen, int workload) : - mOffscreen(offscreen), mWindow(window), mEglDisplay(EGL_NO_DISPLAY), - mEglSurface(EGL_NO_SURFACE), mEglContext(EGL_NO_CONTEXT), mWorkload(workload) { +Renderer::Renderer(EGLNativeWindowType window, bool offscreen) : + mOffscreen(offscreen), mEglDisplay(EGL_NO_DISPLAY), mEglSurface(EGL_NO_SURFACE), + mEglContext(EGL_NO_CONTEXT), mWindow(window) { } -bool Renderer::setUp() { +bool Renderer::eglSetUp() { SCOPED_TRACE(); mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); - if (EGL_NO_DISPLAY == mEglDisplay || EGL_SUCCESS != eglGetError()) { - return false; - } + EGL_RESULT_CHECK(mEglDisplay != EGL_NO_DISPLAY); EGLint major; EGLint minor; - if (!eglInitialize(mEglDisplay, &major, &minor) || EGL_SUCCESS != eglGetError()) { - return false; - } + EGL_RESULT_CHECK(eglInitialize(mEglDisplay, &major, &minor)); EGLint numConfigs = 0; - if (!eglChooseConfig(mEglDisplay, configAttribs, &mGlConfig, 1, &numConfigs) - || EGL_SUCCESS != eglGetError()) { - return false; - } + EGL_RESULT_CHECK(eglChooseConfig(mEglDisplay, configAttribs, &mGlConfig, 1, &numConfigs) + && (numConfigs > 0)); mEglSurface = eglCreateWindowSurface(mEglDisplay, mGlConfig, mWindow, NULL); - if (EGL_NO_SURFACE == mEglSurface || EGL_SUCCESS != eglGetError()) { - return false; - } + EGL_RESULT_CHECK(mEglSurface != EGL_NO_SURFACE); mEglContext = eglCreateContext(mEglDisplay, mGlConfig, EGL_NO_CONTEXT, contextAttribs); - if (EGL_NO_CONTEXT == mEglContext || EGL_SUCCESS != eglGetError()) { - return false; + EGL_RESULT_CHECK(mEglContext != EGL_NO_CONTEXT); + + EGL_RESULT_CHECK(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)); + EGL_RESULT_CHECK(eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &mWidth)); + EGL_RESULT_CHECK(eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &mHeight)); + + return true; +} + +void Renderer::eglTearDown() { + SCOPED_TRACE(); + eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + + if (mEglContext != EGL_NO_CONTEXT) { + eglDestroyContext(mEglDisplay, mEglContext); + mEglContext = EGL_NO_CONTEXT; } - if (!eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) - || EGL_SUCCESS != eglGetError()) { - return false; + if (mEglSurface != EGL_NO_SURFACE) { + mEglSurface = EGL_NO_SURFACE; } - if (!eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &mWidth) - || EGL_SUCCESS != eglGetError()) { - return false; + if (mEglDisplay != EGL_NO_DISPLAY) { + eglTerminate(mEglDisplay); + mEglDisplay = EGL_NO_DISPLAY; } - if (!eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &mHeight) - || EGL_SUCCESS != eglGetError()) { - return false; - } +} + +bool Renderer::setUp(int /*workload*/) { + SCOPED_TRACE(); + + EGL_RESULT_CHECK(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)); if (mOffscreen) { mFboWidth = FBO_SIZE; @@ -178,6 +193,7 @@ ALOGE("GLError %d in setUp", err); return false; } + return true; } @@ -202,29 +218,14 @@ ALOGE("GLError %d in tearDown", err); return false; } - if (mEglContext != EGL_NO_CONTEXT) { - eglDestroyContext(mEglDisplay, mEglContext); - mEglContext = EGL_NO_CONTEXT; - } - if (mEglSurface != EGL_NO_SURFACE) { - eglDestroySurface(mEglDisplay, mEglSurface); - mEglSurface = EGL_NO_SURFACE; - } - if (mEglDisplay != EGL_NO_DISPLAY) { - eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglTerminate(mEglDisplay); - mEglDisplay = EGL_NO_DISPLAY; - } - return EGL_SUCCESS == eglGetError(); + return true; } bool Renderer::draw() { SCOPED_TRACE(); - if (!eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext) - || EGL_SUCCESS != eglGetError()) { - return false; - } + + EGL_RESULT_CHECK(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, mWidth, mHeight); @@ -287,5 +288,6 @@ return false; } - return eglSwapBuffers(mEglDisplay, mEglSurface); + EGL_RESULT_CHECK(eglSwapBuffers(mEglDisplay, mEglSurface)); + return true; }
diff --git a/suite/cts/deviceTests/opengl/jni/graphics/Renderer.h b/suite/cts/deviceTests/opengl/jni/graphics/Renderer.h index caa1634..3c62a26 100644 --- a/suite/cts/deviceTests/opengl/jni/graphics/Renderer.h +++ b/suite/cts/deviceTests/opengl/jni/graphics/Renderer.h
@@ -14,17 +14,18 @@ #ifndef RENDERER_H #define RENDERER_H -#include <android/native_window.h> - #include <EGL/egl.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> class Renderer { public: - Renderer(ANativeWindow* window, bool offscreen, int workload); - virtual bool setUp(); + Renderer(EGLNativeWindowType window, bool offscreen); + virtual bool setUp(int workload); virtual bool tearDown(); + bool eglSetUp(); + void eglTearDown(); + bool draw(); virtual void drawWorkload() = 0; virtual ~Renderer() {}; @@ -32,7 +33,6 @@ static const int OFFSCREEN_GRID_SIZE = 10; bool mOffscreen; protected: - ANativeWindow* mWindow; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLContext mEglContext; @@ -40,7 +40,6 @@ GLuint mProgramId; EGLint mWidth; EGLint mHeight; - int mWorkload; int mFboWidth;// Frame buffer width int mFboHeight;// Frame buffer height GLuint mFboId;// Frame buffer id @@ -52,5 +51,7 @@ GLuint mFboYOffsetUniformHandle;// Frame buffer y offset uniform handle GLuint mFboPositionHandle;// Frame buffer position handle GLuint mFboTexCoordHandle;// Frame buffer texture coordinate handle +private: + EGLNativeWindowType mWindow; }; #endif
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/GLPrimitive.cpp b/suite/cts/deviceTests/opengl/jni/primitive/GLPrimitive.cpp index 9d39af9..856da1e 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/GLPrimitive.cpp +++ b/suite/cts/deviceTests/opengl/jni/primitive/GLPrimitive.cpp
@@ -28,16 +28,24 @@ // Holds the current benchmark's renderer. Renderer* gRenderer = NULL; +ANativeWindow* gNativeWindow = NULL; + +enum { + FULL_PIPELINE_BENCHMARK = 0, + PIXEL_OUTPUT_BENCHMARK = 1, + SHADER_PERF_BENCHMARK = 2, + CONTEXT_SWITCH_BENCHMARK = 3 +}; extern "C" JNIEXPORT jboolean JNICALL Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_startBenchmark( - JNIEnv* env, jclass clazz, jint numFrames, jdoubleArray frameTimes) { + JNIEnv* env, jclass /*clazz*/, jint workload, jint numFrames, jdoubleArray frameTimes) { if (gRenderer == NULL) { return false; } // Sets up the renderer. - bool success = gRenderer->setUp(); + bool success = gRenderer->setUp(workload); // Records the start time. double start = GLUtils::currentTimeMillis(); @@ -60,41 +68,56 @@ double times[] = {start, end}; env->SetDoubleArrayRegion(frameTimes, 0, 2, times); - // Tears down and deletes the renderer. success = gRenderer->tearDown() && success; - delete gRenderer; - gRenderer = NULL; return success; } // The following functions create the renderers for the various benchmarks. extern "C" JNIEXPORT void JNICALL -Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_setupFullPipelineBenchmark( - JNIEnv* env, jclass clazz, jobject surface, jboolean offscreen, jint workload) { - gRenderer = new FullPipelineRenderer( - ANativeWindow_fromSurface(env, surface), offscreen, workload); -} - -extern "C" JNIEXPORT void JNICALL -Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_setupPixelOutputBenchmark( - JNIEnv* env, jclass clazz, jobject surface, jboolean offscreen, jint workload) { - gRenderer = new PixelOutputRenderer( - ANativeWindow_fromSurface(env, surface), offscreen, workload); -} - -extern "C" JNIEXPORT void JNICALL -Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_setupShaderPerfBenchmark( - JNIEnv* env, jclass clazz, jobject surface, jboolean offscreen, jint workload) { - gRenderer = new ShaderPerfRenderer( - ANativeWindow_fromSurface(env, surface), offscreen, workload); -} - -extern "C" JNIEXPORT void JNICALL -Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_setupContextSwitchBenchmark( - JNIEnv* env, jclass clazz, jobject surface, jboolean offscreen, jint workload) { - if (workload <= 8) { - // This test uses 8 iterations, so workload can't be more than 8. - gRenderer = new ContextSwitchRenderer( - ANativeWindow_fromSurface(env, surface), offscreen, workload); +Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_setupBenchmark( + JNIEnv* env, jclass /*clazz*/, jobject surface, jint benchmark, + jboolean offscreen) { + gNativeWindow = ANativeWindow_fromSurface(env, surface); + switch (benchmark) { + case FULL_PIPELINE_BENCHMARK: + gRenderer = new FullPipelineRenderer(gNativeWindow, offscreen); + break; + case PIXEL_OUTPUT_BENCHMARK: + gRenderer = new PixelOutputRenderer(gNativeWindow, offscreen); + break; + case SHADER_PERF_BENCHMARK: + gRenderer = new ShaderPerfRenderer(gNativeWindow, offscreen); + break; + case CONTEXT_SWITCH_BENCHMARK: + gRenderer = new ContextSwitchRenderer(gNativeWindow, offscreen); + break; + default: + ALOGE("Unknown benchmark '%d'", benchmark); + ANativeWindow_release(gNativeWindow); + gNativeWindow = NULL; + return; } + + // Set up call will log error conditions + if (!gRenderer->eglSetUp()) { + delete gRenderer; + gRenderer = NULL; + + ANativeWindow_release(gNativeWindow); + gNativeWindow = NULL; + } +} + +extern "C" JNIEXPORT void JNICALL +Java_com_android_cts_opengl_primitive_GLPrimitiveActivity_tearDownBenchmark( + JNIEnv* /*env*/, jclass /*clazz*/) { + if (gRenderer == NULL) { + return; + } + gRenderer->eglTearDown(); + delete gRenderer; + gRenderer = NULL; + + ANativeWindow_release(gNativeWindow); + gNativeWindow = NULL; }
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.cpp b/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.cpp index 7fd4093..1127d88 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.cpp
@@ -74,13 +74,14 @@ " gl_FragColor = texture2D(u_Texture, v_TexCoord);" "}"; -ContextSwitchRenderer::ContextSwitchRenderer(ANativeWindow* window, bool offscreen, int workload) : - Renderer(window, offscreen, workload), mContexts(NULL) { +ContextSwitchRenderer::ContextSwitchRenderer(ANativeWindow* window, bool offscreen) : + Renderer(window, offscreen), mContexts(NULL), mWorkload(0) { } -bool ContextSwitchRenderer::setUp() { +bool ContextSwitchRenderer::setUp(int workload) { SCOPED_TRACE(); - if (!Renderer::setUp()) { + mWorkload = workload; + if (!Renderer::setUp(workload)) { return false; } @@ -137,7 +138,7 @@ bool ContextSwitchRenderer::tearDown() { SCOPED_TRACE(); if (mContexts) { - // Destroy the contexts, the main one will be handled by Renderer::tearDown(). + // Destroy the contexts, the main one will be handled by Renderer::eglTearDown(). for (int i = 0; i < NUM_WORKER_CONTEXTS; i++) { if (mOffscreen) { if (mFboIds[i] != 0) { @@ -146,6 +147,7 @@ mFboIds[i] = 0; } } + eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(mEglDisplay, mContexts[i]); } delete[] mContexts; @@ -163,6 +165,11 @@ void ContextSwitchRenderer::drawWorkload() { SCOPED_TRACE(); + + if (mWorkload > 8) { + return; // This test does not support higher workloads. + } + // Set the background clear color to black. glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); @@ -216,6 +223,7 @@ } } + eglWaitSyncKHR(mEglDisplay, fence, 0); eglDestroySyncKHR(mEglDisplay, fence); // Switch back to the main context.
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.h b/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.h index 51a4376..ae320ff 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.h +++ b/suite/cts/deviceTests/opengl/jni/primitive/contextswitch/ContextSwitchRenderer.h
@@ -18,9 +18,9 @@ class ContextSwitchRenderer: public Renderer { public: - ContextSwitchRenderer(ANativeWindow* window, bool offscreen, int workload); + ContextSwitchRenderer(ANativeWindow* window, bool offscreen); virtual ~ContextSwitchRenderer() {}; - bool setUp(); + bool setUp(int workload); bool tearDown(); void drawWorkload(); private: @@ -31,6 +31,7 @@ GLuint mTranslateUniformHandle; GLuint mPositionHandle; GLuint mTexCoordHandle; + int mWorkload; }; #endif
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.cpp b/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.cpp index 97462b5..0f75f81 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.cpp
@@ -91,15 +91,15 @@ " gl_FragColor = (diffuse * texture2D(u_Texture, v_TexCoordinate));\n" "}"; -FullPipelineRenderer::FullPipelineRenderer(ANativeWindow* window, bool offscreen, int workload) : - Renderer(window, offscreen, workload), mProgram(NULL), mSceneGraph(NULL), +FullPipelineRenderer::FullPipelineRenderer(ANativeWindow* window, bool offscreen) : + Renderer(window, offscreen), mProgram(NULL), mSceneGraph(NULL), mModelMatrix(NULL), mViewMatrix(NULL), mProjectionMatrix(NULL), mMesh(NULL), mTextureId(0) { } -bool FullPipelineRenderer::setUp() { +bool FullPipelineRenderer::setUp(int workload) { SCOPED_TRACE(); - if (!Renderer::setUp()) { + if (!Renderer::setUp(workload)) { return false; } @@ -147,7 +147,7 @@ return false; } - float count = mWorkload * mWorkload; + float count = workload * workload; float middle = count / 2.0f; float scale = 2.0f / count;
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.h b/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.h index 84616b4..ce44760 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.h +++ b/suite/cts/deviceTests/opengl/jni/primitive/fullpipeline/FullPipelineRenderer.h
@@ -22,9 +22,9 @@ class FullPipelineRenderer: public Renderer { public: - FullPipelineRenderer(ANativeWindow* window, bool offscreen, int workload); + FullPipelineRenderer(ANativeWindow* window, bool offscreen); virtual ~FullPipelineRenderer() {}; - bool setUp(); + bool setUp(int workload); bool tearDown(); void drawWorkload(); private:
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.cpp b/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.cpp index 287ebfb..3a3b9d1 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.cpp
@@ -50,13 +50,14 @@ " gl_FragColor = texture2D(u_Texture, v_TexCoord);" "}"; -PixelOutputRenderer::PixelOutputRenderer(ANativeWindow* window, bool offscreen, int workload) : - Renderer(window, offscreen, workload) { +PixelOutputRenderer::PixelOutputRenderer(ANativeWindow* window, bool offscreen) : + Renderer(window, offscreen), mWorkload(0) { } -bool PixelOutputRenderer::setUp() { +bool PixelOutputRenderer::setUp(int workload) { SCOPED_TRACE(); - if (!Renderer::setUp()) { + mWorkload = workload; + if (!Renderer::setUp(workload)) { return false; } @@ -80,6 +81,11 @@ bool PixelOutputRenderer::tearDown() { SCOPED_TRACE(); + if (mProgramId != 0) + { + glDeleteProgram(mProgramId); + mProgramId = 0; + } if (mTextureId != 0) { glDeleteTextures(1, &mTextureId); mTextureId = 0;
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.h b/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.h index e6b5692..816da6a 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.h +++ b/suite/cts/deviceTests/opengl/jni/primitive/pixeloutput/PixelOutputRenderer.h
@@ -18,9 +18,9 @@ class PixelOutputRenderer: public Renderer { public: - PixelOutputRenderer(ANativeWindow* window, bool offscreen, int workload); + PixelOutputRenderer(ANativeWindow* window, bool offscreen); virtual ~PixelOutputRenderer() {}; - bool setUp(); + bool setUp(int workload); bool tearDown(); void drawWorkload(); private: @@ -28,6 +28,7 @@ GLuint mTextureUniformHandle; GLuint mPositionHandle; GLuint mTexCoordHandle; + int mWorkload; }; #endif
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.cpp b/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.cpp index 1cbc839..a02f4fe 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.cpp
@@ -91,13 +91,13 @@ return destAddr - destStart; } -ShaderPerfRenderer::ShaderPerfRenderer(ANativeWindow* window, bool offscreen, int workload) : - Renderer(window, offscreen, workload) { +ShaderPerfRenderer::ShaderPerfRenderer(ANativeWindow* window, bool offscreen) : + Renderer(window, offscreen) { } -bool ShaderPerfRenderer::setUp() { +bool ShaderPerfRenderer::setUp(int workload) { SCOPED_TRACE(); - if (!Renderer::setUp()) { + if (!Renderer::setUp(workload)) { return false; } @@ -106,7 +106,7 @@ // Add the first part. int index = charCopy(SP_FRAGMENT_1, spFragment, 0); // Add the count, overwriting the '\0' added by charCopy. - spFragment[index - 1] = (char) (((int) '0') + mWorkload); + spFragment[index - 1] = (char) (((int) '0') + workload); // Add the second part. index += charCopy(SP_FRAGMENT_2, spFragment, index); // Create program.
diff --git a/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.h b/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.h index 52fac43..c804202 100644 --- a/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.h +++ b/suite/cts/deviceTests/opengl/jni/primitive/shaderperf/ShaderPerfRenderer.h
@@ -18,9 +18,9 @@ class ShaderPerfRenderer: public Renderer { public: - ShaderPerfRenderer(ANativeWindow* window, bool offscreen, int workload); + ShaderPerfRenderer(ANativeWindow* window, bool offscreen); virtual ~ShaderPerfRenderer() {}; - bool setUp(); + bool setUp(int workload); void drawWorkload(); private: GLuint mTextureId;
diff --git a/suite/cts/deviceTests/opengl/jni/reference/GLReference.cpp b/suite/cts/deviceTests/opengl/jni/reference/GLReference.cpp index 1857848..dc0b4e2 100644 --- a/suite/cts/deviceTests/opengl/jni/reference/GLReference.cpp +++ b/suite/cts/deviceTests/opengl/jni/reference/GLReference.cpp
@@ -23,7 +23,7 @@ extern "C" JNIEXPORT jboolean JNICALL Java_com_android_cts_opengl_reference_GLGameActivity_startBenchmark( - JNIEnv* env, jclass clazz, jobject assetManager, jobject surface, jint numFrames, + JNIEnv* env, jclass /*clazz*/, jobject assetManager, jobject surface, jint numFrames, jdoubleArray setUpTimes, jdoubleArray updateTimes, jdoubleArray renderTimes) { GLUtils::setEnvAndAssetManager(env, assetManager); @@ -32,9 +32,10 @@ return false; } - ReferenceRenderer* renderer = new ReferenceRenderer(ANativeWindow_fromSurface(env, surface)); - - bool success = renderer->setUp(); + ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env, surface); + ReferenceRenderer* renderer = new ReferenceRenderer(nativeWindow); + bool success = renderer->eglSetUp(); + success = renderer->setUp(0) && success; env->SetDoubleArrayRegion( setUpTimes, 0, ReferenceRenderer::NUM_SETUP_TIMES, renderer->mSetUpTimes); @@ -54,7 +55,11 @@ env->SetDoubleArrayRegion(renderTimes, 0, numFrames, renders); success = renderer->tearDown() && success; + renderer->eglTearDown(); delete renderer; renderer = NULL; + + ANativeWindow_release(nativeWindow); + return success; }
diff --git a/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.cpp b/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.cpp index 8f7703e..3b12ee1 100644 --- a/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.cpp +++ b/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.cpp
@@ -22,10 +22,10 @@ #include <Trace.h> ReferenceRenderer::ReferenceRenderer(ANativeWindow* window) : - Renderer(window, false, 0) { + Renderer(window, false) { } -bool ReferenceRenderer::setUp() { +bool ReferenceRenderer::setUp(int workload) { SCOPED_TRACE(); // Reset the times. for (int i = 0; i < NUM_SETUP_TIMES; i++) { @@ -33,7 +33,7 @@ } // Set up OpenGLES. double start = GLUtils::currentTimeMillis(); - if (!Renderer::setUp()) { + if (!Renderer::setUp(workload)) { return false; } mSetUpTimes[0] = GLUtils::currentTimeMillis() - start;
diff --git a/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.h b/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.h index d10297a..f5c4b65 100644 --- a/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.h +++ b/suite/cts/deviceTests/opengl/jni/reference/ReferenceRenderer.h
@@ -23,7 +23,7 @@ public: ReferenceRenderer(ANativeWindow* window); virtual ~ReferenceRenderer() {}; - bool setUp(); + bool setUp(int workload); bool tearDown(); bool update(int frame); void drawWorkload();
diff --git a/suite/cts/deviceTests/opengl/src/com/android/cts/opengl/primitive/GLPrimitiveActivity.java b/suite/cts/deviceTests/opengl/src/com/android/cts/opengl/primitive/GLPrimitiveActivity.java index 5dc9b88..6defdb7 100644 --- a/suite/cts/deviceTests/opengl/src/com/android/cts/opengl/primitive/GLPrimitiveActivity.java +++ b/suite/cts/deviceTests/opengl/src/com/android/cts/opengl/primitive/GLPrimitiveActivity.java
@@ -102,19 +102,12 @@ } } - private static native void setupFullPipelineBenchmark( - Surface surface, boolean offscreen, int workload); + private static native boolean setupBenchmark( + Surface surface, int benchmark, boolean offscreen); - private static native void setupPixelOutputBenchmark( - Surface surface, boolean offscreen, int workload); + private static native boolean startBenchmark(int workload, int numFrames, double[] frameTimes); - private static native void setupShaderPerfBenchmark( - Surface surface, boolean offscreen, int workload); - - private static native void setupContextSwitchBenchmark( - Surface surface, boolean offscreen, int workload); - - private static native boolean startBenchmark(int numFrames, double[] frameTimes); + private static native void tearDownBenchmark(); /** * This thread runs the benchmarks, freeing the UI thread. @@ -138,36 +131,29 @@ watchDog = new WatchDog(mTimeout, this); // Used to record the start and end time of the iteration. double[] times = new double[2]; - for (int i = 0; i < mNumIterations && success; i++) { - // The workload to use for this iteration. - int workload = i + 1; + try { // Setup the benchmark. - switch (mBenchmark) { - case FullPipeline: - setupFullPipelineBenchmark(mSurface, mOffscreen, workload); - break; - case PixelOutput: - setupPixelOutputBenchmark(mSurface, mOffscreen, workload); - break; - case ShaderPerf: - setupShaderPerfBenchmark(mSurface, mOffscreen, workload); - break; - case ContextSwitch: - setupContextSwitchBenchmark(mSurface, mOffscreen, workload); - break; - } - watchDog.start(); - // Start benchmark. - success = startBenchmark(mNumFrames, times); - watchDog.stop(); - - if (!success) { - setException(new Exception("Benchmark failed to run")); - } else { - // Calculate FPS. - mFpsValues[i] = mNumFrames * 1000.0f / (times[1] - times[0]); + setupBenchmark(mSurface, mBenchmark.ordinal(), mOffscreen); + for (int i = 0; i < mNumIterations && success; i++) { + // The workload to use for this iteration. + int workload = i + 1; + watchDog.start(); + // Start benchmark. + success = startBenchmark(workload, mNumFrames, times); + watchDog.stop(); + if (!success) { + setException(new Exception("Benchmark failed to run")); + } else { + // Calculate FPS. + mFpsValues[i] = mNumFrames * 1000.0f / (times[1] - times[0]); + } } } + finally + { + tearDownBenchmark(); + } + complete(); Log.i(TAG, mBenchmark + " Benchmark Completed"); }
diff --git a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/CodecInfo.java b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/CodecInfo.java index 462794b..ccb3126 100644 --- a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/CodecInfo.java +++ b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/CodecInfo.java
@@ -16,6 +16,7 @@ package com.android.cts.videoperf; +import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecInfo.CodecCapabilities; import android.media.MediaCodecInfo.CodecProfileLevel; @@ -23,7 +24,9 @@ import android.media.MediaCodecList; import android.media.MediaFormat; import android.util.Log; +import android.util.Range; +import java.io.IOException; /** * Utility class for getting codec information like bit rate, fps, and etc. @@ -43,32 +46,25 @@ private static final String VIDEO_AVC = MediaFormat.MIMETYPE_VIDEO_AVC; /** * Check if given codec with given (w,h) is supported. + * @param codecName codec name * @param mimeType codec type in mime format like MediaFormat.MIMETYPE_VIDEO_AVC * @param w video width * @param h video height - * @param isEncoder whether the codec is encoder or decoder * @return null if the configuration is not supported. */ public static CodecInfo getSupportedFormatInfo( - String mimeType, int w, int h, boolean isEncoder) { - MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); - MediaFormat format = MediaFormat.createVideoFormat(mimeType, w, h); - String codec = isEncoder - ? mcl.findEncoderForFormat(format) - : mcl.findDecoderForFormat(format); - if (codec == null) { // not supported + String codecName, String mimeType, int w, int h) { + MediaCodec codec; + try { + codec = MediaCodec.createByCodecName(codecName); + } catch (IOException e) { return null; } - CodecCapabilities cap = null; - for (MediaCodecInfo info : mcl.getCodecInfos()) { - if (info.getName().equals(codec)) { - cap = info.getCapabilitiesForType(mimeType); - break; - } - } + CodecCapabilities cap = codec.getCodecInfo().getCapabilitiesForType(mimeType); if (cap.colorFormats.length == 0) { Log.w(TAG, "no supported color format"); + codec.release(); return null; } @@ -84,25 +80,16 @@ printIntArray("supported colors", cap.colorFormats); VideoCapabilities vidCap = cap.getVideoCapabilities(); - if (mimeType.equals(VIDEO_AVC)) { + try { info.mFps = vidCap.getSupportedFrameRatesFor(w, h).getUpper().intValue(); - info.mBitRate = vidCap.getBitrateRange().getUpper(); - - // we don't parse bitrate-range on L, so need to adjust bitrate to supported - // baseline or main profiles only. - int maxBitRate = 0; - for (CodecProfileLevel pl : cap.profileLevels) { - if (pl.profile == pl.AVCProfileBaseline || pl.profile == pl.AVCProfileMain) { - VideoCapabilities vidCapPL = - CodecCapabilities.createFromProfileLevel(mimeType, pl.profile, pl.level) - .getVideoCapabilities(); - maxBitRate = Math.max(maxBitRate, vidCapPL.getBitrateRange().getUpper()); - } - } - info.mBitRate = Math.min(info.mBitRate, maxBitRate); - - Log.i(TAG, "AVC bit rate " + info.mBitRate + " fps " + info.mFps); + } catch (IllegalArgumentException e) { + Log.w(TAG, "unsupported size"); + codec.release(); + return null; } + info.mBitRate = vidCap.getBitrateRange().getUpper(); + Log.i(TAG, "test bit rate " + info.mBitRate + " fps " + info.mFps); + codec.release(); return info; }
diff --git a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java index faa6f6d..62f37c5 100644 --- a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java +++ b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
@@ -16,6 +16,8 @@ package com.android.cts.videoperf; +import android.cts.util.MediaUtils; +import android.cts.util.DeviceReportLog; import android.graphics.ImageFormat; import android.graphics.Point; import android.media.cts.CodecImage; @@ -23,19 +25,28 @@ import android.media.Image; import android.media.Image.Plane; import android.media.MediaCodec; -import android.media.MediaCodecList; +import android.media.MediaCodec.BufferInfo; +import android.media.MediaCodecInfo; import android.media.MediaCodecInfo.CodecCapabilities; +import android.media.MediaCodecList; import android.media.MediaFormat; import android.util.Log; +import android.util.Pair; +import android.util.Range; +import android.util.Size; import android.cts.util.CtsAndroidTestCase; import com.android.cts.util.ResultType; import com.android.cts.util.ResultUnit; import com.android.cts.util.Stat; +import com.android.cts.util.TimeoutReq; import java.io.IOException; import java.nio.ByteBuffer; import java.lang.System; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.LinkedList; import java.util.Random; import java.util.Vector; @@ -57,10 +68,15 @@ private static final long VIDEO_CODEC_WAIT_TIME_US = 5000; private static final boolean VERBOSE = false; private static final String VIDEO_AVC = MediaFormat.MIMETYPE_VIDEO_AVC; - private static final int TOTAL_FRAMES = 300; - private static final int NUMBER_OF_REPEAT = 10; + private static final String VIDEO_VP8 = MediaFormat.MIMETYPE_VIDEO_VP8; + private static final String VIDEO_H263 = MediaFormat.MIMETYPE_VIDEO_H263; + private static final String VIDEO_MPEG4 = MediaFormat.MIMETYPE_VIDEO_MPEG4; + private int mCurrentTestRound = 0; + private double[][] mEncoderFrameTimeDiff = null; + private double[][] mDecoderFrameTimeDiff = null; // i frame interval for encoder private static final int KEY_I_FRAME_INTERVAL = 5; + private static final int MOVING_AVERAGE_NUM = 10; private static final int Y_CLAMP_MIN = 16; private static final int Y_CLAMP_MAX = 235; @@ -75,20 +91,40 @@ private int mVideoHeight; private int mFrameRate; - private Vector<ByteBuffer> mEncodedOutputBuffer; + private MediaFormat mEncInputFormat; + private MediaFormat mEncOutputFormat; + private MediaFormat mDecOutputFormat; + + private LinkedList<Pair<ByteBuffer, BufferInfo>> mEncodedOutputBuffer; // check this many pixels per each decoded frame // checking too many points decreases decoder frame rates a lot. private static final int PIXEL_CHECK_PER_FRAME = 1000; // RMS error in pixel values above this will be treated as error. private static final double PIXEL_RMS_ERROR_MARGAIN = 20.0; + private double mRmsErrorMargain = PIXEL_RMS_ERROR_MARGAIN; private Random mRandom; + private class TestConfig { + public boolean mTestPixels = true; + public boolean mTestResult = false; + public boolean mReportFrameTime = false; + public int mTotalFrames = 300; + public int mMaxTimeMs = 120000; // 2 minutes + public int mNumberOfRepeat = 10; + } + + private TestConfig mTestConfig; + + private DeviceReportLog mReportLog; + @Override protected void setUp() throws Exception { - mEncodedOutputBuffer = new Vector<ByteBuffer>(TOTAL_FRAMES * 2); + mEncodedOutputBuffer = new LinkedList<Pair<ByteBuffer, BufferInfo>>(); // Use time as a seed, hoping to prevent checking pixels in the same pattern long now = System.currentTimeMillis(); mRandom = new Random(now); + mTestConfig = new TestConfig(); + mReportLog = new DeviceReportLog(); super.setUp(); } @@ -101,23 +137,77 @@ mYDirectBuffer = null; mUVDirectBuffer = null; mRandom = null; + mTestConfig = null; + mReportLog.deliverReportToHost(getInstrumentation()); super.tearDown(); } + private String getEncoderName(String mime) { + return getCodecName(mime, true /* isEncoder */); + } + + private String getDecoderName(String mime) { + return getCodecName(mime, false /* isEncoder */); + } + + private String getCodecName(String mime, boolean isEncoder) { + MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); + for (MediaCodecInfo info : mcl.getCodecInfos()) { + if (info.isEncoder() != isEncoder) { + continue; + } + CodecCapabilities caps = null; + try { + caps = info.getCapabilitiesForType(mime); + } catch (IllegalArgumentException e) { // mime is not supported + continue; + } + return info.getName(); + } + return null; + } + + private String[] getEncoderName(String mime, boolean isGoog) { + return getCodecName(mime, isGoog, true /* isEncoder */); + } + + private String[] getDecoderName(String mime, boolean isGoog) { + return getCodecName(mime, isGoog, false /* isEncoder */); + } + + private String[] getCodecName(String mime, boolean isGoog, boolean isEncoder) { + MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); + ArrayList<String> result = new ArrayList<String>(); + for (MediaCodecInfo info : mcl.getCodecInfos()) { + if (info.isEncoder() != isEncoder + || info.getName().toLowerCase().startsWith("omx.google.") != isGoog) { + continue; + } + CodecCapabilities caps = null; + try { + caps = info.getCapabilitiesForType(mime); + } catch (IllegalArgumentException e) { // mime is not supported + continue; + } + result.add(info.getName()); + } + return result.toArray(new String[result.size()]); + } + public void testAvc0176x0144() throws Exception { - doTest(VIDEO_AVC, 176, 144, NUMBER_OF_REPEAT); + doTestDefault(VIDEO_AVC, 176, 144); } public void testAvc0352x0288() throws Exception { - doTest(VIDEO_AVC, 352, 288, NUMBER_OF_REPEAT); + doTestDefault(VIDEO_AVC, 352, 288); } public void testAvc0720x0480() throws Exception { - doTest(VIDEO_AVC, 720, 480, NUMBER_OF_REPEAT); + doTestDefault(VIDEO_AVC, 720, 480); } public void testAvc1280x0720() throws Exception { - doTest(VIDEO_AVC, 1280, 720, NUMBER_OF_REPEAT); + doTestDefault(VIDEO_AVC, 1280, 720); } /** @@ -126,7 +216,133 @@ * which is not specified in API documentation. */ public void testAvc1920x1072() throws Exception { - doTest(VIDEO_AVC, 1920, 1072, NUMBER_OF_REPEAT); + doTestDefault(VIDEO_AVC, 1920, 1072); + } + + // Avc tests + public void testAvc0320x0240Other() throws Exception { + doTestOther(VIDEO_AVC, 320, 240); + } + + public void testAvc0320x0240Goog() throws Exception { + doTestGoog(VIDEO_AVC, 320, 240); + } + + public void testAvc0720x0480Other() throws Exception { + doTestOther(VIDEO_AVC, 720, 480); + } + + public void testAvc0720x0480Goog() throws Exception { + doTestGoog(VIDEO_AVC, 720, 480); + } + + @TimeoutReq(minutes = 10) + public void testAvc1280x0720Other() throws Exception { + doTestOther(VIDEO_AVC, 1280, 720); + } + + @TimeoutReq(minutes = 10) + public void testAvc1280x0720Goog() throws Exception { + doTestGoog(VIDEO_AVC, 1280, 720); + } + + @TimeoutReq(minutes = 10) + public void testAvc1920x1080Other() throws Exception { + doTestOther(VIDEO_AVC, 1920, 1080); + } + + @TimeoutReq(minutes = 10) + public void testAvc1920x1080Goog() throws Exception { + doTestGoog(VIDEO_AVC, 1920, 1080); + } + + // Vp8 tests + public void testVp80320x0180Other() throws Exception { + doTestOther(VIDEO_VP8, 320, 180); + } + + public void testVp80320x0180Goog() throws Exception { + doTestGoog(VIDEO_VP8, 320, 180); + } + + public void testVp80640x0360Other() throws Exception { + doTestOther(VIDEO_VP8, 640, 360); + } + + public void testVp80640x0360Goog() throws Exception { + doTestGoog(VIDEO_VP8, 640, 360); + } + + @TimeoutReq(minutes = 10) + public void testVp81280x0720Other() throws Exception { + doTestOther(VIDEO_VP8, 1280, 720); + } + + @TimeoutReq(minutes = 10) + public void testVp81280x0720Goog() throws Exception { + doTestGoog(VIDEO_VP8, 1280, 720); + } + + @TimeoutReq(minutes = 10) + public void testVp81920x1080Other() throws Exception { + doTestOther(VIDEO_VP8, 1920, 1080); + } + + @TimeoutReq(minutes = 10) + public void testVp81920x1080Goog() throws Exception { + doTestGoog(VIDEO_VP8, 1920, 1080); + } + + // H263 tests + public void testH2630176x0144Other() throws Exception { + doTestOther(VIDEO_H263, 176, 144); + } + + public void testH2630176x0144Goog() throws Exception { + doTestGoog(VIDEO_H263, 176, 144); + } + + public void testH2630352x0288Other() throws Exception { + doTestOther(VIDEO_H263, 352, 288); + } + + public void testH2630352x0288Goog() throws Exception { + doTestGoog(VIDEO_H263, 352, 288); + } + + // Mpeg4 tests + public void testMpeg40176x0144Other() throws Exception { + doTestOther(VIDEO_MPEG4, 176, 144); + } + + public void testMpeg40176x0144Goog() throws Exception { + doTestGoog(VIDEO_MPEG4, 176, 144); + } + + public void testMpeg40352x0288Other() throws Exception { + doTestOther(VIDEO_MPEG4, 352, 288); + } + + public void testMpeg40352x0288Goog() throws Exception { + doTestGoog(VIDEO_MPEG4, 352, 288); + } + + public void testMpeg40640x0480Other() throws Exception { + doTestOther(VIDEO_MPEG4, 640, 480); + } + + public void testMpeg40640x0480Goog() throws Exception { + doTestGoog(VIDEO_MPEG4, 640, 480); + } + + @TimeoutReq(minutes = 10) + public void testMpeg41280x0720Other() throws Exception { + doTestOther(VIDEO_MPEG4, 1280, 720); + } + + @TimeoutReq(minutes = 10) + public void testMpeg41280x0720Goog() throws Exception { + doTestGoog(VIDEO_MPEG4, 1280, 720); } private boolean isSrcSemiPlanar() { @@ -156,25 +372,78 @@ } } + private void doTestGoog(String mimeType, int w, int h) throws Exception { + mTestConfig.mTestPixels = false; + mTestConfig.mTestResult = true; + mTestConfig.mTotalFrames = 3000; + mTestConfig.mNumberOfRepeat = 2; + doTest(true /* isGoog */, mimeType, w, h); + } + + private void doTestOther(String mimeType, int w, int h) throws Exception { + mTestConfig.mTestPixels = false; + mTestConfig.mTestResult = true; + mTestConfig.mTotalFrames = 3000; + mTestConfig.mNumberOfRepeat = 2; + doTest(false /* isGoog */, mimeType, w, h); + } + + private void doTestDefault(String mimeType, int w, int h) throws Exception { + String encoderName = getEncoderName(mimeType); + if (encoderName == null) { + Log.i(TAG, "Encoder for " + mimeType + " not found"); + return; + } + + String decoderName = getDecoderName(mimeType); + if (decoderName == null) { + Log.i(TAG, "Encoder for " + mimeType + " not found"); + return; + } + + doTestByName(encoderName, decoderName, mimeType, w, h); + } + /** * Run encoding / decoding test for given mimeType of codec + * @param isGoog test google or non-google codec. * @param mimeType like video/avc * @param w video width * @param h video height - * @param numberRepeat how many times to repeat the encoding / decoding process */ - private void doTest(String mimeType, int w, int h, int numberRepeat) throws Exception { - CodecInfo infoEnc = CodecInfo.getSupportedFormatInfo(mimeType, w, h, true /* encoder */); + private void doTest(boolean isGoog, String mimeType, int w, int h) + throws Exception { + String[] encoderNames = getEncoderName(mimeType, isGoog); + if (encoderNames.length == 0) { + Log.i(TAG, isGoog ? "Google " : "Non-google " + + "encoder for " + mimeType + " not found"); + return; + } + + String[] decoderNames = getDecoderName(mimeType, isGoog); + if (decoderNames.length == 0) { + Log.i(TAG, isGoog ? "Google " : "Non-google " + + "decoder for " + mimeType + " not found"); + return; + } + + for (String encoderName: encoderNames) { + for (String decoderName: decoderNames) { + doTestByName(encoderName, decoderName, mimeType, w, h); + } + } + } + + private void doTestByName( + String encoderName, String decoderName, String mimeType, int w, int h) + throws Exception { + CodecInfo infoEnc = CodecInfo.getSupportedFormatInfo(encoderName, mimeType, w, h); if (infoEnc == null) { Log.i(TAG, "Encoder " + mimeType + " with " + w + "," + h + " not supported"); return; } - CodecInfo infoDec = CodecInfo.getSupportedFormatInfo(mimeType, w, h, false); - if (infoDec == null) { - Log.i(TAG, "Codec " + mimeType + "with " + w + "," + h + " not supported"); - return; - } - + CodecInfo infoDec = CodecInfo.getSupportedFormatInfo(decoderName, mimeType, w, h); + assertNotNull(infoDec); mVideoWidth = w; mVideoHeight = h; @@ -185,12 +454,17 @@ ", dec format " + mDstColorFormat); initYUVPlane(w + YUV_PLANE_ADDITIONAL_LENGTH, h + YUV_PLANE_ADDITIONAL_LENGTH); - double[] encoderFpsResults = new double[numberRepeat]; - double[] decoderFpsResults = new double[numberRepeat]; - double[] totalFpsResults = new double[numberRepeat]; - double[] decoderRmsErrorResults = new double[numberRepeat]; + mEncoderFrameTimeDiff = + new double[mTestConfig.mNumberOfRepeat][mTestConfig.mTotalFrames - 1]; + mDecoderFrameTimeDiff = + new double[mTestConfig.mNumberOfRepeat][mTestConfig.mTotalFrames - 1]; + double[] encoderFpsResults = new double[mTestConfig.mNumberOfRepeat]; + double[] decoderFpsResults = new double[mTestConfig.mNumberOfRepeat]; + double[] totalFpsResults = new double[mTestConfig.mNumberOfRepeat]; + double[] decoderRmsErrorResults = new double[mTestConfig.mNumberOfRepeat]; boolean success = true; - for (int i = 0; i < numberRepeat && success; i++) { + for (int i = 0; i < mTestConfig.mNumberOfRepeat && success; i++) { + mCurrentTestRound = i; MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, mimeType); format.setInteger(MediaFormat.KEY_BIT_RATE, infoEnc.mBitRate); @@ -200,22 +474,24 @@ format.setInteger(MediaFormat.KEY_FRAME_RATE, infoEnc.mFps); mFrameRate = infoEnc.mFps; format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, KEY_I_FRAME_INTERVAL); - double encodingTime = runEncoder(VIDEO_AVC, format, TOTAL_FRAMES); + + double encodingTime = runEncoder(encoderName, format, mTestConfig.mTotalFrames); // re-initialize format for decoder format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, mimeType); format.setInteger(MediaFormat.KEY_WIDTH, w); format.setInteger(MediaFormat.KEY_HEIGHT, h); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, mDstColorFormat); - double[] decoderResult = runDecoder(VIDEO_AVC, format); + double[] decoderResult = runDecoder(decoderName, format); if (decoderResult == null) { success = false; } else { double decodingTime = decoderResult[0]; decoderRmsErrorResults[i] = decoderResult[1]; - encoderFpsResults[i] = (double)TOTAL_FRAMES / encodingTime * 1000.0; - decoderFpsResults[i] = (double)TOTAL_FRAMES / decodingTime * 1000.0; - totalFpsResults[i] = (double)TOTAL_FRAMES / (encodingTime + decodingTime) * 1000.0; + encoderFpsResults[i] = (double)mTestConfig.mTotalFrames / encodingTime * 1000.0; + decoderFpsResults[i] = (double)mTestConfig.mTotalFrames / decodingTime * 1000.0; + totalFpsResults[i] = + (double)mTestConfig.mTotalFrames / (encodingTime + decodingTime) * 1000.0; } // clear things for re-start @@ -223,34 +499,106 @@ // it will be good to clean everything to make every run the same. System.gc(); } - getReportLog().printArray("encoder", encoderFpsResults, ResultType.HIGHER_BETTER, + mReportLog.printArray("encoder", encoderFpsResults, ResultType.HIGHER_BETTER, ResultUnit.FPS); - getReportLog().printArray("rms error", decoderRmsErrorResults, ResultType.LOWER_BETTER, + mReportLog.printArray("rms error", decoderRmsErrorResults, ResultType.LOWER_BETTER, ResultUnit.NONE); - getReportLog().printArray("decoder", decoderFpsResults, ResultType.HIGHER_BETTER, + mReportLog.printArray("decoder", decoderFpsResults, ResultType.HIGHER_BETTER, ResultUnit.FPS); - getReportLog().printArray("encoder decoder", totalFpsResults, ResultType.HIGHER_BETTER, + mReportLog.printArray("encoder decoder", totalFpsResults, ResultType.HIGHER_BETTER, ResultUnit.FPS); - getReportLog().printSummary("encoder decoder", Stat.getAverage(totalFpsResults), + mReportLog.printValue(mimeType + " encoder average fps for " + w + "x" + h, + Stat.getAverage(encoderFpsResults), ResultType.HIGHER_BETTER, ResultUnit.FPS); + mReportLog.printValue(mimeType + " decoder average fps for " + w + "x" + h, + Stat.getAverage(decoderFpsResults), ResultType.HIGHER_BETTER, ResultUnit.FPS); + mReportLog.printSummary("encoder decoder", Stat.getAverage(totalFpsResults), ResultType.HIGHER_BETTER, ResultUnit.FPS); - // make sure that rms error is not too big. - for (int i = 0; i < numberRepeat; i++) { - assertTrue(decoderRmsErrorResults[i] < PIXEL_RMS_ERROR_MARGAIN); + + boolean encTestPassed = false; + boolean decTestPassed = false; + double[] measuredFps = new double[mTestConfig.mNumberOfRepeat]; + String[] resultRawData = new String[mTestConfig.mNumberOfRepeat]; + for (int i = 0; i < mTestConfig.mNumberOfRepeat; i++) { + // make sure that rms error is not too big. + if (decoderRmsErrorResults[i] >= mRmsErrorMargain) { + fail("rms error is bigger than the limit " + + decoderRmsErrorResults[i] + " vs " + mRmsErrorMargain); + } + + if (mTestConfig.mReportFrameTime) { + mReportLog.printValue( + "encodertest#" + i + ": " + Arrays.toString(mEncoderFrameTimeDiff[i]), + 0, ResultType.NEUTRAL, ResultUnit.NONE); + mReportLog.printValue( + "decodertest#" + i + ": " + Arrays.toString(mDecoderFrameTimeDiff[i]), + 0, ResultType.NEUTRAL, ResultUnit.NONE); + } + + if (mTestConfig.mTestResult) { + double[] avgs = MediaUtils.calculateMovingAverage( + mEncoderFrameTimeDiff[i], MOVING_AVERAGE_NUM); + double encMin = Stat.getMin(avgs); + double encMax = Stat.getMax(avgs); + double encAvg = MediaUtils.getAverage(mEncoderFrameTimeDiff[i]); + double encStdev = MediaUtils.getStdev(avgs); + String prefix = "codec=" + encoderName + " round=" + i + + " EncInputFormat=" + mEncInputFormat + + " EncOutputFormat=" + mEncOutputFormat; + String result = + MediaUtils.logResults(mReportLog, prefix, encMin, encMax, encAvg, encStdev); + double measuredEncFps = 1000000000 / encMin; + resultRawData[i] = result; + measuredFps[i] = measuredEncFps; + if (!encTestPassed) { + encTestPassed = MediaUtils.verifyResults( + encoderName, mimeType, w, h, measuredEncFps); + } + + avgs = MediaUtils.calculateMovingAverage( + mDecoderFrameTimeDiff[i], MOVING_AVERAGE_NUM); + double decMin = Stat.getMin(avgs); + double decMax = Stat.getMax(avgs); + double decAvg = MediaUtils.getAverage(mDecoderFrameTimeDiff[i]); + double decStdev = MediaUtils.getStdev(avgs); + prefix = "codec=" + decoderName + " size=" + w + "x" + h + " round=" + i + + " DecOutputFormat=" + mDecOutputFormat; + MediaUtils.logResults(mReportLog, prefix, decMin, decMax, decAvg, decStdev); + double measuredDecFps = 1000000000 / decMin; + if (!decTestPassed) { + decTestPassed = MediaUtils.verifyResults( + decoderName, mimeType, w, h, measuredDecFps); + } + } } + + if (mTestConfig.mTestResult) { + if (!encTestPassed) { + Range<Double> reportedRange = + MediaUtils.getAchievableFrameRatesFor(encoderName, mimeType, w, h); + String failMessage = + MediaUtils.getErrorMessage(reportedRange, measuredFps, resultRawData); + fail(failMessage); + } + // Decoder result will be verified in VideoDecoderPerfTest + // if (!decTestPassed) { + // fail("Measured fps for " + decoderName + + // " doesn't match with reported achievable frame rates."); + // } + } + measuredFps = null; + resultRawData = null; } /** * run encoder benchmarking - * @param mimeType encoder type like video/avc + * @param encoderName encoder name * @param format format of media to encode * @param totalFrames total number of frames to encode * @return time taken in ms to encode the frames. This does not include initialization time. */ - private double runEncoder(String mimeType, MediaFormat format, int totalFrames) { + private double runEncoder(String encoderName, MediaFormat format, int totalFrames) { MediaCodec codec = null; try { - MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); - String encoderName = mcl.findEncoderForFormat(format); codec = MediaCodec.createByCodecName(encoderName); codec.configure( format, @@ -258,19 +606,21 @@ null /* crypto */, MediaCodec.CONFIGURE_FLAG_ENCODE); } catch (IllegalStateException e) { - Log.e(TAG, "codec '" + mimeType + "' failed configuration."); + Log.e(TAG, "codec '" + encoderName + "' failed configuration."); codec.release(); - assertTrue("codec '" + mimeType + "' failed configuration.", false); + assertTrue("codec '" + encoderName + "' failed configuration.", false); } catch (IOException | NullPointerException e) { Log.i(TAG, "could not find codec for " + format); return Double.NaN; } codec.start(); + mEncInputFormat = codec.getInputFormat(); ByteBuffer[] codecOutputBuffers = codec.getOutputBuffers(); int numBytesSubmitted = 0; int numBytesDequeued = 0; int inFramesCount = 0; + long lastOutputTimeNs = 0; long start = System.currentTimeMillis(); while (true) { int index; @@ -279,6 +629,10 @@ index = codec.dequeueInputBuffer(VIDEO_CODEC_WAIT_TIME_US /* timeoutUs */); if (index != MediaCodec.INFO_TRY_AGAIN_LATER) { int size; + boolean eos = (inFramesCount == (totalFrames - 1)); + if (!eos && ((System.currentTimeMillis() - start) > mTestConfig.mMaxTimeMs)) { + eos = true; + } // when encoder only supports flexYUV, use Image only; otherwise, // use ByteBuffer & Image each on half of the frames to test both if (isSrcFlexYUV() || inFramesCount % 2 == 0) { @@ -287,14 +641,12 @@ assertTrue(image != null); size = queueInputImageEncoder( codec, image, index, inFramesCount, - (inFramesCount == (totalFrames - 1)) ? - MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); + eos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); } else { ByteBuffer buffer = codec.getInputBuffer(index); size = queueInputBufferEncoder( codec, buffer, index, inFramesCount, - (inFramesCount == (totalFrames - 1)) ? - MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); + eos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); } inFramesCount++; numBytesSubmitted += size; @@ -309,9 +661,19 @@ index = codec.dequeueOutputBuffer(info, VIDEO_CODEC_WAIT_TIME_US /* timeoutUs */); if (index == MediaCodec.INFO_TRY_AGAIN_LATER) { } else if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { + mEncOutputFormat = codec.getOutputFormat(); } else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { codecOutputBuffers = codec.getOutputBuffers(); } else if (index >= 0) { + if (lastOutputTimeNs > 0) { + int pos = mEncodedOutputBuffer.size() - 1; + if (pos < mEncoderFrameTimeDiff[mCurrentTestRound].length) { + long diff = System.nanoTime() - lastOutputTimeNs; + mEncoderFrameTimeDiff[mCurrentTestRound][pos] = diff; + } + } + lastOutputTimeNs = System.nanoTime(); + dequeueOutputBufferEncoder(codec, codecOutputBuffers, index, info); numBytesDequeued += info.size; if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { @@ -326,6 +688,10 @@ } } long finish = System.currentTimeMillis(); + int validDataNum = Math.min(mEncodedOutputBuffer.size() - 1, + mEncoderFrameTimeDiff[mCurrentTestRound].length); + mEncoderFrameTimeDiff[mCurrentTestRound] = + Arrays.copyOf(mEncoderFrameTimeDiff[mCurrentTestRound], validDataNum); if (VERBOSE) { Log.d(TAG, "queued a total of " + numBytesSubmitted + "bytes, " + "dequeued " + numBytesDequeued + " bytes."); @@ -536,28 +902,27 @@ MediaCodec codec, ByteBuffer[] outputBuffers, int index, MediaCodec.BufferInfo info) { ByteBuffer output = outputBuffers[index]; - output.clear(); int l = info.size; ByteBuffer copied = ByteBuffer.allocate(l); output.get(copied.array(), 0, l); - mEncodedOutputBuffer.add(copied); + BufferInfo savedInfo = new BufferInfo(); + savedInfo.set(0, l, info.presentationTimeUs, info.flags); + mEncodedOutputBuffer.addLast(Pair.create(copied, savedInfo)); codec.releaseOutputBuffer(index, false /* render */); } /** * run encoder benchmarking with encoded stream stored from encoding phase - * @param mimeType encoder type like video/avc + * @param decoderName decoder name * @param format format of media to decode * @return returns length-2 array with 0: time for decoding, 1 : rms error of pixels */ - private double[] runDecoder(String mimeType, MediaFormat format) { - MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); - String decoderName = mcl.findDecoderForFormat(format); + private double[] runDecoder(String decoderName, MediaFormat format) { MediaCodec codec = null; try { codec = MediaCodec.createByCodecName(decoderName); } catch (IOException | NullPointerException e) { - Log.i(TAG, "could not find codec for " + format); + Log.i(TAG, "could not find decoder for " + format); return null; } codec.configure(format, null /* surface */, null /* crypto */, 0 /* flags */); @@ -573,6 +938,7 @@ int outFrameCount = 0; YUVValue expected = new YUVValue(); YUVValue decoded = new YUVValue(); + long lastOutputTimeNs = 0; long start = System.currentTimeMillis(); while (!sawOutputEOS) { if (inputLeft > 0) { @@ -581,15 +947,22 @@ if (inputBufIndex >= 0) { ByteBuffer dstBuf = codecInputBuffers[inputBufIndex]; dstBuf.clear(); - ByteBuffer src = mEncodedOutputBuffer.get(inputBufferCount); + ByteBuffer src = mEncodedOutputBuffer.get(inputBufferCount).first; + BufferInfo srcInfo = mEncodedOutputBuffer.get(inputBufferCount).second; int writeSize = src.capacity(); dstBuf.put(src.array(), 0, writeSize); + + int flags = srcInfo.flags; + if ((System.currentTimeMillis() - start) > mTestConfig.mMaxTimeMs) { + flags |= MediaCodec.BUFFER_FLAG_END_OF_STREAM; + } + codec.queueInputBuffer( inputBufIndex, 0 /* offset */, writeSize, - 0, - (inputLeft == 1) ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); + srcInfo.presentationTimeUs, + flags); inputLeft --; inputBufferCount ++; } @@ -601,29 +974,57 @@ // only do YUV compare on EOS frame if the buffer size is none-zero if (info.size > 0) { - Point origin = getOrigin(outFrameCount); - int i; - - // if decoder supports planar or semiplanar, check output with - // ByteBuffer & Image each on half of the points - int pixelCheckPerFrame = PIXEL_CHECK_PER_FRAME; - if (!isDstFlexYUV()) { - pixelCheckPerFrame /= 2; - ByteBuffer buf = codec.getOutputBuffer(outputBufIndex); - if (VERBOSE && (outFrameCount == 0)) { - printByteBuffer("Y ", buf, 0, 20); - printByteBuffer("UV ", buf, mVideoWidth * mVideoHeight, 20); - printByteBuffer("UV ", buf, - mVideoWidth * mVideoHeight + mVideoWidth * 60, 20); + if (lastOutputTimeNs > 0) { + int pos = outFrameCount - 1; + if (pos < mDecoderFrameTimeDiff[mCurrentTestRound].length) { + long diff = System.nanoTime() - lastOutputTimeNs; + mDecoderFrameTimeDiff[mCurrentTestRound][pos] = diff; } + } + lastOutputTimeNs = System.nanoTime(); + + if (mTestConfig.mTestPixels) { + Point origin = getOrigin(outFrameCount); + int i; + + // if decoder supports planar or semiplanar, check output with + // ByteBuffer & Image each on half of the points + int pixelCheckPerFrame = PIXEL_CHECK_PER_FRAME; + if (!isDstFlexYUV()) { + pixelCheckPerFrame /= 2; + ByteBuffer buf = codec.getOutputBuffer(outputBufIndex); + if (VERBOSE && (outFrameCount == 0)) { + printByteBuffer("Y ", buf, 0, 20); + printByteBuffer("UV ", buf, mVideoWidth * mVideoHeight, 20); + printByteBuffer("UV ", buf, + mVideoWidth * mVideoHeight + mVideoWidth * 60, 20); + } + for (i = 0; i < pixelCheckPerFrame; i++) { + int w = mRandom.nextInt(mVideoWidth); + int h = mRandom.nextInt(mVideoHeight); + getPixelValuesFromYUVBuffers(origin.x, origin.y, w, h, expected); + getPixelValuesFromOutputBuffer(buf, w, h, decoded); + if (VERBOSE) { + Log.i(TAG, outFrameCount + "-" + i + "- th round: ByteBuffer:" + + " expected " + + expected.mY + "," + expected.mU + "," + expected.mV + + " decoded " + + decoded.mY + "," + decoded.mU + "," + decoded.mV); + } + totalErrorSquared += expected.calcErrorSquared(decoded); + } + } + + Image image = codec.getOutputImage(outputBufIndex); + assertTrue(image != null); for (i = 0; i < pixelCheckPerFrame; i++) { int w = mRandom.nextInt(mVideoWidth); int h = mRandom.nextInt(mVideoHeight); getPixelValuesFromYUVBuffers(origin.x, origin.y, w, h, expected); - getPixelValuesFromOutputBuffer(buf, w, h, decoded); + getPixelValuesFromImage(image, w, h, decoded); if (VERBOSE) { - Log.i(TAG, outFrameCount + "-" + i + "- th round: ByteBuffer:" - + " expected " + Log.i(TAG, outFrameCount + "-" + i + "- th round: FlexYUV:" + + " expcted " + expected.mY + "," + expected.mU + "," + expected.mV + " decoded " + decoded.mY + "," + decoded.mU + "," + decoded.mV); @@ -631,23 +1032,6 @@ totalErrorSquared += expected.calcErrorSquared(decoded); } } - - Image image = codec.getOutputImage(outputBufIndex); - assertTrue(image != null); - for (i = 0; i < pixelCheckPerFrame; i++) { - int w = mRandom.nextInt(mVideoWidth); - int h = mRandom.nextInt(mVideoHeight); - getPixelValuesFromYUVBuffers(origin.x, origin.y, w, h, expected); - getPixelValuesFromImage(image, w, h, decoded); - if (VERBOSE) { - Log.i(TAG, outFrameCount + "-" + i + "- th round: FlexYUV:" - + " expcted " - + expected.mY + "," + expected.mU + "," + expected.mV - + " decoded " - + decoded.mY + "," + decoded.mU + "," + decoded.mV); - } - totalErrorSquared += expected.calcErrorSquared(decoded); - } outFrameCount++; } codec.releaseOutputBuffer(outputBufIndex, false /* render */); @@ -656,9 +1040,9 @@ sawOutputEOS = true; } } else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { - MediaFormat oformat = codec.getOutputFormat(); - Log.d(TAG, "output format has changed to " + oformat); - int colorFormat = oformat.getInteger(MediaFormat.KEY_COLOR_FORMAT); + mDecOutputFormat = codec.getOutputFormat(); + Log.d(TAG, "output format has changed to " + mDecOutputFormat); + int colorFormat = mDecOutputFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT); if (colorFormat == CodecCapabilities.COLOR_FormatYUV420SemiPlanar || colorFormat == CodecCapabilities.COLOR_FormatYUV420Planar) { mDstColorFormat = colorFormat; @@ -670,10 +1054,14 @@ } } long finish = System.currentTimeMillis(); + int validDataNum = Math.min(outFrameCount - 1, + mDecoderFrameTimeDiff[mCurrentTestRound].length); + mDecoderFrameTimeDiff[mCurrentTestRound] = + Arrays.copyOf(mDecoderFrameTimeDiff[mCurrentTestRound], validDataNum); codec.stop(); codec.release(); codec = null; - assertTrue(outFrameCount >= TOTAL_FRAMES); + // divide by 3 as sum is done for Y, U, V. double errorRms = Math.sqrt(totalErrorSquared / PIXEL_CHECK_PER_FRAME / outFrameCount / 3); double[] result = { (double) finish - start, errorRms };
diff --git a/suite/cts/hostTests/jank/app/src/com/android/cts/jank/ui/CtsDeviceJankUi.java b/suite/cts/hostTests/jank/app/src/com/android/cts/jank/ui/CtsDeviceJankUi.java deleted file mode 100644 index ea1f685..0000000 --- a/suite/cts/hostTests/jank/app/src/com/android/cts/jank/ui/CtsDeviceJankUi.java +++ /dev/null
@@ -1,86 +0,0 @@ -/* - * Copyright (C) 2013 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.jank.ui; - -import android.util.Log; -import android.widget.ListView; - -import com.android.cts.jank.CtsJankTestBase; -import com.android.uiautomator.core.UiScrollable; -import com.android.uiautomator.core.UiSelector; -import com.android.uiautomator.platform.SurfaceFlingerHelper; - -public class CtsDeviceJankUi extends CtsJankTestBase { - private final static String TAG = CtsDeviceJankUi.class.getName(); - private final static String PACKAGE = "com.android.cts.ui"; - private final static String COMPONENT = - PACKAGE + "/" + PACKAGE + ".ScrollingActivity"; - private final static int NUM_ELEMENTS = 1000; - private static String APP_WINDOW_NAME = COMPONENT; - - // TODO(stuartscott): expand deviceTests/ui app to have a more complex UI - /** - * Runs the ScrollingActivity and measures jank during a scroll. - */ - public void testScrolling() throws Exception { - // Start activity command - final StringBuilder sb = new StringBuilder(); - sb.append(String.format(START_CMD, COMPONENT)); - sb.append(String.format(INTENT_INTEGER_EXTRA, "num_elements", NUM_ELEMENTS)); - final String startCommand = sb.toString(); - final String stopCommand = String.format(STOP_CMD, PACKAGE); - - Log.i(TAG, "Start command: " + startCommand); - Log.i(TAG, "Stop command: " + stopCommand); - - setIteration(NUM_ITERATIONS); - for (int i = 0; i < NUM_ITERATIONS; i++) { - // Stop any existing instances - runShellCommand(stopCommand); - // Start activity - runShellCommand(startCommand); - - // Wait for the activity to start - sleep(SLEEP_TIME / 2); - - UiScrollable list = new UiScrollable( - new UiSelector().className(ListView.class.getName())); - - // Start systrace - startTrace(mTestCaseName, i); - - // Clear SurfaceFlinger buffer - Log.i(TAG, "Clearing SurfaceFlinger buffer"); - SurfaceFlingerHelper.clearBuffer(APP_WINDOW_NAME); - - list.flingToEnd(2); - - // Dump SurfaceFlinger buffer - Log.i(TAG, "Dumping SurfaceFlinger buffer"); - boolean result = SurfaceFlingerHelper.dumpFrameLatency(APP_WINDOW_NAME, true); - assertTrue("SurfaceFlingerHelper could not get timestamps", result); - - // Stop systrace - endTrace(); - - // Record results - recordResults(mTestCaseName, i); - } - // Save aggregated results - saveResults(mTestCaseName); - // Stop any remaining instances - runShellCommand(stopCommand); - } -}
diff --git a/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java b/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java deleted file mode 100644 index a07171e..0000000 --- a/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java +++ /dev/null
@@ -1,53 +0,0 @@ -/* - * Copyright (C) 2013 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.jank.ui; - -import com.android.cts.jank.CtsHostJankTest; -import com.android.cts.util.AbiUtils; -import java.io.File; - -public class CtsHostJankUi extends CtsHostJankTest { - - private static final String APK_PACKAGE = "com.android.cts"; - private static final String APK = "CtsDeviceUi.apk"; - private static final String PACKAGE = "com.android.cts.jank.ui"; - private static final String HOST_CLASS = CtsHostJankUi.class.getName(); - private static final String DEVICE_CLASS = PACKAGE + ".CtsDeviceJankUi"; - private static final String JAR_NAME = "CtsDeviceJank.jar"; - - public CtsHostJankUi() { - super(JAR_NAME, DEVICE_CLASS, HOST_CLASS); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - // Install the app. - mDevice.uninstallPackage(APK_PACKAGE); - File app = mBuild.getTestApp(APK); - String[] options = {AbiUtils.createAbiFlag(mAbi.getName())}; - mDevice.installPackage(app, false, options); - } - - @Override - protected void tearDown() throws Exception { - // Uninstall the app. - mDevice.uninstallPackage(APK_PACKAGE); - super.tearDown(); - } - - public void testScrolling() throws Exception { - runUiAutomatorTest("testScrolling"); - } -}
diff --git a/suite/cts/hostTests/uihost/appA/Android.mk b/suite/cts/hostTests/uihost/appA/Android.mk index 3e76fdb..17f076f 100644 --- a/suite/cts/hostTests/uihost/appA/Android.mk +++ b/suite/cts/hostTests/uihost/appA/Android.mk
@@ -26,8 +26,6 @@ LOCAL_PACKAGE_NAME := CtsDeviceTaskswitchingAppA -LOCAL_SDK_VERSION := 16 +LOCAL_SDK_VERSION := current -include $(BUILD_CTS_PACKAGE) - - +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/suite/cts/hostTests/uihost/appB/Android.mk b/suite/cts/hostTests/uihost/appB/Android.mk index 13af40f..ebb36d2 100644 --- a/suite/cts/hostTests/uihost/appB/Android.mk +++ b/suite/cts/hostTests/uihost/appB/Android.mk
@@ -26,8 +26,6 @@ LOCAL_PACKAGE_NAME := CtsDeviceTaskswitchingAppB -LOCAL_SDK_VERSION := 16 +LOCAL_SDK_VERSION := current -include $(BUILD_CTS_PACKAGE) - - +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/suite/cts/hostTests/uihost/control/Android.mk b/suite/cts/hostTests/uihost/control/Android.mk index 3770918..4de9ae8 100644 --- a/suite/cts/hostTests/uihost/control/Android.mk +++ b/suite/cts/hostTests/uihost/control/Android.mk
@@ -26,6 +26,6 @@ LOCAL_PACKAGE_NAME := CtsDeviceTaskswitchingControl -LOCAL_SDK_VERSION := 16 +LOCAL_SDK_VERSION := current -include $(BUILD_CTS_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java index 894b824..2d33436 100644 --- a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java +++ b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java
@@ -115,7 +115,9 @@ @Override public void testEnded(TestIdentifier test, Map<String, String> testMetrics) { // necessary as testMetrics passed from CollectingTestListerner is empty - mCtsReport = testMetrics.get("CTS_TEST_RESULT"); + if (testMetrics.containsKey("CTS_TEST_RESULT")) { + mCtsReport = testMetrics.get("CTS_TEST_RESULT"); + } super.testEnded(test, testMetrics); } }
diff --git a/tests/JobScheduler/src/android/jobscheduler/MockJobService.java b/tests/JobScheduler/src/android/jobscheduler/MockJobService.java index a0177e2..4f549f8 100644 --- a/tests/JobScheduler/src/android/jobscheduler/MockJobService.java +++ b/tests/JobScheduler/src/android/jobscheduler/MockJobService.java
@@ -34,7 +34,7 @@ private static final String TAG = "MockJobService"; /** Wait this long before timing out the test. */ - private static final long DEFAULT_TIMEOUT_MILLIS = 5000L; // 5 seconds. + private static final long DEFAULT_TIMEOUT_MILLIS = 30000L; // 30 seconds. @Override public void onCreate() { @@ -46,7 +46,7 @@ public boolean onStartJob(JobParameters params) { Log.i(TAG, "Test job executing: " + params.getJobId()); - TestEnvironment.getTestEnvironment().notifyExecution(params.getJobId()); + TestEnvironment.getTestEnvironment().notifyExecution(params); return false; // No work to do. } @@ -63,10 +63,10 @@ public static final class TestEnvironment { private static TestEnvironment kTestEnvironment; - public static final int INVALID_JOB_ID = -1; + //public static final int INVALID_JOB_ID = -1; private CountDownLatch mLatch; - private int mExecutedJobId; + private JobParameters mExecutedJobParameters; public static TestEnvironment getTestEnvironment() { if (kTestEnvironment == null) { @@ -75,6 +75,10 @@ return kTestEnvironment; } + public JobParameters getLastJobParameters() { + return mExecutedJobParameters; + } + /** * Block the test thread, waiting on the JobScheduler to execute some previously scheduled * job on this service. @@ -93,9 +97,9 @@ return !mLatch.await(DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } - private void notifyExecution(int jobId) { - Log.d(TAG, "Job executed:" + jobId); - mExecutedJobId = jobId; + private void notifyExecution(JobParameters params) { + Log.d(TAG, "Job executed:" + params.getJobId()); + mExecutedJobParameters = params; mLatch.countDown(); } @@ -111,7 +115,7 @@ /** Called in each testCase#setup */ public void setUp() { mLatch = null; - mExecutedJobId = INVALID_JOB_ID; + mExecutedJobParameters = null; } }
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/TimingConstraintsTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/TimingConstraintsTest.java index 36f44ef..40b67c8 100644 --- a/tests/JobScheduler/src/android/jobscheduler/cts/TimingConstraintsTest.java +++ b/tests/JobScheduler/src/android/jobscheduler/cts/TimingConstraintsTest.java
@@ -17,6 +17,7 @@ import android.annotation.TargetApi; import android.app.job.JobInfo; +import android.app.job.JobParameters; /** * Schedules jobs with various timing constraints and ensures that they are executed when @@ -26,10 +27,12 @@ public class TimingConstraintsTest extends ConstraintTest { private static final int TIMING_JOB_ID = TimingConstraintsTest.class.hashCode() + 0; private static final int CANCEL_JOB_ID = TimingConstraintsTest.class.hashCode() + 1; + private static final int EXPIRED_JOB_ID = TimingConstraintsTest.class.hashCode() + 2; + private static final int UNEXPIRED_JOB_ID = TimingConstraintsTest.class.hashCode() + 3; public void testScheduleOnce() throws Exception { JobInfo oneTimeJob = new JobInfo.Builder(TIMING_JOB_ID, kJobServiceComponent) - .setOverrideDeadline(1000) // 1 secs + .setOverrideDeadline(5000) // 5 secs .build(); kTestEnvironment.setExpectedExecutions(1); @@ -41,7 +44,7 @@ public void testSchedulePeriodic() throws Exception { JobInfo periodicJob = new JobInfo.Builder(TIMING_JOB_ID, kJobServiceComponent) - .setPeriodic(1000L) // 1 second period. + .setPeriodic(5000L) // 5 second period. .build(); kTestEnvironment.setExpectedExecutions(3); @@ -52,7 +55,8 @@ public void testCancel() throws Exception { JobInfo cancelJob = new JobInfo.Builder(CANCEL_JOB_ID, kJobServiceComponent) - .setOverrideDeadline(2000L) + .setMinimumLatency(5000L) // make sure it doesn't actually run immediately + .setOverrideDeadline(7000L) .build(); kTestEnvironment.setExpectedExecutions(0); @@ -62,4 +66,44 @@ assertTrue("Cancel failed: job executed when it shouldn't have.", kTestEnvironment.awaitTimeout()); } + + /** + * Ensure that when a job is executed because its deadline has expired, that + * {@link JobParameters#isOverrideDeadlineExpired()} returns the correct value. + */ + public void testJobParameters_expiredDeadline() throws Exception { + + JobInfo deadlineJob = + new JobInfo.Builder(EXPIRED_JOB_ID, kJobServiceComponent) + .setOverrideDeadline(2000L) + .build(); + kTestEnvironment.setExpectedExecutions(1); + mJobScheduler.schedule(deadlineJob); + assertTrue("Failed to execute deadline job", kTestEnvironment.awaitExecution()); + assertTrue("Job that had its deadline expire didn't have" + + " JobParameters#isOverrideDeadlineExpired=true", + kTestEnvironment.getLastJobParameters().isOverrideDeadlineExpired()); + } + + + /** + * Ensure that when a job is executed and its deadline hasn't expired, that + * {@link JobParameters#isOverrideDeadlineExpired()} returns the correct value. + */ + public void testJobParameters_unexpiredDeadline() throws Exception { + + JobInfo deadlineJob = + new JobInfo.Builder(UNEXPIRED_JOB_ID, kJobServiceComponent) + .setMinimumLatency(500L) + .setRequiresCharging(true) + .build(); + kTestEnvironment.setExpectedExecutions(1); + mJobScheduler.schedule(deadlineJob); + // Run everything by pretending the device was just plugged in. + sendExpediteStableChargingBroadcast(); + assertTrue("Failed to execute non-deadline job", kTestEnvironment.awaitExecution()); + assertFalse("Job that ran early (unexpired) didn't have" + + " JobParameters#isOverrideDeadlineExpired=false", + kTestEnvironment.getLastJobParameters().isOverrideDeadlineExpired()); + } } \ No newline at end of file
diff --git a/tests/acceleration/Android.mk b/tests/acceleration/Android.mk index a6d6022..f36b64b 100644 --- a/tests/acceleration/Android.mk +++ b/tests/acceleration/Android.mk
@@ -30,4 +30,4 @@ LOCAL_SDK_VERSION := current -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/accessibility/Android.mk b/tests/accessibility/Android.mk index 43fa291..bddbb58 100644 --- a/tests/accessibility/Android.mk +++ b/tests/accessibility/Android.mk
@@ -28,4 +28,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/app/Android.mk b/tests/app/Android.mk index 69bf590..f4f0a13 100644 --- a/tests/app/Android.mk +++ b/tests/app/Android.mk
@@ -23,7 +23,7 @@ LOCAL_PROGUARD_ENABLED := disabled -LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common voip-common +LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common voip-common org.apache.http.legacy LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner ctstestserver @@ -32,4 +32,4 @@ LOCAL_PACKAGE_NAME := CtsAppTestStubs -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/app/AndroidManifest.xml b/tests/app/AndroidManifest.xml index 0d61e20..8d7729e 100644 --- a/tests/app/AndroidManifest.xml +++ b/tests/app/AndroidManifest.xml
@@ -49,6 +49,7 @@ android:name="android.app.cts.MockApplication" android:supportsRtl="true"> <uses-library android:name="android.test.runner" /> + <uses-library android:name="org.apache.http.legacy" android:required="false" /> <activity android:name="android.app.cts.ActionBarActivity" />
diff --git a/tests/core/runner/src/com/android/cts/runner/CtsTestRunListener.java b/tests/core/runner/src/com/android/cts/runner/CtsTestRunListener.java index 7564f32..57dc7c6 100644 --- a/tests/core/runner/src/com/android/cts/runner/CtsTestRunListener.java +++ b/tests/core/runner/src/com/android/cts/runner/CtsTestRunListener.java
@@ -21,6 +21,7 @@ import android.content.Context; import android.content.pm.PackageManager; import android.support.test.internal.runner.listener.InstrumentationRunListener; +import android.text.TextUtils; import android.util.Log; import junit.framework.TestCase; @@ -28,6 +29,7 @@ import org.junit.runner.Description; import org.junit.runner.notification.RunListener; +import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; @@ -119,6 +121,39 @@ Log.d(TAG, "Total memory : " + total); Log.d(TAG, "Used memory : " + used); Log.d(TAG, "Free memory : " + free); + + String tempdir = System.getProperty("java.io.tmpdir", ""); + // TODO: Remove these extra Logs added to debug a specific timeout problem. + Log.d(TAG, "java.io.tmpdir is:" + tempdir); + + if (!TextUtils.isEmpty(tempdir)) { + String[] commands = {"df", tempdir}; + BufferedReader in = null; + try { + Log.d(TAG, "About to .exec df"); + Process proc = runtime.exec(commands); + Log.d(TAG, ".exec returned"); + in = new BufferedReader(new InputStreamReader(proc.getInputStream())); + Log.d(TAG, "Stream reader created"); + String line; + while ((line = in.readLine()) != null) { + Log.d(TAG, line); + } + } catch (IOException e) { + Log.d(TAG, "Exception: " + e.toString()); + // Well, we tried + } finally { + Log.d(TAG, "In finally"); + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // Meh + } + } + } + } + Log.d(TAG, "Now executing : " + testClass.getName()); } @@ -177,8 +212,8 @@ mSslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); mProperties.setProperty("user.home", ""); - mProperties.setProperty("java.io.tmpdir", System.getProperty("java.io.tmpdir")); - // The CDD mandates that devices that support WiFi are the only ones that will have + mProperties.setProperty("java.io.tmpdir", context.getCacheDir().getAbsolutePath()); + // The CDD mandates that devices that support WiFi are the only ones that will have // multicast. PackageManager pm = context.getPackageManager(); mProperties.setProperty("android.cts.device.multicast",
diff --git a/tests/deviceadmin/Android.mk b/tests/deviceadmin/Android.mk index 9ab9cb8..2e89d34 100644 --- a/tests/deviceadmin/Android.mk +++ b/tests/deviceadmin/Android.mk
@@ -30,4 +30,4 @@ LOCAL_DEX_PREOPT := false -include $(BUILD_PACKAGE) +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/deviceadmin/res/xml/device_admin.xml b/tests/deviceadmin/res/xml/device_admin.xml index 263fda6..f7d394e 100644 --- a/tests/deviceadmin/res/xml/device_admin.xml +++ b/tests/deviceadmin/res/xml/device_admin.xml
@@ -22,6 +22,7 @@ <force-lock /> <wipe-data /> <expire-password /> + <disable-keyguard-features /> </uses-policies> </device-admin>
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt index 5057725..fb28d6d 100644 --- a/tests/expectations/knownfailures.txt +++ b/tests/expectations/knownfailures.txt
@@ -1,5 +1,14 @@ [ { + description: "some AlarmClockTests are not robust across different device types", + names: [ + "android.alarmclock.cts.DismissAlarmTest#testAll", + "android.alarmclock.cts.SetAlarmTest#testAll", + "android.alarmclock.cts.SnoozeAlarmTest#testAll" + ], + bug: 23776083 +}, +{ description: "the UsageStats is not yet stable enough", names: [ "android.app.usage.cts.UsageStatsTest" @@ -7,13 +16,6 @@ bug: 17536113 }, { - description: "the ConnectivityConstraintTest are not yet stable", - names: [ - "android.jobscheduler.cts.ConnectivityConstraintTest" - ], - bug: 18117279 -}, -{ description: "tests a fragile by nature as they rely on hardcoded behavior", names: [ "android.accessibilityservice.cts.AccessibilityTextTraversalTest#testActionNextAndPreviousAtGranularityPageOverText", @@ -22,6 +24,21 @@ bug: 17595050 }, { + description: "test fails on devices with no telephony", + names: [ + "android.calllog.cts.CallLogBackupTest#testSingleCallBackup" + ], + bug: 23776099 +}, +{ + description: "test fails on some devices", + names: [ + "android.dumpsys.cts.DumpsysHostTest#testBatterystatsOutput", + "android.dumpsys.cts.DumpsysHostTest#testGfxinfoFramestats" + ], + bug: 23776893 +}, +{ description: "the SSLCertificateSocketFactoryTest often fails because of lack of live internet or short timeout, it should be refactored to do a local server testing", names: [ "android.net.cts.SSLCertificateSocketFactoryTest#testCreateSocket", @@ -46,6 +63,21 @@ bug: 18461670 }, { + description: "test not robust", + names: [ + "android.telecom.cts.ExtendedInCallServiceTest#testAddNewOutgoingCallAndThenDisconnect", + "android.telecom.cts.RemoteConferenceTest#testRemoteConferenceCallbacks_ConferenceableConnections" + ], + bug: 23604254 +}, +{ + description: "tests too flaky", + names: [ + "android.transition.cts.ChangeScrollTest#testChangeScroll" + ], + bug: 23779020 +}, +{ description: "Not all jdwp features are currently supported. These tests will fail", names: [ "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowDebuggerLaunchTest#testDebuggerLaunch001", @@ -76,18 +108,24 @@ bug: 16720689 }, { - description: "Disable WebGL conformance tests in CTS", + description: "test can only run properly on a user build device when the bug is resolved", names: [ - "android.webgl.cts.WebGLTest" + "android.appwidget.cts.AppWidgetTest#testAppWidgetProviderCallbacks", + "android.appwidget.cts.AppWidgetTest#testBindAppWidget", + "android.appwidget.cts.AppWidgetTest#testCollectionWidgets", + "android.appwidget.cts.AppWidgetTest#testDeleteHost", + "android.appwidget.cts.AppWidgetTest#testDeleteHosts", + "android.appwidget.cts.AppWidgetTest#testGetAppWidgetIds", + "android.appwidget.cts.AppWidgetTest#testGetAppWidgetInfo", + "android.appwidget.cts.AppWidgetTest#testGetAppWidgetOptions", + "android.appwidget.cts.AppWidgetTest#testPartiallyUpdateAppWidgetViaWidgetId", + "android.appwidget.cts.AppWidgetTest#testPartiallyUpdateAppWidgetViaWidgetIds", + "android.appwidget.cts.AppWidgetTest#testTwoAppWidgetProviderCallbacks", + "android.appwidget.cts.AppWidgetTest#testUpdateAppWidgetViaComponentName", + "android.appwidget.cts.AppWidgetTest#testUpdateAppWidgetViaWidgetId", + "android.appwidget.cts.AppWidgetTest#testUpdateAppWidgetViaWidgetIds" ], - bug: 20937460 -}, -{ - description: "WebGL test uniformMatrixBadArgs is too strict. Disabled until it's fixed upstream.", - names: [ - "android.webgl.cts.WebGLTest#test_conformance_more_functions_uniformMatrixBadArgs_html" - ], - bug: 18638404 + bug: 17993121 }, { description: "permissions for the API previously used in the test has changed, making it impossible to pass", @@ -120,6 +158,21 @@ bug: 17508787 }, { + description: "This test should be outside of official CTS suite until it is verified for all Nexus devices", + names: [ + "com.android.cts.devicepolicy.MixedDeviceOwnerTest#testPackageInstallUserRestrictions", + "com.android.cts.devicepolicy.MixedProfileOwnerTest#testPackageInstallUserRestrictions" + ], + bug: 18928535 +}, +{ + description: "Test is not yet properly implemented", + names: [ + "android.voicesettings.cts.ZenModeTest#testAll" + ], + bug: 23238984 +}, +{ description: "These tests fail on some devices.", names: [ "android.uirendering.cts.testclasses.ExactCanvasTests#testBlueRect", @@ -140,172 +193,6 @@ bug: 17605875 }, { - description: "Failures on these tests are known on several devices.", - names: [ - "android.hardware.cts.SensorBatchingTests#testAccelerometer_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testAccelerometer_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testAccelerometer_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testAccelerometer_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testMagneticField_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testMagneticField_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testMagneticField_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testMagneticField_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testOrientation_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testOrientation_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testOrientation_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testOrientation_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testGyroscope_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testGyroscope_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testGyroscope_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testGyroscope_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testPressure_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testPressure_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testPressure_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testPressure_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testGravity_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testGravity_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testGravity_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testGravity_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testRotationVector_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testRotationVector_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testRotationVector_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testRotationVector_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testGameRotationVector_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testGameRotationVector_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testGameRotationVector_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testGameRotationVector_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testGyroscopeUncalibrated_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testGyroscopeUncalibrated_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testGyroscopeUncalibrated_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testGyroscopeUncalibrated_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testLinearAcceleration_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testLinearAcceleration_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testLinearAcceleration_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testLinearAcceleration_50hz_flush", - "android.hardware.cts.SensorBatchingTests#testGeomagneticRotationVector_fastest_batching", - "android.hardware.cts.SensorBatchingTests#testGeomagneticRotationVector_50hz_batching", - "android.hardware.cts.SensorBatchingTests#testGeomagneticRotationVector_fastest_flush", - "android.hardware.cts.SensorBatchingTests#testGeomagneticRotationVector_50hz_flush", - "android.hardware.cts.SensorIntegrationTests#testSensorsWithSeveralClients", - "android.hardware.cts.SensorIntegrationTests#testSensorsMovingRates", - "android.hardware.cts.SensorIntegrationTests#testAccelerometerAccelerometerStopping", - "android.hardware.cts.SensorIntegrationTests#testAccelerometerGyroscopeStopping", - "android.hardware.cts.SensorIntegrationTests#testAccelerometerMagneticFieldStopping", - "android.hardware.cts.SensorIntegrationTests#testGyroscopeAccelerometerStopping", - "android.hardware.cts.SensorIntegrationTests#testGyroscopeGyroscopeStopping", - "android.hardware.cts.SensorIntegrationTests#testGyroscopeMagneticFieldStopping", - "android.hardware.cts.SensorIntegrationTests#testMagneticFieldAccelerometerStopping", - "android.hardware.cts.SensorIntegrationTests#testMagneticFieldGyroscopeStopping", - "android.hardware.cts.SensorIntegrationTests#testMagneticFieldMagneticFieldStopping", - "android.hardware.cts.SingleSensorTests#testSensorProperties", - "android.hardware.cts.SingleSensorTests#testAccelerometer_fastest", - "android.hardware.cts.SingleSensorTests#testAccelerometer_100hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_200hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_50hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_25hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_15hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_10hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_5hz", - "android.hardware.cts.SingleSensorTests#testAccelerometer_1hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_fastest", - "android.hardware.cts.SingleSensorTests#testMagneticField_200hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_100hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_50hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_25hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_15hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_10hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_5hz", - "android.hardware.cts.SingleSensorTests#testMagneticField_1hz", - "android.hardware.cts.SingleSensorTests#testOrientation_fastest", - "android.hardware.cts.SingleSensorTests#testOrientation_200hz", - "android.hardware.cts.SingleSensorTests#testOrientation_100hz", - "android.hardware.cts.SingleSensorTests#testOrientation_50hz", - "android.hardware.cts.SingleSensorTests#testOrientation_25hz", - "android.hardware.cts.SingleSensorTests#testOrientation_15hz", - "android.hardware.cts.SingleSensorTests#testOrientation_10hz", - "android.hardware.cts.SingleSensorTests#testOrientation_5hz", - "android.hardware.cts.SingleSensorTests#testOrientation_1hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_fastest", - "android.hardware.cts.SingleSensorTests#testGyroscope_200hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_100hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_50hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_25hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_15hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_10hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_5hz", - "android.hardware.cts.SingleSensorTests#testGyroscope_1hz", - "android.hardware.cts.SingleSensorTests#testPressure_fastest", - "android.hardware.cts.SingleSensorTests#testPressure_200hz", - "android.hardware.cts.SingleSensorTests#testPressure_100hz", - "android.hardware.cts.SingleSensorTests#testPressure_50hz", - "android.hardware.cts.SingleSensorTests#testPressure_25hz", - "android.hardware.cts.SingleSensorTests#testPressure_15hz", - "android.hardware.cts.SingleSensorTests#testPressure_10hz", - "android.hardware.cts.SingleSensorTests#testPressure_5hz", - "android.hardware.cts.SingleSensorTests#testPressure_1hz", - "android.hardware.cts.SingleSensorTests#testGravity_fastest", - "android.hardware.cts.SingleSensorTests#testGravity_200hz", - "android.hardware.cts.SingleSensorTests#testGravity_100hz", - "android.hardware.cts.SingleSensorTests#testGravity_50hz", - "android.hardware.cts.SingleSensorTests#testGravity_25hz", - "android.hardware.cts.SingleSensorTests#testGravity_15hz", - "android.hardware.cts.SingleSensorTests#testGravity_10hz", - "android.hardware.cts.SingleSensorTests#testGravity_5hz", - "android.hardware.cts.SingleSensorTests#testGravity_1hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_fastest", - "android.hardware.cts.SingleSensorTests#testRotationVector_200hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_100hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_50hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_25hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_15hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_10hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_5hz", - "android.hardware.cts.SingleSensorTests#testRotationVector_1hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_fastest", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_200hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_100hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_50hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_25hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_15hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_10hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_5hz", - "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_1hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_fastest", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_200hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_100hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_50hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_25hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_15hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_10hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_5hz", - "android.hardware.cts.SingleSensorTests#testGameRotationVector_1hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_fastest", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_200hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_100hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_50hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_25hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_15hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_10hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_5hz", - "android.hardware.cts.SingleSensorTests#testGyroscopeUncalibrated_1hz", - "android.hardware.cts.SingleSensorTests#testGeomagneticRotationVector_fastest", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_200hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_100hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_50hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_25hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_15hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_10hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_5hz", - "android.hardware.cts.SingleSensorTests#testLinearAcceleration_1hz", - "android.hardware.cts.SensorTest#testSensorTimeStamps" - ], - bug: 17675466 -}, -{ description: "This test failed on hw decoder that doesn't output frame with the configured format.", names: [ "android.media.cts.ImageReaderDecoderTest#testHwAVCDecode360pForFlexibleYuv" @@ -313,13 +200,6 @@ bug: 17144778 }, { - description: "Roboto font tests are not yet known good on all devices", - names: [ - "android.uirendering.cts.testclasses.FontRenderingTests" - ], - bug: 17109280 -}, -{ description: "android.keystore tests will replace these tests", names: [ "com.android.org.conscrypt.MacTest#test_getInstance_OpenSSL_ENGINE", @@ -329,10 +209,111 @@ bug: 18030049 }, { - description: "EventOrderingVerificationTest not working.", + description: "The new recording test is not yet passing on all devices", names: [ - "android.hardware.cts.helpers.sensorverification.EventOrderingVerificationTest#testSameTimestamp" + "android.hardware.camera2.cts.RecordingTest#testRecordingFramerateLowToHigh" ], - bug: 23792027 + bug: 18705837 +}, +{ + description: "The new image reader test is not yet passing on all devices", + names: [ + "android.hardware.camera2.cts.ImageReaderTest#testAllOutputYUVResolutions" + ], + bug: 18689511 +}, +{ + description: "The new prepare performance test is not yet passing on all devices", + names: [ + "android.hardware.camera2.cts.SurfaceViewPreviewTest#testPreparePerformance" + ], + bug: 17989532 +}, +{ + description: "The new AE/AF trigger tests are not yet passing on all devices", + names: [ + "android.hardware.camera2.cts.RobustnessTest#testBasicTriggerSequence", + "android.hardware.camera2.cts.RobustnessTest#testSimultaneousTriggers", + "android.hardware.camera2.cts.RobustnessTest#testAfThenAeTrigger", + "android.hardware.camera2.cts.RobustnessTest#testAeThenAfTrigger" + ], + bug: 22180706 +}, +{ + description: "The new create session test is not yet passing on all devices", + names: [ + "android.hardware.camera2.cts.CameraDeviceTest#testCreateSessions" + ], + bug: 22092756 +}, +{ + description: "The new long processing test is not yet passing on all devices", + names: [ + "android.hardware.camera2.cts.ImageReaderTest#testLongProcessingRepeatingRaw", + "android.hardware.camera2.cts.ImageReaderTest#testLongProcessingRepeatingFlexibleYuv" + ], + bug: 22861512 +}, +{ + description: "The timing measurements for preview callbacks are not reliable", + names: [ + "android.hardware.cts.CameraTest#testPreviewFpsRange" + ], + bug: 23008511 +}, +{ + description: "Light status bar CTS coming in late", + names: [ + "com.android.cts.systemui.LightStatusBarTests#testLightStatusBarIcons" + ], + bug: 23427621 +}, +{ + description: "known failures", + names: [ + "android.hardware.cts.SensorBatchingTests#testAccelerometer_50hz_batching", + "android.hardware.cts.SensorBatchingTests#testAccelerometer_fastest_batching", + "android.hardware.cts.SensorBatchingTests#testGyroscope_50hz_batching", + "android.hardware.cts.SensorBatchingTests#testGyroscope_50hz_flush", + "android.hardware.cts.SensorBatchingTests#testMagneticField_50hz_batching", + "android.hardware.cts.SensorBatchingTests#testMagneticField_fastest_batching", + "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_50hz_batching", + "android.hardware.cts.SensorBatchingTests#testMagneticFieldUncalibrated_fastest_batching", + "android.hardware.cts.SensorBatchingTests#testPressure_50hz_batching", + "android.hardware.cts.SensorBatchingTests#testPressure_fastest_batching", + "android.hardware.cts.SensorBatchingTests#testRotationVector_50hz_flush", + "android.hardware.cts.SensorBatchingTests#testRotationVector_fastest_batching", + "android.hardware.cts.SensorIntegrationTests#testSensorsMovingRates", + "android.hardware.cts.SensorIntegrationTests#testSensorsWithSeveralClients", + "android.hardware.cts.SensorTest#testSensorTimeStamps", + "android.hardware.cts.SensorTest#testBatchAndFlush", + "android.hardware.cts.SingleSensorTests#testGyroscope_15hz", + "android.hardware.cts.SingleSensorTests#testGyroscope_1hz", + "android.hardware.cts.SingleSensorTests#testMagneticField_1hz", + "android.hardware.cts.SingleSensorTests#testMagneticField_50hz", + "android.hardware.cts.SingleSensorTests#testMagneticFieldUncalibrated_200hz", + "android.hardware.cts.SingleSensorTests#testOrientation_5hz" + ], + bug: 22922206 +}, +{ + description: "tests are not yet ready", + names: [ + "com.android.cts.app.os.OsHostTests#testNonExportedActivities" + ], + bug: 23779168 +}, +{ + description: "New assist tests that do not yet have a track record.", + names: [ + "android.assist.cts.AssistantContentViewTest", + "android.assist.cts.ExtraAssistDataTest", + "android.assist.cts.FocusChangeTest", + "android.assist.cts.LargeViewHierarchyTest", + "android.assist.cts.ScreenshotTest", + "android.assist.cts.TextViewTest", + "android.assist.cts.WebViewTest" + ], + bug: 21668302 } ]
diff --git a/tests/leanbackjank/Android.mk b/tests/leanbackjank/Android.mk new file mode 100644 index 0000000..b3adfb1 --- /dev/null +++ b/tests/leanbackjank/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) \ + ./app/src/android/cts/jank/leanback/IntentKeys.java + +LOCAL_PACKAGE_NAME := CtsLeanbackJankTestCases + +LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner ub-uiautomator ub-janktesthelper android-support-v17-leanback + +include $(BUILD_CTS_PACKAGE) + +include $(call all-makefiles-under, $(LOCAL_PATH)) +
diff --git a/tests/leanbackjank/AndroidManifest.xml b/tests/leanbackjank/AndroidManifest.xml new file mode 100644 index 0000000..1cd552d --- /dev/null +++ b/tests/leanbackjank/AndroidManifest.xml
@@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.cts.leanbackjank"> + + <application> + <uses-library android:name="android.test.runner"/> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.cts.leanbackjank" + android:label="Jank tests"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> + +</manifest>
diff --git a/tests/leanbackjank/AndroidTest.xml b/tests/leanbackjank/AndroidTest.xml new file mode 100644 index 0000000..e61c58d --- /dev/null +++ b/tests/leanbackjank/AndroidTest.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="CTS Jank test config"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsLeanbackJank.apk" /> +</configuration>
diff --git a/tests/leanbackjank/app/Android.mk b/tests/leanbackjank/app/Android.mk new file mode 100644 index 0000000..5abe1a7 --- /dev/null +++ b/tests/leanbackjank/app/Android.mk
@@ -0,0 +1,47 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsLeanbackJank + +LOCAL_RESOURCE_DIR := \ + $(TOP)/frameworks/support/v17/leanback/res \ + $(TOP)/frameworks/support/v7/recyclerview/res \ + $(LOCAL_PATH)/res + +LOCAL_STATIC_JAVA_LIBRARIES := \ + ctsdeviceutil \ + ctstestrunner \ + ub-uiautomator \ + ub-janktesthelper \ + android-support-v4 \ + android-support-v7-recyclerview \ + android-support-v17-leanback \ + glide + +LOCAL_AAPT_FLAGS := \ + --auto-add-overlay \ + --extra-packages android.support.v17.leanback \ + --extra-packages android.support.v7.recyclerview + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/leanbackjank/app/AndroidManifest.xml b/tests/leanbackjank/app/AndroidManifest.xml new file mode 100644 index 0000000..333399e --- /dev/null +++ b/tests/leanbackjank/app/AndroidManifest.xml
@@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.cts.jank.leanback" + android:versionCode="1" + android:versionName="1.1" > + + <uses-sdk + android:minSdkVersion="21" + android:targetSdkVersion="23" /> + + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + + <uses-feature + android:name="android.hardware.touchscreen" + android:required="false" /> + + <uses-feature android:name="android.software.leanback" + android:required="true" /> + + <application + android:allowBackup="false" + android:icon="@drawable/videos_by_google_banner" + android:label="@string/app_name" + android:logo="@drawable/videos_by_google_banner" + android:theme="@style/Theme.Example.Leanback" > + <activity + android:name=".ui.MainActivity" + android:icon="@drawable/videos_by_google_banner" + android:label="@string/app_name" + android:logo="@drawable/videos_by_google_banner" + android:screenOrientation="landscape" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LEANBACK_LAUNCHER" /> + </intent-filter> + </activity> + </application> +</manifest>
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum.png b/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum.png new file mode 100644 index 0000000..fda9a74 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum_card.png b/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum_card.png new file mode 100644 index 0000000..498cf66 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/app_icon_quantum_card.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/ic_launcher.png b/tests/leanbackjank/app/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 0000000..96a442e --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/ic_launcher.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/ic_main_icon.png b/tests/leanbackjank/app/res/drawable-hdpi/ic_main_icon.png new file mode 100644 index 0000000..6f0c962 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/ic_main_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_banner.png b/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_banner.png new file mode 100644 index 0000000..4cedb52 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_banner.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_icon.png b/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_icon.png new file mode 100644 index 0000000..20fd898 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-hdpi/videos_by_google_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-ldpi/ic_launcher.png b/tests/leanbackjank/app/res/drawable-ldpi/ic_launcher.png new file mode 100644 index 0000000..9923872 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-ldpi/ic_launcher.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum.png b/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum.png new file mode 100644 index 0000000..6b62138 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum_card.png b/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum_card.png new file mode 100644 index 0000000..ac9cc30 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/app_icon_quantum_card.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/ic_launcher.png b/tests/leanbackjank/app/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 0000000..359047d --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/ic_launcher.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/ic_main_icon.png b/tests/leanbackjank/app/res/drawable-mdpi/ic_main_icon.png new file mode 100644 index 0000000..e9effc8 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/ic_main_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_banner.png b/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_banner.png new file mode 100644 index 0000000..b191626 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_banner.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_icon.png b/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_icon.png new file mode 100644 index 0000000..8a7c6dc --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-mdpi/videos_by_google_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum.png b/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum.png new file mode 100644 index 0000000..825ef63 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum_card.png b/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum_card.png new file mode 100644 index 0000000..9b1703d --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/app_icon_quantum_card.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/bg.png b/tests/leanbackjank/app/res/drawable-xhdpi/bg.png new file mode 100644 index 0000000..476c698 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/bg.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/card_background_default.9.png b/tests/leanbackjank/app/res/drawable-xhdpi/card_background_default.9.png new file mode 100644 index 0000000..29f4e01 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/card_background_default.9.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/default_background.xml b/tests/leanbackjank/app/res/drawable-xhdpi/default_background.xml new file mode 100644 index 0000000..07b0589 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/default_background.xml
@@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> + +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <gradient + android:startColor="@color/background_gradient_start" + android:endColor="@color/background_gradient_end" + android:angle="-270" /> +</shape> \ No newline at end of file
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/grid_bg.png b/tests/leanbackjank/app/res/drawable-xhdpi/grid_bg.png new file mode 100644 index 0000000..476c698 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/grid_bg.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/ic_launcher.png b/tests/leanbackjank/app/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 0000000..71c6d76 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/ic_launcher.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/ic_main_icon.png b/tests/leanbackjank/app/res/drawable-xhdpi/ic_main_icon.png new file mode 100644 index 0000000..2e56516 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/ic_main_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/shadow7.9.png b/tests/leanbackjank/app/res/drawable-xhdpi/shadow7.9.png new file mode 100644 index 0000000..6d00d09 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/shadow7.9.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_banner.png b/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_banner.png new file mode 100644 index 0000000..bdcf41e --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_banner.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_icon.png b/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_icon.png new file mode 100644 index 0000000..9bc4836 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xhdpi/videos_by_google_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum.png b/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum.png new file mode 100644 index 0000000..c82f94c --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum_card.png b/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum_card.png new file mode 100644 index 0000000..6c50e8f --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xxhdpi/app_icon_quantum_card.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_banner.png b/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_banner.png new file mode 100644 index 0000000..6c121e6 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_banner.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_icon.png b/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_icon.png new file mode 100644 index 0000000..4258160e --- /dev/null +++ b/tests/leanbackjank/app/res/drawable-xxhdpi/videos_by_google_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/android_header.png b/tests/leanbackjank/app/res/drawable/android_header.png new file mode 100644 index 0000000..56206ec --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/android_header.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/app_icon_quantum.png b/tests/leanbackjank/app/res/drawable/app_icon_quantum.png new file mode 100644 index 0000000..fda9a74 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/app_icon_quantum.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/app_icon_quantum_card.png b/tests/leanbackjank/app/res/drawable/app_icon_quantum_card.png new file mode 100644 index 0000000..498cf66 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/app_icon_quantum_card.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/gradation.png b/tests/leanbackjank/app/res/drawable/gradation.png new file mode 100644 index 0000000..ba43a90 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/gradation.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/ic_action_a.png b/tests/leanbackjank/app/res/drawable/ic_action_a.png new file mode 100644 index 0000000..3d555ef --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/ic_action_a.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/ic_title.png b/tests/leanbackjank/app/res/drawable/ic_title.png new file mode 100644 index 0000000..1c62b2e --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/ic_title.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/movie.png b/tests/leanbackjank/app/res/drawable/movie.png new file mode 100644 index 0000000..cb5cb6d --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/movie.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/player_bg_gradient_dark.xml b/tests/leanbackjank/app/res/drawable/player_bg_gradient_dark.xml new file mode 100644 index 0000000..4450cb6 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/player_bg_gradient_dark.xml
@@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<shape xmlns:android="http://schemas.android.com/apk/res/android" > + + <gradient + android:angle="90" + android:centerColor="#00000000" + android:endColor="#B2000000" + android:startColor="#B2000000" + android:type="linear" /> + +</shape> \ No newline at end of file
diff --git a/tests/leanbackjank/app/res/drawable/shadow7.9.png b/tests/leanbackjank/app/res/drawable/shadow7.9.png new file mode 100644 index 0000000..6d00d09 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/shadow7.9.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/text_bg.xml b/tests/leanbackjank/app/res/drawable/text_bg.xml new file mode 100644 index 0000000..43fbeaf --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/text_bg.xml
@@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> + +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <gradient + android:startColor="#FFFF0000" + android:endColor="#FFFF00FF" + android:angle="45" /> + <padding + android:left="7dp" + android:top="7dp" + android:right="7dp" + android:bottom="7dp" /> + <size + android:height="160dp" + android:width="100dp" /> +</shape>
diff --git a/tests/leanbackjank/app/res/drawable/videos_by_google_banner.png b/tests/leanbackjank/app/res/drawable/videos_by_google_banner.png new file mode 100644 index 0000000..4cedb52 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/videos_by_google_banner.png Binary files differ
diff --git a/tests/leanbackjank/app/res/drawable/videos_by_google_icon.png b/tests/leanbackjank/app/res/drawable/videos_by_google_icon.png new file mode 100644 index 0000000..20fd898 --- /dev/null +++ b/tests/leanbackjank/app/res/drawable/videos_by_google_icon.png Binary files differ
diff --git a/tests/leanbackjank/app/res/layout/icon_header_item.xml b/tests/leanbackjank/app/res/layout/icon_header_item.xml new file mode 100644 index 0000000..586881d --- /dev/null +++ b/tests/leanbackjank/app/res/layout/icon_header_item.xml
@@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> +<android.support.v17.leanback.widget.NonOverlappingLinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <ImageView + android:id="@+id/header_icon" + android:layout_width="32dp" + android:layout_height="32dp" /> + + <TextView + android:id="@+id/header_label" + android:layout_marginTop="6dp" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> +</android.support.v17.leanback.widget.NonOverlappingLinearLayout>
diff --git a/tests/leanbackjank/app/res/layout/main.xml b/tests/leanbackjank/app/res/layout/main.xml new file mode 100644 index 0000000..7a83b69 --- /dev/null +++ b/tests/leanbackjank/app/res/layout/main.xml
@@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> + +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/main_frame" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <fragment + android:name="android.cts.jank.leanback.ui.MainFragment" + android:id="@+id/main_browse_fragment" + android:layout_width="match_parent" + android:layout_height="match_parent" /> + +</FrameLayout>
diff --git a/tests/leanbackjank/app/res/layout/movie_card.xml b/tests/leanbackjank/app/res/layout/movie_card.xml new file mode 100644 index 0000000..c63841d --- /dev/null +++ b/tests/leanbackjank/app/res/layout/movie_card.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> + +<android.support.v17.leanback.widget.NonOverlappingLinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:scaleType="centerCrop" + android:focusable="true" + android:focusableInTouchMode="true"> + <ImageView + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:id="@+id/poster" android:layout_gravity="center"/> + <TextView + android:id="@+id/poster_text" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:paddingTop="10dp" + android:paddingRight="10dp" + android:paddingBottom="10dp" + android:paddingLeft="10dp" /> +</android.support.v17.leanback.widget.NonOverlappingLinearLayout> \ No newline at end of file
diff --git a/tests/leanbackjank/app/res/values/colors.xml b/tests/leanbackjank/app/res/values/colors.xml new file mode 100644 index 0000000..7e246ed --- /dev/null +++ b/tests/leanbackjank/app/res/values/colors.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="background_gradient_start">#000000</color> + <color name="background_gradient_end">#DDDDDD</color> + <color name="fastlane_background">#0096a6</color> + <color name="search_opaque">#ffaa3f</color> + <color name="selected_background">#ffaa3f</color> + <color name="soft_opaque">#30000000</color> + <color name="img_soft_opaque">#30FF0000</color> + <color name="img_full_opaque">#00000000</color> + <color name="black_opaque">#AA000000</color> + <color name="black">#59000000</color> + <color name="white">#FFFFFF</color> + <color name="orange_transparent">#AAFADCA7</color> + <color name="orange">#FADCA7</color> + <color name="yellow">#EEFF41</color> + <color name="default_background">#0096a6</color> + <color name="icon_background">#4A4F51</color> + <color name="icon_alt_background">#2A2F51</color> +</resources> \ No newline at end of file
diff --git a/tests/leanbackjank/app/res/values/strings.xml b/tests/leanbackjank/app/res/values/strings.xml new file mode 100644 index 0000000..17edf95 --- /dev/null +++ b/tests/leanbackjank/app/res/values/strings.xml
@@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright (C) 2015 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. +--> + +<resources> + <string name="app_name"><![CDATA[Leanback launcher jank test application]]></string> + <string name="browse_title"><![CDATA[Leanback launcher jank test application]]></string> + <string name="error">Error</string> + <string name="ok">OK</string> + <string name="grid_item_template">Item %1$d</string> + <string name="settings">Settings</string> + + <!-- Error messages --> + <string name="error_fragment_message">An error occurred</string> + <string name="dismiss_error">Dismiss</string> +</resources>
diff --git a/tests/leanbackjank/app/res/values/themes.xml b/tests/leanbackjank/app/res/values/themes.xml new file mode 100644 index 0000000..4a1e06d --- /dev/null +++ b/tests/leanbackjank/app/res/values/themes.xml
@@ -0,0 +1,15 @@ +<resources> + <style name="Theme.Example.Leanback" parent="Theme.Leanback"> + <item name="android:colorPrimary">@color/search_opaque</item> + <item name="android:windowEnterTransition">@android:transition/fade</item> + <item name="android:windowExitTransition">@android:transition/fade</item> + <item name="android:windowSharedElementExitTransition">@android:transition/move</item> + <item name="android:windowSharedElementEnterTransition">@android:transition/move</item> + <!-- Set to display colorPrimary when apps launches --> + <item name="android:windowAllowReturnTransitionOverlap">true</item> + <item name="android:windowAllowEnterTransitionOverlap">false</item> + <item name="android:windowContentTransitions">true</item> + </style> + <style name="Widget.Example.Leanback.Title.Text" parent="Widget.Leanback.Title.Text" > + </style> +</resources>
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/IntentKeys.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/IntentKeys.java new file mode 100644 index 0000000..e9c5e6e --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/IntentKeys.java
@@ -0,0 +1,10 @@ +package android.cts.jank.leanback; + +/** + * Intent key strings of the leanback jank test helper app. + */ +public class IntentKeys { + public static final String SCROLL_COUNT = "SCROLL_COUNT"; + public static final String SCROLL_DELAY = "SCROLL_DELAY"; + public static final String SCROLL_INTERVAL = "SCROLL_INTERVAL"; +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/Utils.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/Utils.java new file mode 100644 index 0000000..de6d6af --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/Utils.java
@@ -0,0 +1,112 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Point; +import android.media.MediaMetadataRetriever; +import android.os.Build; +import android.util.DisplayMetrics; +import android.view.Display; +import android.view.WindowManager; +import android.widget.FrameLayout; +import android.widget.Toast; +import android.widget.VideoView; + +import java.util.HashMap; + +/** + * A collection of utility methods, all static. + */ +public class Utils { + + public interface MediaDimensions { + double MEDIA_HEIGHT = 0.95; + double MEDIA_WIDTH = 0.95; + double MEDIA_TOP_MARGIN = 0.025; + double MEDIA_RIGHT_MARGIN = 0.025; + double MEDIA_BOTTOM_MARGIN = 0.025; + double MEDIA_LEFT_MARGIN = 0.025; + } + + /* + * Making sure public utility methods remain static + */ + private Utils() { + } + + /** + * Returns the screen/display size + */ + public static Point getDisplaySize(Context context) { + WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + Display display = wm.getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + return size; + } + + /** + * Shows a (long) toast + */ + public static void showToast(Context context, String msg) { + Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); + } + + /** + * Shows a (long) toast. + */ + public static void showToast(Context context, int resourceId) { + Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show(); + } + + public static int convertDpToPixel(Context ctx, int dp) { + float density = ctx.getResources().getDisplayMetrics().density; + return Math.round((float) dp * density); + } + + + /** + * Example for handling resizing content for overscan. Typically you won't need to resize + * when using the Leanback support library. + */ + public void overScan(Activity activity, VideoView videoView) { + DisplayMetrics metrics = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); + int w = (int) (metrics.widthPixels * MediaDimensions.MEDIA_WIDTH); + int h = (int) (metrics.heightPixels * MediaDimensions.MEDIA_HEIGHT); + int marginLeft = (int) (metrics.widthPixels * MediaDimensions.MEDIA_LEFT_MARGIN); + int marginTop = (int) (metrics.heightPixels * MediaDimensions.MEDIA_TOP_MARGIN); + int marginRight = (int) (metrics.widthPixels * MediaDimensions.MEDIA_RIGHT_MARGIN); + int marginBottom = (int) (metrics.heightPixels * MediaDimensions.MEDIA_BOTTOM_MARGIN); + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(w, h); + lp.setMargins(marginLeft, marginTop, marginRight, marginBottom); + videoView.setLayoutParams(lp); + } + + + public static long getDuration(String videoUrl) { + MediaMetadataRetriever mmr = new MediaMetadataRetriever(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + mmr.setDataSource(videoUrl, new HashMap<String, String>()); + } else { + mmr.setDataSource(videoUrl); + } + return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); + } +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/data/VideoProvider.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/data/VideoProvider.java new file mode 100644 index 0000000..fa317ed --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/data/VideoProvider.java
@@ -0,0 +1,79 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.data; + +import android.cts.jank.leanback.model.Movie; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Provides synthesized movie data. + */ +public class VideoProvider { + private static HashMap<String, List<Movie>> sMovieList; + private static HashMap<String, Movie> sMovieListById; + + public static Movie getMovieById(String mediaId) { + return sMovieListById.get(mediaId); + } + + public static HashMap<String, List<Movie>> getMovieList() { + return sMovieList; + } + + public static HashMap<String, List<Movie>> buildMedia(int nCategories) { + if (null != sMovieList) { + return sMovieList; + } + sMovieList = new HashMap<>(); + sMovieListById = new HashMap<>(); + + String title = new String(); + String studio = new String(); + for (int i = 0; i < nCategories; i++) { + String category_name = String.format("Category %d", i); + List<Movie> categoryList = new ArrayList<Movie>(); + for (int j = 0; j < 20; j++) { + String description = "This is description of a movie."; + title = String.format("Video %d-%d", i, j); + studio = String.format("Studio %d", (i + j) % 7); + Movie movie = buildMovieInfo(category_name, title, description, studio); + sMovieListById.put(movie.getId(), movie); + categoryList.add(movie); + } + sMovieList.put(category_name, categoryList); + } + return sMovieList; + } + + private static Movie buildMovieInfo(String category, + String title, + String description, + String studio) { + Movie movie = new Movie(); + movie.setId(Movie.getCount()); + Movie.incrementCount(); + movie.setTitle(title); + movie.setDescription(description); + movie.setStudio(studio); + movie.setCategory(category); + + return movie; + } +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/model/Movie.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/model/Movie.java new file mode 100644 index 0000000..874bb00 --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/model/Movie.java
@@ -0,0 +1,129 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.model; + +import android.os.Parcel; +import android.os.Parcelable; + +/** + * Movie class represents video entity with title, description, image thumbs and video url. + */ +public class Movie implements Parcelable { + static final long serialVersionUID = 727566175075960653L; + private static int sCount = 0; + private String mId; + private String mTitle; + private String mDescription; + private String mStudio; + private String mCategory; + + public Movie() { + } + + public Movie(Parcel in){ + String[] data = new String[5]; + + in.readStringArray(data); + mId = data[0]; + mTitle = data[1]; + mDescription = data[2]; + mStudio = data[3]; + mCategory = data[4]; + } + + public static String getCount() { + return Integer.toString(sCount); + } + + public static void incrementCount() { + sCount++; + } + + public String getId() { + return mId; + } + + public void setId(String id) { + mId = id; + } + + public String getTitle() { + return mTitle; + } + + public void setTitle(String title) { + mTitle = title; + } + + public String getDescription() { + return mDescription; + } + + public void setDescription(String description) { + mDescription = description; + } + + public String getStudio() { + return mStudio; + } + + public void setStudio(String studio) { + mStudio = studio; + } + + public String getCategory() { + return mCategory; + } + + public void setCategory(String category) { + mCategory = category; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeStringArray(new String[] {mId, + mTitle, + mDescription, + mStudio, + mCategory}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(200); + sb.append("Movie{"); + sb.append("mId=" + mId); + sb.append(", mTitle='" + mTitle + '\''); + sb.append('}'); + return sb.toString(); + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Movie createFromParcel(Parcel in) { + return new Movie(in); + } + + public Movie[] newArray(int size) { + return new Movie[size]; + } + }; +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/CardPresenter.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/CardPresenter.java new file mode 100644 index 0000000..9f425ca --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/CardPresenter.java
@@ -0,0 +1,90 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.presenter; + +import android.graphics.drawable.Drawable; +import android.support.v17.leanback.widget.ImageCardView; +import android.support.v17.leanback.widget.Presenter; +import android.view.ViewGroup; + +import com.bumptech.glide.Glide; +import android.cts.jank.leanback.R; +import android.cts.jank.leanback.model.Movie; + +/** + * A CardPresenter is used to generate Views and bind Objects to them on demand. + * It contains an Image CardView + */ +public class CardPresenter extends Presenter { + private static int CARD_WIDTH = 313; + private static int CARD_HEIGHT = 176; + private static int sSelectedBackgroundColor; + private static int sDefaultBackgroundColor; + private Drawable mDefaultCardImage; + + @Override + public ViewHolder onCreateViewHolder(ViewGroup parent) { + sDefaultBackgroundColor = parent.getResources().getColor(R.color.default_background, null); + sSelectedBackgroundColor = + parent.getResources().getColor(R.color.selected_background, null); + mDefaultCardImage = parent.getResources().getDrawable(R.drawable.movie, null); + + ImageCardView cardView = new ImageCardView(parent.getContext()) { + @Override + public void setSelected(boolean selected) { + updateCardBackgroundColor(this, selected); + super.setSelected(selected); + } + }; + + cardView.setFocusable(true); + cardView.setFocusableInTouchMode(true); + updateCardBackgroundColor(cardView, false); + return new ViewHolder(cardView); + } + + private static void updateCardBackgroundColor(ImageCardView view, boolean selected) { + int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor; + // Both background colors should be set because the view's background is temporarily visible + // during animations. + view.setBackgroundColor(color); + view.findViewById(R.id.info_field).setBackgroundColor(color); + } + + @Override + public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { + Movie movie = (Movie) item; + ImageCardView cardView = (ImageCardView) viewHolder.view; + + cardView.setTitleText(movie.getTitle()); + cardView.setContentText(movie.getStudio()); + cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT); + Glide.with(viewHolder.view.getContext()) + .load(R.drawable.gradation) + .centerCrop() + .error(mDefaultCardImage) + .into(cardView.getMainImageView()); + } + + @Override + public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { + ImageCardView cardView = (ImageCardView) viewHolder.view; + // Remove references to images so that the garbage collector can free up memory + cardView.setBadgeImage(null); + cardView.setMainImage(null); + } +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/GridItemPresenter.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/GridItemPresenter.java new file mode 100644 index 0000000..4084383 --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/GridItemPresenter.java
@@ -0,0 +1,59 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.presenter; + +import android.graphics.Color; +import android.support.v17.leanback.widget.Presenter; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.TextView; + +import android.cts.jank.leanback.R; +import android.cts.jank.leanback.ui.MainFragment; + +public class GridItemPresenter extends Presenter { + private static int GRID_ITEM_WIDTH = 200; + private static int GRID_ITEM_HEIGHT = 200; + + private MainFragment mainFragment; + + public GridItemPresenter(MainFragment mainFragment) { + this.mainFragment = mainFragment; + } + + @Override + public ViewHolder onCreateViewHolder(ViewGroup parent) { + TextView view = new TextView(parent.getContext()); + view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT)); + view.setFocusable(true); + view.setFocusableInTouchMode(true); + view.setBackgroundColor( + mainFragment.getResources().getColor(R.color.default_background, null)); + view.setTextColor(Color.WHITE); + view.setGravity(Gravity.CENTER); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(ViewHolder viewHolder, Object item) { + ((TextView) viewHolder.view).setText((String) item); + } + + @Override + public void onUnbindViewHolder(ViewHolder viewHolder) { + } +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/IconHeaderItemPresenter.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/IconHeaderItemPresenter.java new file mode 100644 index 0000000..42e4c0c --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/presenter/IconHeaderItemPresenter.java
@@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.presenter; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.support.v17.leanback.widget.HeaderItem; +import android.support.v17.leanback.widget.ListRow; +import android.support.v17.leanback.widget.Presenter; +import android.support.v17.leanback.widget.RowHeaderPresenter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import android.cts.jank.leanback.R; + +public class IconHeaderItemPresenter extends RowHeaderPresenter { + private float mUnselectedAlpha; + + @Override + public ViewHolder onCreateViewHolder(ViewGroup viewGroup) { + mUnselectedAlpha = viewGroup.getResources() + .getFraction(R.fraction.lb_browse_header_unselect_alpha, 1, 1); + LayoutInflater inflater = (LayoutInflater) viewGroup.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + View view = inflater.inflate(R.layout.icon_header_item, null); + + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object o) { + HeaderItem headerItem = ((ListRow) o).getHeaderItem(); + View rootView = viewHolder.view; + + ImageView iconView = (ImageView) rootView.findViewById(R.id.header_icon); + Drawable icon = rootView.getResources().getDrawable(R.drawable.android_header, null); + iconView.setImageDrawable(icon); + + TextView label = (TextView) rootView.findViewById(R.id.header_label); + label.setText(headerItem.getName()); + } + + @Override + public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { + } + + // TODO: TEMP - remove me when leanback onCreateViewHolder no longer sets the mUnselectAlpha,AND + // also assumes the xml inflation will return a RowHeaderView + @Override + protected void onSelectLevelChanged(RowHeaderPresenter.ViewHolder holder) { + // this is a temporary fix + holder.view.setAlpha(mUnselectedAlpha + holder.getSelectLevel() * + (1.0f - mUnselectedAlpha)); + } +} \ No newline at end of file
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainActivity.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainActivity.java new file mode 100644 index 0000000..fb27fa1 --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainActivity.java
@@ -0,0 +1,35 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.ui; + +import android.app.Activity; +import android.os.Bundle; +import android.cts.jank.leanback.R; + +/** + * MainActivity class that loads MainFragment + */ +public class MainActivity extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + } + + @Override + public boolean onSearchRequested() { + return false; + } +}
diff --git a/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainFragment.java b/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainFragment.java new file mode 100644 index 0000000..e645f6b --- /dev/null +++ b/tests/leanbackjank/app/src/android/cts/jank/leanback/ui/MainFragment.java
@@ -0,0 +1,193 @@ +/* + * Copyright (C) 2015 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 android.cts.jank.leanback.ui; + +import android.content.Intent; +import android.content.res.Resources.Theme; +import android.cts.jank.leanback.IntentKeys; +import android.cts.jank.leanback.R; +import android.cts.jank.leanback.data.VideoProvider; +import android.cts.jank.leanback.model.Movie; +import android.cts.jank.leanback.presenter.CardPresenter; +import android.cts.jank.leanback.presenter.GridItemPresenter; +import android.cts.jank.leanback.presenter.IconHeaderItemPresenter; +import android.os.Bundle; +import android.os.Handler; +import android.support.v17.leanback.app.BackgroundManager; +import android.support.v17.leanback.app.BrowseFragment; +import android.support.v17.leanback.widget.ArrayObjectAdapter; +import android.support.v17.leanback.widget.HeaderItem; +import android.support.v17.leanback.widget.ListRow; +import android.support.v17.leanback.widget.ListRowPresenter; +import android.support.v17.leanback.widget.Presenter; +import android.support.v17.leanback.widget.PresenterSelector; +import android.util.DisplayMetrics; +import android.view.View; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; + +/** + * Main class to show BrowseFragment with header and rows of videos + */ +public class MainFragment extends BrowseFragment { + private static final int NUM_ROWS = 20; + private final Handler mHandler = new Handler(); + private Timer mAutoScrollTimer; + private int mAutoScrollCount; + + private ArrayObjectAdapter mRowsAdapter; + private DisplayMetrics mMetrics; + private BackgroundManager mBackgroundManager; + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + buildRowAdapterItems(VideoProvider.buildMedia(NUM_ROWS)); + prepareBackgroundManager(); + setupUIElements(); + setupEventListeners(); + Intent intent = getActivity().getIntent(); + if (intent.getExtras() != null) { + int initialDelay = intent.getExtras().getInt(IntentKeys.SCROLL_DELAY); + int scrollCount = intent.getExtras().getInt(IntentKeys.SCROLL_COUNT); + int scrollInterval = intent.getExtras().getInt(IntentKeys.SCROLL_INTERVAL); + if (scrollInterval != 0 && scrollCount != 0) { + startAutoScrollTimer(initialDelay, scrollInterval, scrollCount); + } + } + } + + @Override + public void onDestroy() { + if (null != mAutoScrollTimer) { + mAutoScrollTimer.cancel(); + mAutoScrollTimer = null; + } + super.onDestroy(); + } + + @Override + public void onStop() { + mBackgroundManager.release(); + super.onStop(); + } + + private void prepareBackgroundManager() { + mBackgroundManager = BackgroundManager.getInstance(getActivity()); + mBackgroundManager.attach(getActivity().getWindow()); + mBackgroundManager.setDrawable(getActivity().getResources().getDrawable( + R.drawable.default_background, getContext().getTheme())); + mMetrics = new DisplayMetrics(); + getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics); + } + + private void setupUIElements() { + setBadgeDrawable(getActivity().getResources().getDrawable( + R.drawable.videos_by_google_banner, getContext().getTheme())); + setTitle(getString(R.string.browse_title)); + setHeadersState(HEADERS_ENABLED); + setHeadersTransitionOnBackEnabled(true); + + Theme theme = getContext().getTheme(); + setBrandColor(getResources().getColor(R.color.fastlane_background, theme)); + + setSearchAffordanceColor(getResources().getColor(R.color.search_opaque, theme)); + + setHeaderPresenterSelector(new PresenterSelector() { + @Override + public Presenter getPresenter(Object o) { + return new IconHeaderItemPresenter(); + } + }); + } + + private void setupEventListeners() { + // Add lister to show the search button. + setOnSearchClickedListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + } + }); + } + + public void buildRowAdapterItems(HashMap<String, List<Movie>> data) { + mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); + CardPresenter cardPresenter = new CardPresenter(); + + int i = 0; + + for (Map.Entry<String, List<Movie>> entry : data.entrySet()) { + ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter); + List<Movie> list = entry.getValue(); + + for (int j = 0; j < list.size(); j++) { + listRowAdapter.add(list.get(j)); + } + HeaderItem header = new HeaderItem(i, entry.getKey()); + i++; + mRowsAdapter.add(new ListRow(header, listRowAdapter)); + } + + HeaderItem gridHeader = new HeaderItem(i, getString(R.string.settings)); + + GridItemPresenter gridPresenter = new GridItemPresenter(this); + ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(gridPresenter); + for (int j = 0; j < 10; j++) { + gridRowAdapter.add(getString(R.string.grid_item_template, j)); + } + mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter)); + + setAdapter(mRowsAdapter); + } + + private class UpdateAutoScrollTask extends TimerTask { + @Override + public void run() { + mHandler.post(new Runnable() { + @Override + public void run() { + if (mAutoScrollCount == 0) { + mAutoScrollTimer.cancel(); + return; + } + if (mAutoScrollCount % 2 == 0) { + setSelectedPosition(NUM_ROWS - 1); + } else { + setSelectedPosition(0); + } + mAutoScrollCount--; + } + }); + } + } + + private void startAutoScrollTimer(int initialDelay, int interval, int count) { + if (null != mAutoScrollTimer) { + mAutoScrollTimer.cancel(); + } + mAutoScrollCount = count; + mAutoScrollTimer = new Timer(); + mAutoScrollTimer.schedule(new UpdateAutoScrollTask(), initialDelay, interval); + } + + public void selectRow(int row) { + setSelectedPosition(row); + } +}
diff --git a/tests/leanbackjank/src/android/cts/leanbackjank/CtsDeviceLeanback.java b/tests/leanbackjank/src/android/cts/leanbackjank/CtsDeviceLeanback.java new file mode 100644 index 0000000..241535e --- /dev/null +++ b/tests/leanbackjank/src/android/cts/leanbackjank/CtsDeviceLeanback.java
@@ -0,0 +1,98 @@ +/* + * Copyright (C) 2015 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 android.cts.leanbackjank; + +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.cts.jank.leanback.IntentKeys; +import android.os.SystemClock; +import android.support.test.jank.GfxMonitor; +import android.support.test.jank.JankTest; +import android.support.test.jank.WindowContentFrameStatsMonitor; +import android.support.test.uiautomator.By; +import android.support.test.uiautomator.Until; +import android.util.Log; + +public class CtsDeviceLeanback extends CtsJankTestBase { + private static final String TAG = "CtsDeviceLeanback"; + private static final int MILLIS_PER_SECOND = 1000; + private static final long WAIT_TIMEOUT = 5 * MILLIS_PER_SECOND; + private static final int SCROLL_COUNT = 100; + private static final int SCROLL_INTERVAL_MILLIS = 200; + private static final int PRE_SCROLL_DELAY_MILLIS = 0; + private static final int PRE_SCROLL_IDLE_TIME = 2 * MILLIS_PER_SECOND; + private static final int SAMPLING_DURATION_SECONDS = 3; + private static final int SAMPLING_DURATION_MILLIS = + SAMPLING_DURATION_SECONDS * MILLIS_PER_SECOND; + private final static String APP_PACKAGE = "android.cts.jank.leanback"; + private final static String JAVA_PACKAGE = "android.cts.jank.leanback.ui"; + private final static String CLASS = JAVA_PACKAGE + ".MainActivity"; + + private boolean shouldSkip() { + PackageManager packageManager = + getInstrumentation().getTargetContext().getPackageManager(); + if (!packageManager.hasSystemFeature( + PackageManager.FEATURE_LEANBACK)) { + return true; + } + return false; + } + + @Override + protected void runTest() throws Throwable { + if (shouldSkip()) { + return; + } + super.runTest(); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + if (shouldSkip()) { + return; + } + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setComponent(new ComponentName(APP_PACKAGE, CLASS)); + + // Trigger automated scroll of the helper app. + intent.putExtra(IntentKeys.SCROLL_DELAY, PRE_SCROLL_DELAY_MILLIS); + intent.putExtra(IntentKeys.SCROLL_COUNT, SCROLL_COUNT); + intent.putExtra(IntentKeys.SCROLL_INTERVAL, SCROLL_INTERVAL_MILLIS); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getInstrumentation().getTargetContext().startActivity(intent); + if (!getUiDevice().wait(Until.hasObject(By.pkg(APP_PACKAGE)), WAIT_TIMEOUT)) { + fail("Test helper app package not found on device"); + } + + // Wait until scroll animation starts. + SystemClock.sleep(PRE_SCROLL_IDLE_TIME); + } + + @Override + protected void tearDown() throws Exception { + getUiDevice().pressHome(); + super.tearDown(); + } + + // Requires at least 30 fps on average to pass the test. + @JankTest(expectedFrames = 30 * SAMPLING_DURATION_SECONDS, defaultIterationCount = 2) + @GfxMonitor(processName = APP_PACKAGE) + @WindowContentFrameStatsMonitor + public void testScrollingByTimer() { + SystemClock.sleep(SAMPLING_DURATION_MILLIS); + } +}
diff --git a/tests/leanbackjank/src/android/cts/leanbackjank/CtsJankTestBase.java b/tests/leanbackjank/src/android/cts/leanbackjank/CtsJankTestBase.java new file mode 100644 index 0000000..4de0702 --- /dev/null +++ b/tests/leanbackjank/src/android/cts/leanbackjank/CtsJankTestBase.java
@@ -0,0 +1,104 @@ +/* + * Copyright (C) 2015 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 android.cts.leanbackjank; + +import android.cts.util.DeviceReportLog; +import android.os.Bundle; +import android.support.test.jank.GfxMonitor; +import android.support.test.jank.JankTestBase; +import android.support.test.jank.WindowContentFrameStatsMonitor; +import android.support.test.uiautomator.UiDevice; + +import com.android.cts.util.ResultType; +import com.android.cts.util.ResultUnit; + +public abstract class CtsJankTestBase extends JankTestBase { + + private UiDevice mDevice; + private DeviceReportLog mLog; + + private void printIntValueWithKey(String source, Bundle metrics, String key, + ResultType resultType, ResultUnit resultUnit) { + if (!metrics.containsKey(key)) { + return; + } + mLog.printValue(source, key, metrics.getInt(key), resultType, resultUnit); + } + + private void printDoubleValueWithKey(String source, Bundle metrics, String key, + ResultType resultType, ResultUnit resultUnit) { + if (!metrics.containsKey(key)) { + return; + } + mLog.printValue(source, key, metrics.getDouble(key), resultType, resultUnit); + } + + @Override + public void afterTest(Bundle metrics) { + String source = String.format("%s#%s", getClass().getCanonicalName(), getName()); + printDoubleValueWithKey(source, metrics, WindowContentFrameStatsMonitor.KEY_AVG_FPS, + ResultType.HIGHER_BETTER, ResultUnit.FPS); + printDoubleValueWithKey(source, metrics, + WindowContentFrameStatsMonitor.KEY_AVG_LONGEST_FRAME, + ResultType.LOWER_BETTER, ResultUnit.MS); + printIntValueWithKey(source, metrics, WindowContentFrameStatsMonitor.KEY_MAX_NUM_JANKY, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + mLog.printSummary(WindowContentFrameStatsMonitor.KEY_AVG_NUM_JANKY, + metrics.getDouble(WindowContentFrameStatsMonitor.KEY_AVG_NUM_JANKY), + ResultType.LOWER_BETTER, ResultUnit.COUNT); + + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_NUM_JANKY, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_FRAME_TIME_90TH_PERCENTILE, + ResultType.LOWER_BETTER, ResultUnit.MS); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_FRAME_TIME_95TH_PERCENTILE, + ResultType.LOWER_BETTER, ResultUnit.MS); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_FRAME_TIME_99TH_PERCENTILE, + ResultType.LOWER_BETTER, ResultUnit.MS); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_MISSED_VSYNC, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_SLOW_UI_THREAD, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_SLOW_BITMAP_UPLOADS, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_SLOW_DRAW, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + printDoubleValueWithKey(source, metrics, GfxMonitor.KEY_AVG_HIGH_INPUT_LATENCY, + ResultType.LOWER_BETTER, ResultUnit.COUNT); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mLog = new DeviceReportLog(); + // fix device orientation + mDevice = UiDevice.getInstance(getInstrumentation()); + mDevice.setOrientationNatural(); + } + + @Override + protected void tearDown() throws Exception { + mLog.deliverReportToHost(getInstrumentation()); + // restore device orientation + mDevice.unfreezeRotation(); + super.tearDown(); + } + + protected UiDevice getUiDevice() { + return mDevice; + } +}
diff --git a/tests/netlegacy22.api/Android.mk b/tests/netlegacy22.api/Android.mk new file mode 100644 index 0000000..68fd6f8 --- /dev/null +++ b/tests/netlegacy22.api/Android.mk
@@ -0,0 +1,32 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := tests +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsNetTestCasesLegacyApi22 + +LOCAL_SDK_VERSION := 22 + +LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner + +include $(BUILD_CTS_PACKAGE)
diff --git a/tests/netlegacy22.api/AndroidManifest.xml b/tests/netlegacy22.api/AndroidManifest.xml new file mode 100644 index 0000000..f13805c --- /dev/null +++ b/tests/netlegacy22.api/AndroidManifest.xml
@@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2007 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.netlegacy22.api"> + + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> + <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> + <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> + <uses-permission android:name="android.permission.INTERNET" /> + + <application> + <uses-library android:name="android.test.runner" /> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.netlegacy22.api" + android:label="CTS tests of legacy android.net APIs as of API 22"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> + +</manifest> +
diff --git a/tests/netlegacy22.api/src/android/net/cts/legacy/api22/ConnectivityManagerLegacyTest.java b/tests/netlegacy22.api/src/android/net/cts/legacy/api22/ConnectivityManagerLegacyTest.java new file mode 100644 index 0000000..1836f06 --- /dev/null +++ b/tests/netlegacy22.api/src/android/net/cts/legacy/api22/ConnectivityManagerLegacyTest.java
@@ -0,0 +1,292 @@ +/* + * Copyright (C) 2015 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 android.net.cts.legacy.api22; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.net.ConnectivityManager; +import android.net.LinkAddress; +import android.net.LinkProperties; +import android.net.Network; +import android.net.NetworkInfo; +import android.net.wifi.WifiManager; +import android.os.ConditionVariable; +import android.test.AndroidTestCase; +import android.util.Log; + +import java.net.DatagramSocket; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; + +import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; +import static android.net.ConnectivityManager.TYPE_MOBILE; +import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI; +import static android.net.ConnectivityManager.TYPE_VPN; +import static android.net.ConnectivityManager.TYPE_WIFI; + +public class ConnectivityManagerLegacyTest extends AndroidTestCase { + private static final String TAG = ConnectivityManagerLegacyTest.class.getSimpleName(); + private static final String FEATURE_ENABLE_HIPRI = "enableHIPRI"; + private static final String HOST_ADDRESS1 = "192.0.2.1"; + private static final String HOST_ADDRESS2 = "192.0.2.2"; + private static final String HOST_ADDRESS3 = "192.0.2.3"; + + // These are correct as of API level 22, which is what we target here. + private static final int APN_REQUEST_FAILED = 3; + private static final int MAX_NETWORK_TYPE = TYPE_VPN; + + private ConnectivityManager mCm; + private WifiManager mWifiManager; + private PackageManager mPackageManager; + + private final List<Integer>mProtectedNetworks = new ArrayList<Integer>(); + + protected void setUp() throws Exception { + super.setUp(); + mCm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); + mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE); + mPackageManager = getContext().getPackageManager(); + + // Get com.android.internal.R.array.config_protectedNetworks + int resId = getContext().getResources().getIdentifier("config_protectedNetworks", "array", "android"); + int[] protectedNetworks = getContext().getResources().getIntArray(resId); + for (int p : protectedNetworks) { + mProtectedNetworks.add(p); + } + } + + // true if only the system can turn it on + private boolean isNetworkProtected(int networkType) { + return mProtectedNetworks.contains(networkType); + } + + private int ipv4AddrToInt(String addrString) throws Exception { + byte[] addr = ((Inet4Address) InetAddress.getByName(addrString)).getAddress(); + return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | + ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); + } + + // Returns a list of all the IP addresses for all the networks of a given legacy type. We can't + // just fetch the IP addresses for that type because there is no public getLinkProperties API + // that takes a legacy type. + private List<InetAddress> getIpAddresses(int type) { + ArrayList<InetAddress> addresses = new ArrayList<>(); + Network[] networks = mCm.getAllNetworks(); + for (int i = 0; i < networks.length; i++) { + NetworkInfo ni = mCm.getNetworkInfo(networks[i]); + if (ni != null && ni.getType() == type) { + // This does not include IP addresses on stacked interfaces (e.g., 464xlat), because + // there is no public API that will return them. + LinkProperties lp = mCm.getLinkProperties(networks[i]); + for (LinkAddress address : lp.getLinkAddresses()) { + addresses.add(address.getAddress()); + } + } + } + return addresses; + } + + private boolean hasIPv4(int type) { + for (InetAddress address : getIpAddresses(type)) { + if (address instanceof Inet4Address) { + return true; + } + } + return false; + } + + private void checkSourceAddress(String addrString, int type) throws Exception { + // The public requestRouteToHost API only supports IPv4, but it will not return failure if + // the network does not have an IPv4 address. So don't check that it's working unless we + // know that the network has an IPv4 address. Note that it's possible that the network will + // have an IPv4 address but we don't know about it, because the IPv4 address might be on a + // stacked interface and we wouldn't be able to see it. + if (!hasIPv4(type)) { + Log.d(TAG, "Not checking source address on network type " + type + ", no IPv4 address"); + return; + } + + DatagramSocket d = new DatagramSocket(); + d.connect(InetAddress.getByName(addrString), 7); + InetAddress localAddress = d.getLocalAddress(); + String localAddrString = localAddress.getHostAddress(); + + Log.d(TAG, "Got source address " + localAddrString + " for destination " + addrString); + + assertTrue( + "Local address " + localAddress + " not assigned to any network of type " + type, + getIpAddresses(type).contains(localAddress)); + + Log.d(TAG, "Source address " + localAddress + " found on network type " + type); + } + + /** Test that hipri can be brought up when Wifi is enabled. */ + public void testStartUsingNetworkFeature_enableHipri() throws Exception { + if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) + || !mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) { + // This test requires a mobile data connection and WiFi. + return; + } + + // Make sure WiFi is connected to an access point. + connectToWifi(); + + expectNetworkBroadcast(TYPE_MOBILE_HIPRI, NetworkInfo.State.CONNECTED, + new Runnable() { + public void run() { + int ret = mCm.startUsingNetworkFeature(TYPE_MOBILE, FEATURE_ENABLE_HIPRI); + assertTrue("Couldn't start using the HIPRI feature.", ret != -1); + } + }); + + assertTrue("Couldn't requestRouteToHost using HIPRI.", + mCm.requestRouteToHost(TYPE_MOBILE_HIPRI, ipv4AddrToInt(HOST_ADDRESS1))); + + checkSourceAddress(HOST_ADDRESS1, TYPE_MOBILE); + checkSourceAddress(HOST_ADDRESS2, TYPE_WIFI); + + // TODO check dns selection + + expectNetworkBroadcast(TYPE_MOBILE_HIPRI, NetworkInfo.State.DISCONNECTED, + new Runnable() { + public void run() { + int ret = mCm.stopUsingNetworkFeature(TYPE_MOBILE, FEATURE_ENABLE_HIPRI); + assertTrue("Couldn't stop using the HIPRI feature.", ret != -1); + } + }); + + + // TODO check dns selection + disconnectFromWifi(); + } + + public void testStartUsingNetworkFeature() { + + final String invalidFeature = "invalidFeature"; + final String mmsFeature = "enableMMS"; + final int failureCode = -1; + final int wifiOnlyStartFailureCode = APN_REQUEST_FAILED; + final int wifiOnlyStopFailureCode = -1; + + NetworkInfo ni = mCm.getNetworkInfo(TYPE_MOBILE); + if (ni != null) { + assertEquals(APN_REQUEST_FAILED, + mCm.startUsingNetworkFeature(TYPE_MOBILE, invalidFeature)); + assertEquals(failureCode, mCm.stopUsingNetworkFeature(TYPE_MOBILE, invalidFeature)); + } else { + assertEquals(wifiOnlyStartFailureCode, mCm.startUsingNetworkFeature(TYPE_MOBILE, + invalidFeature)); + assertEquals(wifiOnlyStopFailureCode, mCm.stopUsingNetworkFeature(TYPE_MOBILE, + invalidFeature)); + } + + ni = mCm.getNetworkInfo(TYPE_WIFI); + if (ni != null) { + // Should return failure because MMS is not supported on WIFI. + assertEquals(APN_REQUEST_FAILED, mCm.startUsingNetworkFeature(TYPE_WIFI, + mmsFeature)); + assertEquals(failureCode, mCm.stopUsingNetworkFeature(TYPE_WIFI, + mmsFeature)); + } + } + + private void expectNetworkBroadcast(final int type, final NetworkInfo.State state, + Runnable afterWhat) { + final int TIMEOUT_MS = 30 * 1000; + final ConditionVariable var = new ConditionVariable(); + + Log.d(TAG, "Waiting for " + state + " broadcast for type " + type); + BroadcastReceiver receiver = new BroadcastReceiver() { + public void onReceive(Context context, Intent intent) { + NetworkInfo ni = intent.getExtras() + .getParcelable(ConnectivityManager.EXTRA_NETWORK_INFO); + assertNotNull("CONNECTIVITY_ACTION with null EXTRA_NETWORK_INFO", ni); + if (ni.getType() == type && ni.getState().equals(state)) { + Log.d(TAG, "Received expected " + state + " broadcast for type " + type); + var.open(); + } + } + }; + IntentFilter filter = new IntentFilter(); + filter.addAction(CONNECTIVITY_ACTION); + mContext.registerReceiver(receiver, filter); + + try { + afterWhat.run(); + final String msg = "Did not receive expected " + state + " broadcast for type " + type + + " after " + TIMEOUT_MS + " ms"; + assertTrue(msg, var.block(TIMEOUT_MS)); + } finally { + mContext.unregisterReceiver(receiver); + } + } + + private boolean isWifiConnected() { + NetworkInfo ni = mCm.getNetworkInfo(TYPE_WIFI); + return ni != null && ni.isConnected(); + } + + private void setWifiState(final boolean enabled) { + if (enabled != isWifiConnected()) { + final NetworkInfo.State desiredState = enabled ? + NetworkInfo.State.CONNECTED : + NetworkInfo.State.DISCONNECTED; + expectNetworkBroadcast(TYPE_WIFI, desiredState, new Runnable() { + public void run() { + mWifiManager.setWifiEnabled(enabled); + } + }); + } + } + + private void connectToWifi() { + setWifiState(true); + } + + private void disconnectFromWifi() { + setWifiState(false); + } + + private boolean isNetworkSupported(int networkType) { + return mCm.getNetworkInfo(networkType) != null; + } + + public void testRequestRouteToHost() throws Exception { + for (int type = -1 ; type <= MAX_NETWORK_TYPE; type++) { + NetworkInfo ni = mCm.getNetworkInfo(type); + boolean expectToWork = isNetworkSupported(type) && !isNetworkProtected(type) && + ni != null && ni.isConnected(); + + try { + assertTrue("Network type " + type, + mCm.requestRouteToHost(type, ipv4AddrToInt(HOST_ADDRESS3)) == expectToWork); + } catch (Exception e) { + Log.d(TAG, "got exception in requestRouteToHost for type " + type); + assertFalse("Exception received for type " + type, expectToWork); + } + + //TODO verify route table + } + + assertFalse(mCm.requestRouteToHost(-1, ipv4AddrToInt(HOST_ADDRESS1))); + } +}
diff --git a/tests/netlegacy22.permission/Android.mk b/tests/netlegacy22.permission/Android.mk new file mode 100644 index 0000000..fff9d85 --- /dev/null +++ b/tests/netlegacy22.permission/Android.mk
@@ -0,0 +1,32 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := tests +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsNetTestCasesLegacyPermission22 + +LOCAL_SDK_VERSION := 22 + +LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner + +include $(BUILD_CTS_PACKAGE)
diff --git a/tests/netlegacy22.permission/AndroidManifest.xml b/tests/netlegacy22.permission/AndroidManifest.xml new file mode 100644 index 0000000..cd1d2ba --- /dev/null +++ b/tests/netlegacy22.permission/AndroidManifest.xml
@@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.cts.netlegacy22.permission"> + + <uses-permission android:name="android.permission.INJECT_EVENTS" /> + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name="android.permission.cts.PermissionStubActivity" + android:label="PermissionStubActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN"/> + <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/> + </intent-filter> + </activity> + </application> + + <!-- + The CTS stubs package cannot be used as the target application here, + since that requires many permissions to be set. Instead, specify this + package itself as the target and include any stub activities needed. + + This test package uses the default InstrumentationTestRunner, because + the InstrumentationCtsTestRunner is only available in the stubs + package. That runner cannot be added to this package either, since it + relies on hidden APIs. + --> + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.cts.netlegacy22.permission" + android:label="CTS tests of legacy android.net permissions as of API 22"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> + +</manifest> +
diff --git a/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/ConnectivityManagerPermissionTest.java b/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/ConnectivityManagerPermissionTest.java new file mode 100644 index 0000000..0e59288 --- /dev/null +++ b/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/ConnectivityManagerPermissionTest.java
@@ -0,0 +1,54 @@ +/* + * Copyright (C) 2009 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 android.net.cts.legacy.api22.permission; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +/** +* Test that protected android.net.ConnectivityManager methods cannot be called without +* permissions +*/ +public class ConnectivityManagerPermissionTest extends AndroidTestCase { + + private ConnectivityManager mConnectivityManager = null; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); + assertNotNull(mConnectivityManager); + } + + /** + * Verify that calling {@link ConnectivityManager#requestRouteToHost(int, int)} + * requires permissions. + * <p>Tests Permission: + * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. + */ + @SmallTest + public void testRequestRouteToHost() { + try { + mConnectivityManager.requestRouteToHost(ConnectivityManager.TYPE_MOBILE, 1); + fail("Was able to call requestRouteToHost"); + } catch (SecurityException e) { + // expected + } + } +}
diff --git a/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/NoNetworkStatePermissionTest.java b/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/NoNetworkStatePermissionTest.java new file mode 100644 index 0000000..8547261 --- /dev/null +++ b/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/NoNetworkStatePermissionTest.java
@@ -0,0 +1,72 @@ +/* + * Copyright (C) 2009 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 android.net.cts.legacy.api22.permission; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; +import java.net.InetAddress; + +/** + * Verify ConnectivityManager related methods without specific network state permissions. + */ +public class NoNetworkStatePermissionTest extends AndroidTestCase { + private ConnectivityManager mConnectivityManager; + private static final int TEST_NETWORK_TYPE = ConnectivityManager.TYPE_MOBILE; + private static final String TEST_FEATURE = "enableHIPRI"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mConnectivityManager = (ConnectivityManager) mContext.getSystemService( + Context.CONNECTIVITY_SERVICE); + assertNotNull(mConnectivityManager); + } + + /** + * Verify that ConnectivityManager#startUsingNetworkFeature() requires permissions. + * <p>Requires Permission: + * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. + */ + @SmallTest + public void testStartUsingNetworkFeature() { + try { + mConnectivityManager.startUsingNetworkFeature(TEST_NETWORK_TYPE, TEST_FEATURE); + fail("ConnectivityManager.startUsingNetworkFeature didn't throw SecurityException as" + + " expected"); + } catch (SecurityException e) { + // expected + } + } + + /** + * Verify that ConnectivityManager#requestRouteToHost() requires permissions. + * <p>Requires Permission: + * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}. + */ + @SmallTest + public void testRequestRouteToHost() { + try { + mConnectivityManager.requestRouteToHost(TEST_NETWORK_TYPE, 0xffffffff); + fail("ConnectivityManager.requestRouteToHost didn't throw SecurityException as" + + " expected"); + } catch (SecurityException e) { + // expected + } + } +}
diff --git a/tests/netsecpolicy/Android.mk b/tests/netsecpolicy/Android.mk new file mode 100644 index 0000000..137672e --- /dev/null +++ b/tests/netsecpolicy/Android.mk
@@ -0,0 +1,17 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/netsecpolicy/usescleartexttraffic-false/Android.mk b/tests/netsecpolicy/usescleartexttraffic-false/Android.mk new file mode 100644 index 0000000..1af3b49 --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, \ + ../usescleartexttraffic-shared/src) + +LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficFalse + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/netsecpolicy/usescleartexttraffic-false/AndroidManifest.xml b/tests/netsecpolicy/usescleartexttraffic-false/AndroidManifest.xml new file mode 100644 index 0000000..013821e --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-false/AndroidManifest.xml
@@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.netsecpolicy.usescleartext.false.cts"> + <uses-permission android:name="android.permission.INTERNET"/> + <application android:usesCleartextTraffic="false"> + </application> +</manifest>
diff --git a/tests/netsecpolicy/usescleartexttraffic-shared/src/Dummy.java b/tests/netsecpolicy/usescleartexttraffic-shared/src/Dummy.java new file mode 100644 index 0000000..2705a5f --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-shared/src/Dummy.java
@@ -0,0 +1,2 @@ +public class Dummy { +}
diff --git a/tests/netsecpolicy/usescleartexttraffic-true/Android.mk b/tests/netsecpolicy/usescleartexttraffic-true/Android.mk new file mode 100644 index 0000000..5effc57 --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, \ + ../usescleartexttraffic-shared/src) + +LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficTrue + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/netsecpolicy/usescleartexttraffic-true/AndroidManifest.xml b/tests/netsecpolicy/usescleartexttraffic-true/AndroidManifest.xml new file mode 100644 index 0000000..f50295e --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-true/AndroidManifest.xml
@@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.netsecpolicy.usescleartext.true.cts"> + <uses-permission android:name="android.permission.INTERNET"/> + <uses-library android:name="org.apache.http.legacy"/> + + <application android:usesCleartextTraffic="true"> + </application> +</manifest>
diff --git a/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk b/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk new file mode 100644 index 0000000..685a16f --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, \ + ../usescleartexttraffic-shared/src) + +LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficUnspecified + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/netsecpolicy/usescleartexttraffic-unspecified/AndroidManifest.xml b/tests/netsecpolicy/usescleartexttraffic-unspecified/AndroidManifest.xml new file mode 100644 index 0000000..7e735c7 --- /dev/null +++ b/tests/netsecpolicy/usescleartexttraffic-unspecified/AndroidManifest.xml
@@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.netsecpolicy.usescleartext.unspecified.cts"> + <uses-permission android:name="android.permission.INTERNET"/> + <application> + </application> +</manifest>
diff --git a/tests/print/Android.mk b/tests/print/Android.mk deleted file mode 100644 index fea7dc0..0000000 --- a/tests/print/Android.mk +++ /dev/null
@@ -1,36 +0,0 @@ -# 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. - -LOCAL_PATH:= $(call my-dir) - -################################################## -# Build the print instrument library -################################################## -include $(CLEAR_VARS) -LOCAL_MODULE := CtsPrintInstrument -LOCAL_SRC_FILES := $(call all-subdir-java-files) \ - src/android/print/cts/IPrivilegedOperations.aidl -LOCAL_MODULE_TAGS := optional -LOCAL_DEX_PREOPT := false - -include $(BUILD_JAVA_LIBRARY) - -# Copy the shell script to run the print instrument Jar to the CTS out folder. -$(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).jar : $(LOCAL_BUILT_MODULE) | $(ACP) - $(copy-file-to-target) - -# Copy the built print instrument library Jar to the CTS out folder. -$(CTS_TESTCASES_OUT)/print-instrument : $(LOCAL_PATH)/print-instrument | $(ACP) - $(copy-file-to-target) -
diff --git a/tests/print/print-instrument b/tests/print/print-instrument deleted file mode 100755 index a79cb8a..0000000 --- a/tests/print/print-instrument +++ /dev/null
@@ -1,37 +0,0 @@ -# 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. - -# Script to start "print-instrument" on the device -# -# The script sets up an alternative dalvik cache when running as -# non-root. Jar files needs to be dexopt'd to run in Dalvik. For -# plain jar files, this is done at first use. shell user does not -# have write permission to default system Dalvik cache so we -# redirect to an alternative cache. - -RUN_BASE=/data/local/tmp - -# If not running as root, use an alternative dex cache. -if [ ${USER_ID} -ne 0 ]; then - tmp_cache=${RUN_BASE}/dalvik-cache - if [ ! -d ${tmp_cache} ]; then - mkdir -p ${tmp_cache} - fi - export ANDROID_DATA=${RUN_BASE} -fi - -# Run print-instrument. -export CLASSPATH=${RUN_BASE}/CtsPrintInstrument.jar - -exec app_process ${RUN_BASE} android.print.cts.PrintInstrument ${@}
diff --git a/tests/print/src/android/print/cts/IPrivilegedOperations.aidl b/tests/print/src/android/print/cts/IPrivilegedOperations.aidl deleted file mode 100644 index 93c8c3e..0000000 --- a/tests/print/src/android/print/cts/IPrivilegedOperations.aidl +++ /dev/null
@@ -1,21 +0,0 @@ -/* - * 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 android.print.cts; - -interface IPrivilegedOperations { - boolean clearApplicationUserData(String packageName); -}
diff --git a/tests/print/src/android/print/cts/PrintInstrument.java b/tests/print/src/android/print/cts/PrintInstrument.java deleted file mode 100644 index 1c568a1..0000000 --- a/tests/print/src/android/print/cts/PrintInstrument.java +++ /dev/null
@@ -1,279 +0,0 @@ -/* - * 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 android.print.cts; - -import android.app.ActivityManagerNative; -import android.app.IActivityManager; -import android.app.IInstrumentationWatcher; -import android.app.Instrumentation; -import android.app.UiAutomationConnection; -import android.content.ComponentName; -import android.content.pm.IPackageDataObserver; -import android.os.Binder; -import android.os.Bundle; -import android.os.RemoteException; -import android.os.ServiceManager; -import android.os.UserHandle; -import android.util.AndroidException; -import android.view.IWindowManager; - -import com.android.internal.os.BaseCommand; - -import java.io.PrintStream; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; - -public final class PrintInstrument extends BaseCommand { - - private static final String ARG_PRIVILEGED_OPS = "ARG_PRIVILEGED_OPS"; - - private IActivityManager mAm; - - public static void main(String[] args) { - PrintInstrument instrumenter = new PrintInstrument(); - instrumenter.run(args); - } - - @Override - public void onRun() throws Exception { - mAm = ActivityManagerNative.getDefault(); - if (mAm == null) { - System.err.println(NO_SYSTEM_ERROR_CODE); - throw new AndroidException("Can't connect to activity manager;" - + " is the system running?"); - } - - String op = nextArgRequired(); - - if (op.equals("instrument")) { - runInstrument(); - } else { - showError("Error: unknown command '" + op + "'"); - } - } - - @Override - public void onShowUsage(PrintStream out) { - /* do nothing */ - } - - @SuppressWarnings("deprecation") - private void runInstrument() throws Exception { - String profileFile = null; - boolean wait = false; - boolean rawMode = false; - boolean no_window_animation = false; - int userId = UserHandle.USER_CURRENT; - Bundle args = new Bundle(); - String argKey = null, argValue = null; - IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); - - String opt; - while ((opt=nextOption()) != null) { - if (opt.equals("-p")) { - profileFile = nextArgRequired(); - } else if (opt.equals("-w")) { - wait = true; - } else if (opt.equals("-r")) { - rawMode = true; - } else if (opt.equals("-e")) { - argKey = nextArgRequired(); - argValue = nextArgRequired(); - args.putString(argKey, argValue); - } else if (opt.equals("--no_window_animation") - || opt.equals("--no-window-animation")) { - no_window_animation = true; - } else if (opt.equals("--user")) { - userId = parseUserArg(nextArgRequired()); - } else { - System.err.println("Error: Unknown option: " + opt); - return; - } - } - - if (userId == UserHandle.USER_ALL) { - System.err.println("Error: Can't start instrumentation with user 'all'"); - return; - } - - String cnArg = nextArgRequired(); - ComponentName cn = ComponentName.unflattenFromString(cnArg); - if (cn == null) throw new IllegalArgumentException("Bad component name: " + cnArg); - - InstrumentationWatcher watcher = null; - UiAutomationConnection connection = null; - if (wait) { - watcher = new InstrumentationWatcher(); - watcher.setRawOutput(rawMode); - connection = new UiAutomationConnection(); - } - - float[] oldAnims = null; - if (no_window_animation) { - oldAnims = wm.getAnimationScales(); - wm.setAnimationScale(0, 0.0f); - wm.setAnimationScale(1, 0.0f); - } - - args.putIBinder(ARG_PRIVILEGED_OPS, new PrivilegedOperations(mAm)); - - if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher, connection, userId, null)) { - throw new AndroidException("INSTRUMENTATION_FAILED: " + cn.flattenToString()); - } - - if (watcher != null) { - if (!watcher.waitForFinish()) { - System.out.println("INSTRUMENTATION_ABORTED: System has crashed."); - } - } - - if (oldAnims != null) { - wm.setAnimationScales(oldAnims); - } - } - - private int parseUserArg(String arg) { - int userId; - if ("all".equals(arg)) { - userId = UserHandle.USER_ALL; - } else if ("current".equals(arg) || "cur".equals(arg)) { - userId = UserHandle.USER_CURRENT; - } else { - userId = Integer.parseInt(arg); - } - return userId; - } - - private class InstrumentationWatcher extends IInstrumentationWatcher.Stub { - private boolean mFinished = false; - private boolean mRawMode = false; - - /** - * Set or reset "raw mode". In "raw mode", all bundles are dumped. In "pretty mode", - * if a bundle includes Instrumentation.REPORT_KEY_STREAMRESULT, just print that. - * @param rawMode true for raw mode, false for pretty mode. - */ - public void setRawOutput(boolean rawMode) { - mRawMode = rawMode; - } - - @Override - public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { - synchronized (this) { - // pretty printer mode? - String pretty = null; - if (!mRawMode && results != null) { - pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); - } - if (pretty != null) { - System.out.print(pretty); - } else { - if (results != null) { - for (String key : results.keySet()) { - System.out.println( - "INSTRUMENTATION_STATUS: " + key + "=" + results.get(key)); - } - } - System.out.println("INSTRUMENTATION_STATUS_CODE: " + resultCode); - } - notifyAll(); - } - } - - @Override - public void instrumentationFinished(ComponentName name, int resultCode, - Bundle results) { - synchronized (this) { - // pretty printer mode? - String pretty = null; - if (!mRawMode && results != null) { - pretty = results.getString(Instrumentation.REPORT_KEY_STREAMRESULT); - } - if (pretty != null) { - System.out.println(pretty); - } else { - if (results != null) { - for (String key : results.keySet()) { - System.out.println( - "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); - } - } - System.out.println("INSTRUMENTATION_CODE: " + resultCode); - } - mFinished = true; - notifyAll(); - } - } - - public boolean waitForFinish() { - synchronized (this) { - while (!mFinished) { - try { - if (!mAm.asBinder().pingBinder()) { - return false; - } - wait(1000); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } - } - } - return true; - } - } - - private static final class PrivilegedOperations extends IPrivilegedOperations.Stub { - private final IActivityManager mAm; - - public PrivilegedOperations(IActivityManager am) { - mAm = am; - } - - @Override - public boolean clearApplicationUserData(final String clearedPackageName) - throws RemoteException { - final long identity = Binder.clearCallingIdentity(); - try { - final AtomicBoolean success = new AtomicBoolean(); - final CountDownLatch completionLatch = new CountDownLatch(1); - - mAm.clearApplicationUserData(clearedPackageName, - new IPackageDataObserver.Stub() { - @Override - public void onRemoveCompleted(String packageName, boolean succeeded) { - if (clearedPackageName.equals(packageName) && succeeded) { - success.set(true); - } else { - success.set(false); - } - completionLatch.countDown(); - } - }, UserHandle.USER_CURRENT); - - try { - completionLatch.await(); - } catch (InterruptedException ie) { - /* ignore */ - } - - return success.get(); - } finally { - Binder.restoreCallingIdentity(identity); - } - } - } -}
diff --git a/tests/tests/accessibility/Android.mk b/tests/tests/accessibility/Android.mk index 9f98b16..263c47b 100644 --- a/tests/tests/accessibility/Android.mk +++ b/tests/tests/accessibility/Android.mk
@@ -26,7 +26,6 @@ LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner -# This test runner sets up/cleans up the device before/after running the tests. -LOCAL_CTS_TEST_RUNNER := com.android.cts.tradefed.testtype.AccessibilityTestRunner +LOCAL_SDK_VERSION := current include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/accessibility/AndroidManifest.xml b/tests/tests/accessibility/AndroidManifest.xml index 319fb49..b3bcbc8 100644 --- a/tests/tests/accessibility/AndroidManifest.xml +++ b/tests/tests/accessibility/AndroidManifest.xml
@@ -17,18 +17,19 @@ --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="android.view.cts.accessibility"> + package="android.view.cts.accessibility"> - <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> - <application android:theme="@android:style/Theme.Holo.NoActionBar" > - <uses-library android:name="android.test.runner"/> - </application> + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> - <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" - android:targetPackage="android.view.cts.accessibility" - android:label="Tests for the accessibility APIs."> + <application android:theme="@android:style/Theme.Holo.NoActionBar" > + <uses-library android:name="android.test.runner"/> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.view.cts.accessibility" + android:label="Tests for the accessibility APIs."> <meta-data android:name="listener" - android:value="com.android.cts.runner.CtsTestRunListener" /> + android:value="com.android.cts.runner.CtsTestRunListener" /> </instrumentation> </manifest>
diff --git a/tests/tests/accessibility/AndroidTest.xml b/tests/tests/accessibility/AndroidTest.xml new file mode 100644 index 0000000..7832508 --- /dev/null +++ b/tests/tests/accessibility/AndroidTest.xml
@@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="Base config for CTS package preparer"> + <include name="common-config" /> + <option name="run-command:run-command" value="settings put secure enabled_accessibility_services android.view.accessibility.services/.SpeakingAccessibilityService:android.view.accessibility.services/.VibratingAccessibilityService" /> + <option name="run-command:run-command" value="settings put secure touch_exploration_granted_accessibility_services android.view.accessibility.services/.SpeakingAccessibilityService:android.view.accessibility.services/.VibratingAccessibilityService" /> + <option name="run-command:run-command" value="settings put secure accessibility_enabled 1" /> + <option name="run-command:teardown-command" value="settings put secure enabled_accessibility_services """ /> + <option name="run-command:teardown-command" value="settings put secure touch_exploration_granted_accessibility_services """ /> + <option name="run-command:teardown-command" value="settings put secure accessibility_enabled 0" /> + <option name="cts-apk-installer:test-file-name" value="CtsSomeAccessibilityServices.apk" /> +</configuration>
diff --git a/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java b/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java index 8be2b99..db4e54b 100644 --- a/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java +++ b/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityEventTest.java
@@ -113,6 +113,8 @@ AccessibilityEvent.TYPE_VIEW_HOVER_EXIT)); assertEquals("TYPE_VIEW_LONG_CLICKED", AccessibilityEvent.eventTypeToString( AccessibilityEvent.TYPE_VIEW_LONG_CLICKED)); + assertEquals("TYPE_VIEW_CONTEXT_CLICKED", AccessibilityEvent.eventTypeToString( + AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED)); assertEquals("TYPE_VIEW_SCROLLED", AccessibilityEvent.eventTypeToString( AccessibilityEvent.TYPE_VIEW_SCROLLED)); assertEquals("TYPE_VIEW_SELECTED", AccessibilityEvent.eventTypeToString(
diff --git a/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java b/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java index f5e1d48..506c022 100644 --- a/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java +++ b/tests/tests/accessibility/src/android/view/accessibility/cts/AccessibilityNodeInfoTest.java
@@ -185,6 +185,7 @@ info.setFocusable(true); info.setFocused(true); info.setLongClickable(true); + info.setContextClickable(true); info.setPassword(true); info.setScrollable(true); info.setSelected(true); @@ -235,6 +236,8 @@ receivedInfo.isFocused()); assertSame("longClickable has incorrect value", expectedInfo.isLongClickable(), receivedInfo.isLongClickable()); + assertSame("contextClickable has incorrect value", expectedInfo.isContextClickable(), + receivedInfo.isContextClickable()); assertSame("password has incorrect value", expectedInfo.isPassword(), receivedInfo.isPassword()); assertSame("scrollable has incorrect value", expectedInfo.isScrollable(), @@ -281,6 +284,7 @@ assertFalse("focusable not properly recycled", info.isFocusable()); assertFalse("focused not properly recycled", info.isFocused()); assertFalse("longClickable not properly recycled", info.isLongClickable()); + assertFalse("contextClickable not properly recycled", info.isContextClickable()); assertFalse("password not properly recycled", info.isPassword()); assertFalse("scrollable not properly recycled", info.isScrollable()); assertFalse("selected not properly recycled", info.isSelected());
diff --git a/tests/tests/accessibility/src/android/view/accessibility/cts/CaptioningManagerTest.java b/tests/tests/accessibility/src/android/view/accessibility/cts/CaptioningManagerTest.java new file mode 100644 index 0000000..53eb215 --- /dev/null +++ b/tests/tests/accessibility/src/android/view/accessibility/cts/CaptioningManagerTest.java
@@ -0,0 +1,173 @@ +/* + * Copyright (C) 2015 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 android.view.accessibility.cts; + +import android.app.UiAutomation; +import android.os.ParcelFileDescriptor; +import android.test.InstrumentationTestCase; +import android.view.accessibility.CaptioningManager; +import android.view.accessibility.CaptioningManager.CaptionStyle; +import android.view.accessibility.CaptioningManager.CaptioningChangeListener; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Locale; + +/** + * Tests whether the CaptioningManager APIs are functional. + */ +public class CaptioningManagerTest extends InstrumentationTestCase { + private CaptioningManager mManager; + private UiAutomation mUiAutomation; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mManager = getInstrumentation().getTargetContext().getSystemService( + CaptioningManager.class); + + assertNotNull("Obtained captioning manager", mManager); + + mUiAutomation = getInstrumentation().getUiAutomation(); + } + + /** + * Tests whether a client can observe changes in caption properties. + */ + public void testChangeListener() { + putSecureSetting("accessibility_captioning_enabled","0"); + putSecureSetting("accessibility_captioning_preset", "1"); + putSecureSetting("accessibility_captioning_locale", "en_US"); + putSecureSetting("accessibility_captioning_font_scale", "1.0"); + + MockCaptioningChangeListener listener = new MockCaptioningChangeListener(); + mManager.addCaptioningChangeListener(listener); + + putSecureSetting("accessibility_captioning_enabled", "1"); + assertTrue("Observed enabled change", listener.wasEnabledChangedCalled); + + putSecureSetting("accessibility_captioning_preset", "-1"); + assertTrue("Observed user style change", listener.wasUserStyleChangedCalled); + + putSecureSetting("accessibility_captioning_locale", "ja_JP"); + assertTrue("Observed locale change", listener.wasLocaleChangedCalled); + + putSecureSetting("accessibility_captioning_font_scale", "2.0"); + assertTrue("Observed font scale change", listener.wasFontScaleChangedCalled); + + mManager.removeCaptioningChangeListener(listener); + + listener.reset(); + + putSecureSetting("accessibility_captioning_enabled","0"); + assertFalse("Did not observe enabled change", listener.wasEnabledChangedCalled); + + try { + mManager.removeCaptioningChangeListener(listener); + } catch (Exception e) { + throw new AssertionError("Fails silently when removing listener twice", e); + } + } + + public void testProperties() { + putSecureSetting("accessibility_captioning_font_scale", "2.0"); + putSecureSetting("accessibility_captioning_locale", "ja_JP"); + putSecureSetting("accessibility_captioning_enabled", "1"); + + assertEquals("Test runner set font scale to 2.0", 2.0f, mManager.getFontScale()); + assertEquals("Test runner set locale to Japanese", Locale.JAPAN, mManager.getLocale()); + assertEquals("Test runner set enabled to true", true, mManager.isEnabled()); + } + + public void testUserStyle() { + putSecureSetting("accessibility_captioning_preset", "-1"); + putSecureSetting("accessibility_captioning_foreground_color", "511"); + putSecureSetting("accessibility_captioning_background_color", "511"); + putSecureSetting("accessibility_captioning_window_color", "511"); + putSecureSetting("accessibility_captioning_edge_color", "511"); + putSecureSetting("accessibility_captioning_edge_type", "-1"); + deleteSecureSetting("accessibility_captioning_typeface"); + + CaptionStyle userStyle = mManager.getUserStyle(); + assertNotNull("Default user style is not null", userStyle); + assertFalse("Default user style has no edge type", userStyle.hasEdgeType()); + assertFalse("Default user style has no edge color", userStyle.hasEdgeColor()); + assertFalse("Default user style has no foreground color", userStyle.hasForegroundColor()); + assertFalse("Default user style has no background color", userStyle.hasBackgroundColor()); + assertFalse("Default user style has no window color", userStyle.hasWindowColor()); + assertNull("Default user style has no typeface", userStyle.getTypeface()); + } + + private void deleteSecureSetting(String name) { + execShellCommand("settings delete secure " + name); + } + + private void putSecureSetting(String name, String value) { + execShellCommand("settings put secure " + name + " " + value); + } + + private void execShellCommand(String cmd) { + ParcelFileDescriptor pfd = mUiAutomation.executeShellCommand(cmd); + InputStream is = new FileInputStream(pfd.getFileDescriptor()); + try { + final byte[] buffer = new byte[8192]; + while ((is.read(buffer)) != -1); + } catch (IOException e) { + throw new RuntimeException("Failed to exec: " + cmd); + } + } + + private static class MockCaptioningChangeListener extends CaptioningChangeListener { + boolean wasEnabledChangedCalled = false; + boolean wasUserStyleChangedCalled = false; + boolean wasLocaleChangedCalled = false; + boolean wasFontScaleChangedCalled = false; + + @Override + public void onEnabledChanged(boolean enabled) { + super.onEnabledChanged(enabled); + wasEnabledChangedCalled = true; + } + + @Override + public void onUserStyleChanged(CaptionStyle userStyle) { + super.onUserStyleChanged(userStyle); + wasUserStyleChangedCalled = true; + } + + @Override + public void onLocaleChanged(Locale locale) { + super.onLocaleChanged(locale); + wasLocaleChangedCalled = true; + } + + @Override + public void onFontScaleChanged(float fontScale) { + super.onFontScaleChanged(fontScale); + wasFontScaleChangedCalled = true; + } + + public void reset() { + wasEnabledChangedCalled = false; + wasUserStyleChangedCalled = false; + wasLocaleChangedCalled = false; + wasFontScaleChangedCalled = false; + } + } +}
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java index b11248a..ca20549 100644 --- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java +++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
@@ -24,8 +24,10 @@ import android.app.Service; import android.app.UiAutomation; import android.content.Intent; +import android.content.res.Configuration; import android.test.suitebuilder.annotation.MediumTest; import android.text.TextUtils; +import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.widget.Button; import android.widget.EditText; @@ -44,6 +46,8 @@ public class AccessibilityEndToEndTest extends AccessibilityActivityTestCase<AccessibilityEndToEndActivity> { + private static final String LOG_TAG = "AccessibilityEndToEndTest"; + /** * Creates a new instance for testing {@link AccessibilityEndToEndActivity}. */ @@ -309,16 +313,26 @@ @MediumTest @SuppressWarnings("deprecation") public void testTypeNotificationStateChangedAccessibilityEvent() throws Throwable { + // No notification UI on televisions. + if((getActivity().getResources().getConfiguration().uiMode + & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) { + Log.i(LOG_TAG, "Skipping: testTypeNotificationStateChangedAccessibilityEvent" + + " - No notification UI on televisions."); + return; + } + String message = getActivity().getString(R.string.notification_message); // create the notification to send final int notificationId = 1; - final Notification notification = new Notification(); - notification.icon = android.R.drawable.stat_notify_call_mute; - notification.contentIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(), - PendingIntent.FLAG_CANCEL_CURRENT); - notification.tickerText = message; - notification.setLatestEventInfo(getActivity(), "", "", notification.contentIntent); + final Notification notification = new Notification.Builder(getActivity()) + .setSmallIcon(android.R.drawable.stat_notify_call_mute) + .setContentIntent(PendingIntent.getActivity(getActivity(), 0, new Intent(), + PendingIntent.FLAG_CANCEL_CURRENT)) + .setTicker(message) + .setContentTitle("") + .setContentText("") + .build(); // create and populate the expected event final AccessibilityEvent expected = AccessibilityEvent.obtain();
diff --git a/tests/tests/accounts/Android.mk b/tests/tests/accounts/Android.mk index 1579822..6ed35c6 100644 --- a/tests/tests/accounts/Android.mk +++ b/tests/tests/accounts/Android.mk
@@ -21,7 +21,7 @@ # and when built explicitly put it in the data partition LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) -LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner +LOCAL_STATIC_JAVA_LIBRARIES := CtsAccountTestsCommon ctstestrunner LOCAL_SRC_FILES := $(call all-java-files-under, src) @@ -30,3 +30,4 @@ LOCAL_SDK_VERSION := current include $(BUILD_CTS_PACKAGE) +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/accounts/AndroidManifest.xml b/tests/tests/accounts/AndroidManifest.xml index c671ff0..d882690 100644 --- a/tests/tests/accounts/AndroidManifest.xml +++ b/tests/tests/accounts/AndroidManifest.xml
@@ -18,11 +18,9 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.accounts.cts"> - <!-- Used for AccountManagerService test, don't delete this permission --> - <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> - <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> - <uses-permission android:name="android.permission.GET_ACCOUNTS" /> - <uses-permission android:name="android.permission.USE_CREDENTIALS" /> + <!-- Don't need GET_ACCOUNTS because share a Uid with the relevant + authenticators --> + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <application> @@ -43,10 +41,21 @@ <intent-filter> <action android:name="android.accounts.AccountAuthenticator" /> </intent-filter> - <meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /> </service> + + <service android:name="MockCustomTokenAccountService" android:exported="true" + android:process="android.accounts.cts"> + <intent-filter> + <action android:name="android.accounts.AccountAuthenticator" /> + </intent-filter> + <meta-data android:name="android.accounts.AccountAuthenticator" + android:resource="@xml/custom_token_authenticator" /> + <meta-data android:name="android.accounts.AccountAuthenticator.customTokens" + android:value="1" /> + + </service> </application> <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/accounts/AndroidTest.xml b/tests/tests/accounts/AndroidTest.xml new file mode 100644 index 0000000..3e29c9c --- /dev/null +++ b/tests/tests/accounts/AndroidTest.xml
@@ -0,0 +1,18 @@ +<!-- Copyright (C) 2015 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. +--> +<configuration description="Test module config for Account apis"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsUnaffiliatedAccountAuthenticators.apk" /> +</configuration>
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk new file mode 100644 index 0000000..cb504da --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
@@ -0,0 +1,42 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# LOCAL_MODULE_TAGS := tests + +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SDK_VERSION := current + +LOCAL_STATIC_JAVA_LIBRARIES := \ + ctstestrunner \ + CtsAccountTestsCommon + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/res + +LOCAL_PACKAGE_NAME := CtsUnaffiliatedAccountAuthenticators + +LOCAL_SDK_VERSION := current + +LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2 + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml new file mode 100644 index 0000000..c32f89f --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/AndroidManifest.xml
@@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2009 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.accounts.cts.unaffiliated"> + + <!-- Used for AccountManagerService test, don't delete this permission --> + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> + + <application> + + <activity + android:name="android.accounts.cts.common.TestAuthenticatorActivity" + android:exported="true" /> + + <provider + android:name="android.accounts.cts.common.AuthenticatorContentProvider" + android:authorities="android.accounts.cts.unaffiliated.authenticators.provider" + android:exported="true" /> + + <service + android:name=".StdAccountAuthService" + android:exported="false"> + <intent-filter> + <action android:name="android.accounts.AccountAuthenticator" /> + </intent-filter> + <meta-data android:name="android.accounts.AccountAuthenticator" + android:resource="@xml/standard_authenticator" /> + </service> +<!-- + <service android:name=".CustomAccountAuthService" android:exported="false"> + <intent-filter> + <action android:name="android.accounts.AccountAuthenticator" /> + </intent-filter> + <meta-data android:name="android.accounts.AccountAuthenticator" + android:resource="@xml/custom_authenticator" /> + </service> + --> + + </application> +</manifest> +
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected.png b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected.png new file mode 100644 index 0000000..c730050 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected.png Binary files differ
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected_custom_account.png b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected_custom_account.png new file mode 100644 index 0000000..3fbbc94 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_minitab_selected_custom_account.png Binary files differ
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected.png b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected.png new file mode 100644 index 0000000..72a065c --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected.png Binary files differ
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected_custom_account.png b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected_custom_account.png new file mode 100644 index 0000000..70e35c0 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/drawable/ic_cts_selected_custom_account.png Binary files differ
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/values/strings.xml b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/values/strings.xml new file mode 100644 index 0000000..442669b --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/values/strings.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/* + * Copyright (C) 2009 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. + */ +--> + +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <!-- Label for this package --> + <string name="label">Android CTS - Account</string> +</resources> \ No newline at end of file
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/custom_authenticator.xml b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/custom_authenticator.xml new file mode 100644 index 0000000..3485f76 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/custom_authenticator.xml
@@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/** + * Copyright (c) 2009, 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. + */ +--> + +<!-- The attributes in this XML file provide configuration information --> +<!-- for the Account Manager. --> + +<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" + android:accountType="android.accounts.test.custom" + android:icon="@drawable/ic_cts_selected_custom_account" + android:smallIcon="@drawable/ic_cts_minitab_selected_custom_account" + android:customTokens="true" + android:label="@string/label" +/>
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/standard_authenticator.xml b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/standard_authenticator.xml new file mode 100644 index 0000000..0c843b9 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/res/xml/standard_authenticator.xml
@@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/** + * Copyright (c) 2009, 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. + */ +--> + +<!-- The attributes in this XML file provide configuration information --> +<!-- for the Account Manager. --> + +<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" + android:accountType="android.accounts.test.standard.unaffiliated" + android:icon="@drawable/ic_cts_selected" + android:smallIcon="@drawable/ic_cts_minitab_selected" + android:label="@string/label" +/>
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/src/android/accounts/cts/unaffiliated/StdAccountAuthService.java b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/src/android/accounts/cts/unaffiliated/StdAccountAuthService.java new file mode 100644 index 0000000..de87ac7 --- /dev/null +++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/src/android/accounts/cts/unaffiliated/StdAccountAuthService.java
@@ -0,0 +1,36 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts.unaffiliated; + +import android.accounts.cts.common.Fixtures; +import android.accounts.cts.common.TestAccountAuthenticator; +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +/** + * a basic Mock Service for wrapping the MockAccountAuthenticator + */ +public class StdAccountAuthService extends Service { + + @Override + public IBinder onBind(Intent intent) { + TestAccountAuthenticator auth = + new TestAccountAuthenticator(this, Fixtures.TYPE_STANDARD_UNAFFILIATED); + return auth.getIBinder(); + } +}
diff --git a/tests/tests/accounts/common/Android.mk b/tests/tests/accounts/common/Android.mk new file mode 100644 index 0000000..cac9c5e --- /dev/null +++ b/tests/tests/accounts/common/Android.mk
@@ -0,0 +1,36 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +# Includes all the java files, and explicitly declares any aidl files +LOCAL_SRC_FILES := \ + $(call all-java-files-under, src) \ + $(call all-Iaidl-files-under, src) + +LOCAL_AIDL_INCLUDES += $(LOCAL_PATH)/src + +LOCAL_MODULE:= CtsAccountTestsCommon + +LOCAL_SDK_VERSION := current + +# Build the actual static library +include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/tests/accounts/common/AndroidManifest.xml b/tests/tests/accounts/common/AndroidManifest.xml new file mode 100644 index 0000000..6e6d107 --- /dev/null +++ b/tests/tests/accounts/common/AndroidManifest.xml
@@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.accounts.test.shared"> + <uses-sdk + android:minSdkVersion="4" /> + <application /> +</manifest>
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/AuthenticatorContentProvider.java b/tests/tests/accounts/common/src/android/accounts/cts/common/AuthenticatorContentProvider.java new file mode 100644 index 0000000..b52dae3 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/AuthenticatorContentProvider.java
@@ -0,0 +1,150 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts.common; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AuthenticatorDescription; +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.os.Parcelable; + +import java.util.concurrent.atomic.AtomicReference; + +public class AuthenticatorContentProvider extends ContentProvider { + + public static final String AUTHORITY = + "android.accounts.cts.unaffiliated.authenticators.provider"; + + public static final int RESULT_SUCCESS = 1; + public static final int RESULT_FAIL = 2; + + public static final String METHOD_GET = "get"; + public static final String METHOD_SETUP = "setup"; + public static final String METHOD_TEARDOWN = "setup"; + + public static final int ACTION_GET = 1; + public static final int ACTION_SETUP = 2; + public static final int ACTION_TEARDOWN = 3; + + public static final int ARG_UNAFFILIATED = 10; + public static final int ARG_AFFILIATED = 11; + + public static final String KEY_CALLBACK = "callback"; + public static final String KEY_TX = "tx"; + + public static final AtomicReference<Parcelable> sLastTx = new AtomicReference<>(); + + public static void setTx(Parcelable tx) { + sLastTx.set(tx); + } + + @Override + // public void handleMessage(Message msg) { + public Bundle call(String method, String arg, Bundle extras) { + super.call(method, arg, extras); + Bundle result = new Bundle(); + if (METHOD_GET.equals(method)) { + result.putParcelable(KEY_TX, sLastTx.get()); + return result; + } else if (METHOD_SETUP.equals(method)) { + setup(); + return result; + } else if (METHOD_TEARDOWN.equals(method)) { + teardown(); + return result; + } else { + throw new IllegalArgumentException("Unrecognized method!"); + } + } + + public void setup() { + Context context = getContext(); + AccountManager am = AccountManager.get(context); + AuthenticatorDescription[] authenticators = am.getAuthenticatorTypes(); + for (AuthenticatorDescription a : authenticators) { + /* + * Populate relevant test information for authenticators in the + * same package as the TestAuthenticatorSupportHandler. + */ + if (a.packageName.equals(context.getPackageName())) { + for (String name : Fixtures.getFixtureAccountNames()) { + Account account = new Account(name, a.type); + am.addAccountExplicitly(account, Fixtures.PREFIX_PASSWORD + name, null); + } + } + } + } + + public void teardown() { + Context context = getContext(); + AccountManager am = AccountManager.get(context); + AuthenticatorDescription[] authenticators = am.getAuthenticatorTypes(); + for (AuthenticatorDescription a : authenticators) { + /* + * Populate relevant test information for authenticators in the + * same package as the TestAuthenticatorSupportHandler. + */ + if (a.packageName.equals(context.getPackageName())) { + Account[] accountsToRemove = am.getAccountsByType(a.type); + for (Account account : accountsToRemove) { + am.removeAccountExplicitly(account); + } + } + } + } + + @Override + public boolean onCreate() { + return true; + } + + @Override + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { + throw new UnsupportedOperationException(); + } + + @Override + public String getType(Uri uri) { + throw new UnsupportedOperationException(); + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + throw new UnsupportedOperationException(); + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } +} +
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/Fixtures.java b/tests/tests/accounts/common/src/android/accounts/cts/common/Fixtures.java new file mode 100644 index 0000000..f8636a0 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/Fixtures.java
@@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts.common; + +import android.accounts.Account; + +import java.util.ArrayList; +import java.util.List; + +/** + * Constants shared amongst account hostside tests. + */ +public final class Fixtures { + + public static final String TYPE_CUSTOM = "android.accounts.test.custom"; + public static final String TYPE_STANDARD = "android.accounts.test.standard"; + + public static final String TYPE_STANDARD_UNAFFILIATED = + "android.accounts.test.standard.unaffiliated"; + + public static final String PREFIX_TOKEN = "token:"; + public static final String PREFIX_PASSWORD = "password:"; + + public static final String SUFFIX_NAME_FIXTURE = "fixture.com"; + public static final String SUFFIX_NAME_TEST = "test.com"; + + public static final String PREFIX_NAME_SUCCESS = "success_on_return"; + public static final String PREFIX_NAME_ERROR = "error"; + public static final String PREFIX_NAME_INTERVENE = "intervene"; + + private static final String[] accountNamePrefixes = new String[] { + PREFIX_NAME_SUCCESS, + PREFIX_NAME_ERROR, + PREFIX_NAME_INTERVENE + }; + + public static final Account ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS = new Account( + PREFIX_NAME_SUCCESS + "@" + SUFFIX_NAME_FIXTURE, + TYPE_STANDARD_UNAFFILIATED); + + public static List<String> getFixtureAccountNames() { + List<String> accountNames = new ArrayList<>(accountNamePrefixes.length); + for (String prefix : accountNamePrefixes) { + accountNames.add(prefix + "@" + SUFFIX_NAME_FIXTURE); + } + return accountNames; + } + + public static final int TEST_SUPPORT_RESULT_SUCCESS = 1; + public static final int TEST_SUPPORT_RESULT_FAIL = 2; + + public static final String KEY_ACCOUNT_NAME = "test:account_name"; + + public static final String KEY_CALLBACK = "test:callback"; + public static final String KEY_CALLBACK_REQUIRED = "test:callback_required"; + public static final String KEY_RESULT = "test:result"; + public static final String KEY_TOKEN_EXPIRY = "test:token_duration"; + + private Fixtures() {} +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/TestAccountAuthenticator.java b/tests/tests/accounts/common/src/android/accounts/cts/common/TestAccountAuthenticator.java new file mode 100644 index 0000000..1fac1ea --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/TestAccountAuthenticator.java
@@ -0,0 +1,326 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts.common; + +import android.accounts.AbstractAccountAuthenticator; +import android.accounts.Account; +import android.accounts.AccountAuthenticatorResponse; +import android.accounts.AccountManager; +import android.accounts.NetworkErrorException; +import android.accounts.cts.common.tx.AddAccountTx; +import android.accounts.cts.common.tx.ConfirmCredentialsTx; +import android.accounts.cts.common.tx.GetAuthTokenLabelTx; +import android.accounts.cts.common.tx.GetAuthTokenTx; +import android.accounts.cts.common.tx.HasFeaturesTx; +import android.accounts.cts.common.tx.UpdateCredentialsTx; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; + +import java.util.Arrays; + +public class TestAccountAuthenticator extends AbstractAccountAuthenticator { + + private final String mAccountType; + private final Context mContext; + private volatile int mCounter = 0; + + public TestAccountAuthenticator(Context context, String accountType) { + super(context); + mContext = context; + mAccountType = accountType; + } + + @Override + public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { + throw new UnsupportedOperationException( + "editProperties should be tested using the MockAuthenticator"); + } + + @Override + public Bundle addAccount( + AccountAuthenticatorResponse response, + String accountType, + String authTokenType, + String[] requiredFeatures, + Bundle options) throws NetworkErrorException { + if (!mAccountType.equals(accountType)) { + throw new IllegalArgumentException("Request to the wrong authenticator!"); + } + String accountName = null; + boolean isCallbackRequired = false; + if (options != null) { + accountName = options.getString(Fixtures.KEY_ACCOUNT_NAME); + isCallbackRequired = options.getBoolean(Fixtures.KEY_CALLBACK_REQUIRED, false); + } + Bundle result = new Bundle(); + AuthenticatorContentProvider.setTx( + new AddAccountTx(accountType, authTokenType, requiredFeatures, options, result)); + if (accountName.startsWith(Fixtures.PREFIX_NAME_SUCCESS)) { + // fill bundle with a success result. + result.putString(AccountManager.KEY_ACCOUNT_NAME, accountName); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType); + } else if (accountName.startsWith(Fixtures.PREFIX_NAME_INTERVENE)) { + // Specify data to be returned by the eventual activity. + Intent eventualActivityResultData = new Intent(); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); + // Fill result with Intent. + Intent intent = new Intent(mContext, TestAuthenticatorActivity.class); + intent.putExtra(Fixtures.KEY_RESULT, eventualActivityResultData); + intent.putExtra(Fixtures.KEY_CALLBACK, response); + + result.putParcelable(AccountManager.KEY_INTENT, intent); + } else { + // fill with error + int errorCode = AccountManager.ERROR_CODE_INVALID_RESPONSE; + String errorMsg = "Default Error Message"; + if (options != null) { + errorCode = options.getInt(AccountManager.KEY_ERROR_CODE); + errorMsg = options.getString(AccountManager.KEY_ERROR_MESSAGE); + } + result.putInt(AccountManager.KEY_ERROR_CODE, errorCode); + result.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg); + } + + try { + return (isCallbackRequired) ? null : result; + } finally { + if (isCallbackRequired) { + response.onResult(result); + } + } + } + + @Override + public Bundle confirmCredentials( + AccountAuthenticatorResponse response, + Account account, + Bundle options) throws NetworkErrorException { + if (!mAccountType.equals(account.type)) { + throw new IllegalArgumentException("Request to the wrong authenticator!"); + } + Bundle result = new Bundle(); + AuthenticatorContentProvider.setTx( + new ConfirmCredentialsTx(account, options, result)); + + boolean isCallbackRequired = + options != null && options.getBoolean(Fixtures.KEY_CALLBACK_REQUIRED); + if (account.name.startsWith(Fixtures.PREFIX_NAME_SUCCESS)) { + // fill bundle with a success result. + result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + } else if (account.name.startsWith(Fixtures.PREFIX_NAME_INTERVENE)) { + // Specify data to be returned by the eventual activity. + Intent eventualActivityResultData = new Intent(); + eventualActivityResultData.putExtra(AccountManager.KEY_BOOLEAN_RESULT, true); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type); + + // Fill result with Intent. + Intent intent = new Intent(mContext, TestAuthenticatorActivity.class); + intent.putExtra(Fixtures.KEY_RESULT, eventualActivityResultData); + intent.putExtra(Fixtures.KEY_CALLBACK, response); + + result.putParcelable(AccountManager.KEY_INTENT, intent); + } else { + // fill with error + // fill with error + int errorCode = AccountManager.ERROR_CODE_INVALID_RESPONSE; + String errorMsg = "Default Error Message"; + if (options != null) { + errorCode = options.getInt(AccountManager.KEY_ERROR_CODE); + errorMsg = options.getString(AccountManager.KEY_ERROR_MESSAGE); + } + result.putInt(AccountManager.KEY_ERROR_CODE, errorCode); + result.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg); + } + + try { + return (isCallbackRequired) ? null : result; + } finally { + if (isCallbackRequired) { + response.onResult(result); + } + } + } + + @Override + public Bundle getAuthToken( + AccountAuthenticatorResponse response, + Account account, + String authTokenType, + Bundle options) throws NetworkErrorException { + if (!mAccountType.equals(account.type)) { + throw new IllegalArgumentException("Request to the wrong authenticator!"); + } + Bundle result = new Bundle(); + AuthenticatorContentProvider.setTx( + new GetAuthTokenTx(account, authTokenType, options, result)); + boolean isCallbackRequired = + options != null && options.getBoolean(Fixtures.KEY_CALLBACK_REQUIRED); + long expiryMillis = (options == null) ? 0 : options.getLong(Fixtures.KEY_TOKEN_EXPIRY); + if (account.name.startsWith(Fixtures.PREFIX_NAME_SUCCESS)) { + // fill bundle with a success result. + result.putString( + AccountManager.KEY_AUTHTOKEN, Fixtures.PREFIX_TOKEN + mCounter++); + result.putLong( + AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, + expiryMillis); + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + } else if (account.name.startsWith(Fixtures.PREFIX_NAME_INTERVENE)) { + // Specify data to be returned by the eventual activity. + Intent eventualActivityResultData = new Intent(); + eventualActivityResultData.putExtra( + AccountManager.KEY_AUTHTOKEN, Fixtures.PREFIX_TOKEN + mCounter++); + eventualActivityResultData.putExtra( + AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, + expiryMillis); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type); + + // Fill result with Intent. + Intent intent = new Intent(mContext, TestAuthenticatorActivity.class); + intent.putExtra(Fixtures.KEY_RESULT, eventualActivityResultData); + intent.putExtra(Fixtures.KEY_CALLBACK, response); + + result.putParcelable(AccountManager.KEY_INTENT, intent); + + } else { + // fill with error + int errorCode = AccountManager.ERROR_CODE_INVALID_RESPONSE; + String errorMsg = "Default Error Message"; + if (options != null) { + errorCode = options.getInt(AccountManager.KEY_ERROR_CODE); + errorMsg = options.getString(AccountManager.KEY_ERROR_MESSAGE); + } + result.putInt(AccountManager.KEY_ERROR_CODE, errorCode); + result.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg); + } + + try { + return (isCallbackRequired) ? null : result; + } finally { + if (isCallbackRequired) { + response.onResult(result); + } + } + } + + @Override + public String getAuthTokenLabel(String authTokenType) { + String result = "Label:" + authTokenType; + AuthenticatorContentProvider.setTx( + new GetAuthTokenLabelTx(authTokenType, result)); + return result; + } + + @Override + public Bundle updateCredentials( + AccountAuthenticatorResponse response, + Account account, + String authTokenType, + Bundle options) throws NetworkErrorException { + if (!mAccountType.equals(account.type)) { + throw new IllegalArgumentException("Request to the wrong authenticator!"); + } + Bundle result = new Bundle(); + AuthenticatorContentProvider.setTx( + new UpdateCredentialsTx(account, authTokenType, options, result)); + + boolean isCallbackRequired = + options != null && options.getBoolean(Fixtures.KEY_CALLBACK_REQUIRED); + if (account.name.startsWith(Fixtures.PREFIX_NAME_SUCCESS)) { + // fill bundle with a success result. + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + } else if (account.name.startsWith(Fixtures.PREFIX_NAME_INTERVENE)) { + // Specify data to be returned by the eventual activity. + Intent eventualActivityResultData = new Intent(); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name); + eventualActivityResultData.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type); + + // Fill result with Intent. + Intent intent = new Intent(mContext, TestAuthenticatorActivity.class); + intent.putExtra(Fixtures.KEY_RESULT, eventualActivityResultData); + intent.putExtra(Fixtures.KEY_CALLBACK, response); + + result.putParcelable(AccountManager.KEY_INTENT, intent); + } else { + // fill with error + // fill with error + int errorCode = AccountManager.ERROR_CODE_INVALID_RESPONSE; + String errorMsg = "Default Error Message"; + if (options != null) { + errorCode = options.getInt(AccountManager.KEY_ERROR_CODE); + errorMsg = options.getString(AccountManager.KEY_ERROR_MESSAGE); + } + result.putInt(AccountManager.KEY_ERROR_CODE, errorCode); + result.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg); + } + + try { + return (isCallbackRequired) ? null : result; + } finally { + if (isCallbackRequired) { + response.onResult(result); + } + } + } + + @Override + public Bundle hasFeatures( + AccountAuthenticatorResponse response, + Account account, + String[] features) throws NetworkErrorException { + if (!mAccountType.equals(account.type)) { + throw new IllegalArgumentException("Request to the wrong authenticator!"); + } + Bundle result = new Bundle(); + AuthenticatorContentProvider.setTx( + new HasFeaturesTx(account, features, result)); + boolean isCallbackRequired = + Arrays.asList(features).contains(Fixtures.KEY_CALLBACK_REQUIRED); + if (account.name.startsWith(Fixtures.PREFIX_NAME_SUCCESS)) { + // fill bundle with a success result. + result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + } else if (account.name.startsWith(Fixtures.PREFIX_NAME_INTERVENE)) { + // Specify data to be returned by the eventual activity. + Intent eventualActivityResultData = new Intent(); + eventualActivityResultData.putExtra(AccountManager.KEY_BOOLEAN_RESULT, true); + + Intent intent = new Intent(mContext, TestAuthenticatorActivity.class); + intent.putExtra(Fixtures.KEY_RESULT, eventualActivityResultData); + intent.putExtra(Fixtures.KEY_CALLBACK, response); + + result.putParcelable(AccountManager.KEY_INTENT, intent); + } else { + // fill with error + } + + try { + return (isCallbackRequired) ? null : result; + } finally { + if (isCallbackRequired) { + response.onResult(result); + } + } + } +} +
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/TestAuthenticatorActivity.java b/tests/tests/accounts/common/src/android/accounts/cts/common/TestAuthenticatorActivity.java new file mode 100644 index 0000000..83c0533 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/TestAuthenticatorActivity.java
@@ -0,0 +1,39 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts.common; + +import android.accounts.AccountAuthenticatorResponse; +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +public class TestAuthenticatorActivity extends Activity { + + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + Intent intent = getIntent(); + AccountAuthenticatorResponse response = intent.getParcelableExtra(Fixtures.KEY_CALLBACK); + Intent result = intent.getParcelableExtra(Fixtures.KEY_RESULT); + if (response != null) { + response.onResult(result.getExtras()); + } + setResult(RESULT_OK, result); + finish(); + } +} +
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.aidl new file mode 100644 index 0000000..912322a --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable AddAccountTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.java new file mode 100644 index 0000000..3d829315 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/AddAccountTx.java
@@ -0,0 +1,70 @@ +package android.accounts.cts.common.tx; + +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +import java.util.ArrayList; +import java.util.List; + +public class AddAccountTx implements Parcelable { + + public static final Parcelable.Creator<AddAccountTx> CREATOR = + new Parcelable.Creator<AddAccountTx>() { + + @Override + public AddAccountTx createFromParcel(Parcel in) { + return new AddAccountTx(in); + } + + @Override + public AddAccountTx[] newArray(int size) { + return new AddAccountTx[size]; + } + }; + + public final String accountType; + public final String authTokenType; + public final List<String> requiredFeatures = new ArrayList<>(); + public final Bundle options; + public final Bundle result; + + private AddAccountTx(Parcel in) { + accountType = in.readString(); + authTokenType = in.readString(); + in.readStringList(requiredFeatures); + options = in.readBundle(); + result = in.readBundle(); + } + + public AddAccountTx( + String accountType, + String authTokenType, + String[] requiredFeatures, + Bundle options, + Bundle result) { + this.accountType = accountType; + this.authTokenType = authTokenType; + if (requiredFeatures != null) { + for (String feature : requiredFeatures) { + this.requiredFeatures.add(feature); + } + } + this.options = options; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeString(accountType); + out.writeString(authTokenType); + out.writeStringList(requiredFeatures); + out.writeBundle(options); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.aidl new file mode 100644 index 0000000..98a6367 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable ConfirmCredentialsTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.java new file mode 100644 index 0000000..d73b0a5 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/ConfirmCredentialsTx.java
@@ -0,0 +1,54 @@ +package android.accounts.cts.common.tx; + +import android.accounts.Account; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +public class ConfirmCredentialsTx implements Parcelable { + + public static final Parcelable.Creator<ConfirmCredentialsTx> CREATOR = + new Parcelable.Creator<ConfirmCredentialsTx>() { + + @Override + public ConfirmCredentialsTx createFromParcel(Parcel in) { + return new ConfirmCredentialsTx(in); + } + + @Override + public ConfirmCredentialsTx[] newArray(int size) { + return new ConfirmCredentialsTx[size]; + } + }; + + public final Account account; + public final Bundle options; + public final Bundle result; + + private ConfirmCredentialsTx(Parcel in) { + account = in.readParcelable(null); + options = in.readBundle(); + result = in.readBundle(); + } + + public ConfirmCredentialsTx( + Account account, + Bundle options, + Bundle result) { + this.account = account; + this.options = options; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeParcelable(account, flags); + out.writeBundle(options); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.aidl new file mode 100644 index 0000000..d9e813f --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable EditPropertiesTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.java new file mode 100644 index 0000000..4eba64d --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/EditPropertiesTx.java
@@ -0,0 +1,48 @@ +package android.accounts.cts.common.tx; + +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +public class EditPropertiesTx implements Parcelable { + + public static final Parcelable.Creator<EditPropertiesTx> CREATOR = + new Parcelable.Creator<EditPropertiesTx>() { + + @Override + public EditPropertiesTx createFromParcel(Parcel in) { + return new EditPropertiesTx(in); + } + + @Override + public EditPropertiesTx[] newArray(int size) { + return new EditPropertiesTx[size]; + } + }; + + public final String accountType; + public final Bundle result; + + private EditPropertiesTx(Parcel in) { + accountType = in.readString(); + result = in.readBundle(); + } + + public EditPropertiesTx( + String accountType, + Bundle result) { + this.accountType = accountType; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeString(accountType); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.aidl new file mode 100644 index 0000000..cbcd99d --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable GetAccountRemovalAllowedTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.java new file mode 100644 index 0000000..0e456b0 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAccountRemovalAllowedTx.java
@@ -0,0 +1,49 @@ +package android.accounts.cts.common.tx; + +import android.accounts.Account; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +public class GetAccountRemovalAllowedTx implements Parcelable { + + public static final Parcelable.Creator<GetAccountRemovalAllowedTx> CREATOR = + new Parcelable.Creator<GetAccountRemovalAllowedTx>() { + + @Override + public GetAccountRemovalAllowedTx createFromParcel(Parcel in) { + return new GetAccountRemovalAllowedTx(in); + } + + @Override + public GetAccountRemovalAllowedTx[] newArray(int size) { + return new GetAccountRemovalAllowedTx[size]; + } + }; + + public final Account account; + public final Bundle result; + + private GetAccountRemovalAllowedTx(Parcel in) { + account = in.readParcelable(null); + result = in.readBundle(); + } + + public GetAccountRemovalAllowedTx( + Account account, + Bundle result) { + this.account = account; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeParcelable(account, flags); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.aidl new file mode 100644 index 0000000..82aeb9e --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable GetAuthTokenLabelTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.java new file mode 100644 index 0000000..4a017dd --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenLabelTx.java
@@ -0,0 +1,47 @@ +package android.accounts.cts.common.tx; + +import android.os.Parcel; +import android.os.Parcelable; + +public class GetAuthTokenLabelTx implements Parcelable { + + public static final Parcelable.Creator<GetAuthTokenLabelTx> CREATOR = + new Parcelable.Creator<GetAuthTokenLabelTx>() { + + @Override + public GetAuthTokenLabelTx createFromParcel(Parcel in) { + return new GetAuthTokenLabelTx(in); + } + + @Override + public GetAuthTokenLabelTx[] newArray(int size) { + return new GetAuthTokenLabelTx[size]; + } + }; + + public final String authTokenType; + public final String result; + + private GetAuthTokenLabelTx(Parcel in) { + authTokenType = in.readString(); + result = in.readString(); + } + + public GetAuthTokenLabelTx( + String authTokenType, + String result) { + this.authTokenType = authTokenType; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeString(authTokenType); + out.writeString(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.aidl new file mode 100644 index 0000000..4ff5abb --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable GetAuthTokenTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.java new file mode 100644 index 0000000..c328353 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/GetAuthTokenTx.java
@@ -0,0 +1,59 @@ +package android.accounts.cts.common.tx; + +import android.accounts.Account; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +public class GetAuthTokenTx implements Parcelable { + + public static final Parcelable.Creator<GetAuthTokenTx> CREATOR = + new Parcelable.Creator<GetAuthTokenTx>() { + + @Override + public GetAuthTokenTx createFromParcel(Parcel in) { + return new GetAuthTokenTx(in); + } + + @Override + public GetAuthTokenTx[] newArray(int size) { + return new GetAuthTokenTx[size]; + } + }; + + public final Account account; + public final String authTokenType; + public final Bundle options; + public final Bundle result; + + private GetAuthTokenTx(Parcel in) { + account = in.readParcelable(null); + authTokenType = in.readString(); + options = in.readBundle(); + result = in.readBundle(); + } + + public GetAuthTokenTx( + Account account, + String authTokenType, + Bundle options, + Bundle result) { + this.account = account; + this.authTokenType = authTokenType; + this.options = options; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeParcelable(account, flags); + out.writeString(authTokenType); + out.writeBundle(options); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.aidl new file mode 100644 index 0000000..20b4a67 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable HasFeaturesTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.java new file mode 100644 index 0000000..81d3446 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/HasFeaturesTx.java
@@ -0,0 +1,61 @@ +package android.accounts.cts.common.tx; + +import android.accounts.Account; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +import java.util.ArrayList; +import java.util.List; + +public class HasFeaturesTx implements Parcelable { + + public static final Parcelable.Creator<HasFeaturesTx> CREATOR = + new Parcelable.Creator<HasFeaturesTx>() { + + @Override + public HasFeaturesTx createFromParcel(Parcel in) { + return new HasFeaturesTx(in); + } + + @Override + public HasFeaturesTx[] newArray(int size) { + return new HasFeaturesTx[size]; + } + }; + + public final Account account; + public final List<String> features = new ArrayList<>(); + public final Bundle result; + + private HasFeaturesTx(Parcel in) { + account = in.readParcelable(null); + in.readStringList(features); + result = in.readBundle(); + } + + public HasFeaturesTx( + Account account, + String[] features, + Bundle result) { + this.account = account; + if (features != null) { + for (String feature : features) { + this.features.add(feature); + } + } + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeParcelable(account, flags); + out.writeStringList(features); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.aidl b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.aidl new file mode 100644 index 0000000..8106242 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.aidl
@@ -0,0 +1,3 @@ +package android.accounts.cts.common.tx; + +parcelable UpdateCredentialsTx;
diff --git a/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.java b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.java new file mode 100644 index 0000000..ed2e082 --- /dev/null +++ b/tests/tests/accounts/common/src/android/accounts/cts/common/tx/UpdateCredentialsTx.java
@@ -0,0 +1,59 @@ +package android.accounts.cts.common.tx; + +import android.accounts.Account; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +public class UpdateCredentialsTx implements Parcelable { + + public static final Parcelable.Creator<UpdateCredentialsTx> CREATOR = + new Parcelable.Creator<UpdateCredentialsTx>() { + + @Override + public UpdateCredentialsTx createFromParcel(Parcel in) { + return new UpdateCredentialsTx(in); + } + + @Override + public UpdateCredentialsTx[] newArray(int size) { + return new UpdateCredentialsTx[size]; + } + }; + + public final Account account; + public final String authTokenType; + public final Bundle options; + public final Bundle result; + + private UpdateCredentialsTx(Parcel in) { + account = in.readParcelable(null); + authTokenType = in.readString(); + options = in.readBundle(); + result = in.readBundle(); + } + + public UpdateCredentialsTx( + Account account, + String authTokenType, + Bundle options, + Bundle result) { + this.account = account; + this.authTokenType = authTokenType; + this.options = options; + this.result = result; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel out, int flags) { + out.writeParcelable(account, flags); + out.writeString(authTokenType); + out.writeBundle(options); + out.writeBundle(result); + } +}
diff --git a/tests/tests/accounts/res/drawable/ic_cts_minitab_selected_custom_account.png b/tests/tests/accounts/res/drawable/ic_cts_minitab_selected_custom_account.png new file mode 100644 index 0000000..3fbbc94 --- /dev/null +++ b/tests/tests/accounts/res/drawable/ic_cts_minitab_selected_custom_account.png Binary files differ
diff --git a/tests/tests/accounts/res/drawable/ic_cts_selected_custom_account.png b/tests/tests/accounts/res/drawable/ic_cts_selected_custom_account.png new file mode 100644 index 0000000..70e35c0 --- /dev/null +++ b/tests/tests/accounts/res/drawable/ic_cts_selected_custom_account.png Binary files differ
diff --git a/tests/tests/accounts/res/xml/custom_token_authenticator.xml b/tests/tests/accounts/res/xml/custom_token_authenticator.xml new file mode 100644 index 0000000..3337917 --- /dev/null +++ b/tests/tests/accounts/res/xml/custom_token_authenticator.xml
@@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +/** + * Copyright (c) 2009, 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. + */ +--> + +<!-- The attributes in this XML file provide configuration information --> +<!-- for the Account Manager. --> + +<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" + android:accountType="android.accounts.cts.custom.account.type" + android:icon="@drawable/ic_cts_selected_custom_account" + android:smallIcon="@drawable/ic_cts_minitab_selected_custom_account" + android:customTokens="true" + android:label="@string/label" +/>
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java index b2a48e6..4350191 100644 --- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java +++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -26,16 +26,19 @@ import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Context; -import android.content.Intent; import android.os.Bundle; import android.os.Handler; +import android.os.HandlerThread; import android.os.Looper; import android.os.StrictMode; import android.test.ActivityInstrumentationTestCase2; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; /** * You can run those unit tests with the following command line: @@ -52,13 +55,15 @@ public static final String ACCOUNT_NAME_OTHER = "android.accounts.cts.account.name.other"; public static final String ACCOUNT_TYPE = "android.accounts.cts.account.type"; - public static final String ACCOUNT_TYPE_OTHER = "android.accounts.cts.account.type.other"; + public static final String ACCOUNT_TYPE_CUSTOM = "android.accounts.cts.custom.account.type"; + public static final String ACCOUNT_TYPE_ABSENT = "android.accounts.cts.account.type.absent"; public static final String ACCOUNT_PASSWORD = "android.accounts.cts.account.password"; - public static final String AUTH_TOKEN = "mockAuthToken"; public static final String AUTH_TOKEN_TYPE = "mockAuthTokenType"; + public static final String AUTH_EXPIRING_TOKEN_TYPE = "mockAuthExpiringTokenType"; public static final String AUTH_TOKEN_LABEL = "mockAuthTokenLabel"; + public static final long AUTH_TOKEN_DURATION_MILLIS = 10000L; // Ten seconds. public static final String FEATURE_1 = "feature.1"; public static final String FEATURE_2 = "feature.2"; @@ -86,6 +91,9 @@ MockAccountAuthenticator.ACCOUNT_NAME_FOR_NEW_REMOVE_API, ACCOUNT_TYPE); public static final Account ACCOUNT_SAME_TYPE = new Account(ACCOUNT_NAME_OTHER, ACCOUNT_TYPE); + public static final Account CUSTOM_TOKEN_ACCOUNT = + new Account(ACCOUNT_NAME,ACCOUNT_TYPE_CUSTOM); + private static MockAccountAuthenticator mockAuthenticator; private static final int LATCH_TIMEOUT_MS = 500; private static AccountManager am; @@ -130,16 +138,101 @@ assertTrue(removeAccount(am, ACCOUNT_SAME_TYPE, mActivity, null /* callback */).getBoolean( AccountManager.KEY_BOOLEAN_RESULT)); + // Clean out any other accounts added during the tests. + Account[] ctsAccounts = am.getAccountsByType(ACCOUNT_TYPE); + Account[] ctsCustomAccounts = am.getAccountsByType(ACCOUNT_TYPE_CUSTOM); + ArrayList<Account> accounts = new ArrayList<>(Arrays.asList(ctsAccounts)); + accounts.addAll(Arrays.asList(ctsCustomAccounts)); + for (Account ctsAccount : accounts) { + removeAccount(am, ctsAccount, mActivity, null /* callback */); + } + // need to clean up the authenticator cached data mockAuthenticator.clearData(); super.tearDown(); } - private void validateAccountAndAuthTokenResult(Bundle result) { - assertEquals(ACCOUNT_NAME, result.get(AccountManager.KEY_ACCOUNT_NAME)); - assertEquals(ACCOUNT_TYPE, result.get(AccountManager.KEY_ACCOUNT_TYPE)); - assertEquals(AUTH_TOKEN, result.get(AccountManager.KEY_AUTHTOKEN)); + interface TokenFetcher { + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException; + public Account getAccount(); + } + + private void validateSuccessfulTokenFetchingLifecycle(TokenFetcher fetcher, String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + Account account = fetcher.getAccount(); + Bundle expected = new Bundle(); + expected.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + expected.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + + // First fetch. + Bundle actual = fetcher.fetch(tokenType); + assertTrue(mockAuthenticator.isRecentlyCalled()); + validateAccountAndAuthTokenResult(expected, actual); + + /* + * On the second fetch the cache will be populated if we are using a authenticator with + * customTokens=false or we are using a scope that will cause the authenticator to set an + * expiration time (and that expiration time hasn't been reached). + */ + actual = fetcher.fetch(tokenType); + + boolean isCachingExpected = + ACCOUNT_TYPE.equals(account.type) || AUTH_EXPIRING_TOKEN_TYPE.equals(tokenType); + assertEquals(isCachingExpected, !mockAuthenticator.isRecentlyCalled()); + validateAccountAndAuthTokenResult(expected, actual); + + try { + // Delay further execution until expiring tokens can actually expire. + Thread.sleep(mockAuthenticator.getTokenDurationMillis() + 1L); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + /* + * With the time shift above, the third request will result in cache hits only from + * customToken=false authenticators. + */ + actual = fetcher.fetch(tokenType); + isCachingExpected = ACCOUNT_TYPE.equals(account.type); + assertEquals(isCachingExpected, !mockAuthenticator.isRecentlyCalled()); + validateAccountAndAuthTokenResult(expected, actual); + + // invalidate token + String token = actual.getString(AccountManager.KEY_AUTHTOKEN); + am.invalidateAuthToken(account.type, token); + + /* + * Upon invalidating the token, the cache should be clear regardless of authenticator. + */ + actual = fetcher.fetch(tokenType); + assertTrue(mockAuthenticator.isRecentlyCalled()); + validateAccountAndAuthTokenResult(expected, actual); + } + + private void validateAccountAndAuthTokenResult(Bundle actual) { + assertEquals( + ACCOUNT.name, + actual.get(AccountManager.KEY_ACCOUNT_NAME)); + assertEquals( + ACCOUNT.type, + actual.get(AccountManager.KEY_ACCOUNT_TYPE)); + assertEquals( + mockAuthenticator.getLastTokenServed(), + actual.get(AccountManager.KEY_AUTHTOKEN)); + } + + private void validateAccountAndAuthTokenResult(Bundle expected, Bundle actual) { + assertEquals( + expected.get(AccountManager.KEY_ACCOUNT_NAME), + actual.get(AccountManager.KEY_ACCOUNT_NAME)); + assertEquals( + expected.get(AccountManager.KEY_ACCOUNT_TYPE), + actual.get(AccountManager.KEY_ACCOUNT_TYPE)); + assertEquals( + mockAuthenticator.getLastTokenServed(), + actual.get(AccountManager.KEY_AUTHTOKEN)); } private void validateAccountAndNoAuthTokenResult(Bundle result) { @@ -224,7 +317,6 @@ private boolean removeAccount(AccountManager am, Account account, AccountManagerCallback<Boolean> callback) throws IOException, AuthenticatorException, OperationCanceledException { - AccountManagerFuture<Boolean> futureBoolean = am.removeAccount(account, callback, null /* handler */); @@ -357,6 +449,7 @@ final CountDownLatch latch = new CountDownLatch(1); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { Bundle resultBundle = null; try { @@ -483,9 +576,7 @@ /** * Test addAccountExplicitly() and removeAccountExplictly(). */ - public void testAddAccountExplicitlyAndRemoveAccountExplicitly() throws IOException, - AuthenticatorException, OperationCanceledException { - + public void testAddAccountExplicitlyAndRemoveAccountExplicitly() { final int expectedAccountsCount = getAccountsCount(); addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); @@ -581,7 +672,7 @@ assertEquals(2, accounts.length); // Check if we dont have any account from the other type - accounts = am.getAccountsByType(ACCOUNT_TYPE_OTHER); + accounts = am.getAccountsByType(ACCOUNT_TYPE_ABSENT); assertEquals(0, accounts.length); } @@ -684,6 +775,7 @@ final CountDownLatch latch1 = new CountDownLatch(1); AccountManagerCallback<Account[]> callback1 = new AccountManagerCallback<Account[]>() { + @Override public void run(AccountManagerFuture<Account[]> accountsFuture) { try { Account[] accounts = accountsFuture.getResult(); @@ -724,6 +816,7 @@ final CountDownLatch latch2 = new CountDownLatch(1); AccountManagerCallback<Account[]> callback2 = new AccountManagerCallback<Account[]>() { + @Override public void run(AccountManagerFuture<Account[]> accountsFuture) { try { Account[] accounts = accountsFuture.getResult(); @@ -765,25 +858,24 @@ */ public void testSetAndPeekAndInvalidateAuthToken() { addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); - - am.setAuthToken(ACCOUNT, AUTH_TOKEN_TYPE, AUTH_TOKEN); + String expected = "x"; + am.setAuthToken(ACCOUNT, AUTH_TOKEN_TYPE, expected); // Ask for the AuthToken String token = am.peekAuthToken(ACCOUNT, AUTH_TOKEN_TYPE); assertNotNull(token); - assertEquals(AUTH_TOKEN, token); + assertEquals(expected, token); - am.invalidateAuthToken(ACCOUNT_TYPE, AUTH_TOKEN); + am.invalidateAuthToken(ACCOUNT_TYPE, token); token = am.peekAuthToken(ACCOUNT, AUTH_TOKEN_TYPE); assertNull(token); } /** - * Test blockingGetAuthToken() + * Test successful blockingGetAuthToken() with customTokens=false authenticator. */ - public void testBlockingGetAuthToken() throws IOException, AuthenticatorException, - OperationCanceledException { - + public void testBlockingGetAuthToken_DefaultToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null); String token = am.blockingGetAuthToken(ACCOUNT, @@ -792,17 +884,61 @@ // Ask for the AuthToken assertNotNull(token); - assertEquals(AUTH_TOKEN, token); + assertEquals(mockAuthenticator.getLastTokenServed(), token); + } + + private static class BlockingGetAuthTokenFetcher implements TokenFetcher { + private final Account mAccount; + + BlockingGetAuthTokenFetcher(Account account) { + mAccount = account; + } + + @Override + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + String token = am.blockingGetAuthToken( + getAccount(), + tokenType, + false /* no failure notification */); + Bundle result = new Bundle(); + result.putString(AccountManager.KEY_AUTHTOKEN, token); + result.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type); + return result; + } + @Override + public Account getAccount() { + return CUSTOM_TOKEN_ACCOUNT; + } } /** - * Test getAuthToken() + * Test successful blockingGetAuthToken() with customTokens=true authenticator. */ - public void testGetAuthToken() throws IOException, AuthenticatorException, - OperationCanceledException { + public void testBlockingGetAuthToken_CustomToken_NoCaching_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(CUSTOM_TOKEN_ACCOUNT, ACCOUNT_PASSWORD, null); + TokenFetcher f = new BlockingGetAuthTokenFetcher(CUSTOM_TOKEN_ACCOUNT); + validateSuccessfulTokenFetchingLifecycle(f, AUTH_TOKEN_TYPE); + } + /** + * Test successful blockingGetAuthToken() with customTokens=true authenticator. + */ + public void testBlockingGetAuthToken_CustomToken_ExpiringCache_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(CUSTOM_TOKEN_ACCOUNT, ACCOUNT_PASSWORD, null); + TokenFetcher f = new BlockingGetAuthTokenFetcher(CUSTOM_TOKEN_ACCOUNT); + validateSuccessfulTokenFetchingLifecycle(f, AUTH_EXPIRING_TOKEN_TYPE); + } + + /** + * Test successful getAuthToken() using a future with customTokens=false authenticator. + */ + public void testDeprecatedGetAuthTokenWithFuture_NoOptions_DefaultToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); - AccountManagerFuture<Bundle> futureBundle = am.getAuthToken(ACCOUNT, AUTH_TOKEN_TYPE, false /* no failure notification */, @@ -820,6 +956,226 @@ } /** + * Test successful getAuthToken() using a future with customTokens=false without + * expiring tokens. + */ + public void testDeprecatedGetAuthTokenWithFuture_NoOptions_CustomToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(CUSTOM_TOKEN_ACCOUNT, ACCOUNT_PASSWORD, null); + // validateSuccessfulTokenFetchingLifecycle(AccountManager am, TokenFetcher fetcher, String tokenType) + TokenFetcher f = new TokenFetcher() { + @Override + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + AccountManagerFuture<Bundle> futureBundle = am.getAuthToken( + getAccount(), + tokenType, + false /* no failure notification */, + null /* no callback */, + null /* no handler */ + ); + Bundle actual = futureBundle.getResult(); + assertTrue(futureBundle.isDone()); + assertNotNull(actual); + return actual; + } + + @Override + public Account getAccount() { + return CUSTOM_TOKEN_ACCOUNT; + } + }; + validateSuccessfulTokenFetchingLifecycle(f, AUTH_EXPIRING_TOKEN_TYPE); + validateSuccessfulTokenFetchingLifecycle(f, AUTH_TOKEN_TYPE); + } + + /** + * Test successful getAuthToken() using a future with customTokens=false without + * expiring tokens. + */ + public void testGetAuthTokenWithFuture_Options_DefaultToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); + + AccountManagerFuture<Bundle> futureBundle = am.getAuthToken(ACCOUNT, + AUTH_TOKEN_TYPE, + OPTIONS_BUNDLE, + mActivity, + null /* no callback */, + null /* no handler */ + ); + + Bundle resultBundle = futureBundle.getResult(); + + assertTrue(futureBundle.isDone()); + assertNotNull(resultBundle); + + // Assert returned result + validateAccountAndAuthTokenResult(resultBundle); + + validateOptions(null, mockAuthenticator.mOptionsAddAccount); + validateOptions(null, mockAuthenticator.mOptionsUpdateCredentials); + validateOptions(null, mockAuthenticator.mOptionsConfirmCredentials); + validateOptions(OPTIONS_BUNDLE, mockAuthenticator.mOptionsGetAuthToken); + validateSystemOptions(mockAuthenticator.mOptionsGetAuthToken); + } + + /** + * Test successful getAuthToken() using a future with customTokens=false without + * expiring tokens. + */ + public void testGetAuthTokenWithFuture_Options_CustomToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(CUSTOM_TOKEN_ACCOUNT, ACCOUNT_PASSWORD, null); + TokenFetcher fetcherWithOptions = new TokenFetcher() { + @Override + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + AccountManagerFuture<Bundle> futureBundle = am.getAuthToken( + getAccount(), + tokenType, + OPTIONS_BUNDLE, + false /* no failure notification */, + null /* no callback */, + null /* no handler */ + ); + Bundle actual = futureBundle.getResult(); + assertTrue(futureBundle.isDone()); + assertNotNull(actual); + return actual; + } + + @Override + public Account getAccount() { + return CUSTOM_TOKEN_ACCOUNT; + } + }; + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_TOKEN_TYPE); + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_EXPIRING_TOKEN_TYPE); + } + + + /** + * Test successful getAuthToken() using a future with customTokens=false without + * expiring tokens. + */ + public void testGetAuthTokenWithCallback_Options_Handler_DefaultToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null); + final HandlerThread handlerThread = new HandlerThread("accounts.test"); + handlerThread.start(); + TokenFetcher fetcherWithOptions = new TokenFetcher() { + @Override + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + final AtomicReference<Bundle> actualRef = new AtomicReference<>(); + final CountDownLatch latch = new CountDownLatch(1); + + AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override + public void run(AccountManagerFuture<Bundle> bundleFuture) { + Bundle resultBundle = null; + try { + resultBundle = bundleFuture.getResult(); + actualRef.set(resultBundle); + } catch (OperationCanceledException e) { + fail("should not throw an OperationCanceledException"); + } catch (IOException e) { + fail("should not throw an IOException"); + } catch (AuthenticatorException e) { + fail("should not throw an AuthenticatorException"); + } finally { + latch.countDown(); + } + } + }; + + am.getAuthToken(getAccount(), + tokenType, + OPTIONS_BUNDLE, + false /* no failure notification */, + callback, + new Handler(handlerThread.getLooper())); + + // Wait with timeout for the callback to do its work + try { + latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + fail("should not throw an InterruptedException"); + } + return actualRef.get(); + } + + @Override + public Account getAccount() { + return ACCOUNT; + } + }; + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_TOKEN_TYPE); + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_EXPIRING_TOKEN_TYPE); + } + + /** + * Test successful getAuthToken() using a future with customTokens=false without + * expiring tokens. + */ + public void testGetAuthTokenWithCallback_Options_Handler_CustomToken_Success() + throws IOException, AuthenticatorException, OperationCanceledException { + addAccountExplicitly(CUSTOM_TOKEN_ACCOUNT, ACCOUNT_PASSWORD, null); + final HandlerThread handlerThread = new HandlerThread("accounts.test"); + handlerThread.start(); + TokenFetcher fetcherWithOptions = new TokenFetcher() { + @Override + public Bundle fetch(String tokenType) + throws OperationCanceledException, AuthenticatorException, IOException { + final AtomicReference<Bundle> actualRef = new AtomicReference<>(); + final CountDownLatch latch = new CountDownLatch(1); + + AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override + public void run(AccountManagerFuture<Bundle> bundleFuture) { + Bundle resultBundle = null; + try { + resultBundle = bundleFuture.getResult(); + actualRef.set(resultBundle); + } catch (OperationCanceledException e) { + fail("should not throw an OperationCanceledException"); + } catch (IOException e) { + fail("should not throw an IOException"); + } catch (AuthenticatorException e) { + fail("should not throw an AuthenticatorException"); + } finally { + latch.countDown(); + } + } + }; + + am.getAuthToken(getAccount(), + tokenType, + OPTIONS_BUNDLE, + false /* no failure notification */, + callback, + new Handler(handlerThread.getLooper())); + + // Wait with timeout for the callback to do its work + try { + latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + fail("should not throw an InterruptedException"); + } + return actualRef.get(); + } + + @Override + public Account getAccount() { + return CUSTOM_TOKEN_ACCOUNT; + } + }; + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_TOKEN_TYPE); + validateSuccessfulTokenFetchingLifecycle(fetcherWithOptions, AUTH_EXPIRING_TOKEN_TYPE); + } + + /** * Test getAuthToken() with callback and handler */ public void testGetAuthTokenWithCallbackAndHandler() throws IOException, AuthenticatorException, @@ -837,6 +1193,7 @@ final CountDownLatch latch = new CountDownLatch(1); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { Bundle resultBundle = null; @@ -880,37 +1237,6 @@ } /** - * test getAuthToken() with options - */ - public void testGetAuthTokenWithOptions() throws IOException, AuthenticatorException, - OperationCanceledException { - - addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); - - AccountManagerFuture<Bundle> futureBundle = am.getAuthToken(ACCOUNT, - AUTH_TOKEN_TYPE, - OPTIONS_BUNDLE, - mActivity, - null /* no callback */, - null /* no handler */ - ); - - Bundle resultBundle = futureBundle.getResult(); - - assertTrue(futureBundle.isDone()); - assertNotNull(resultBundle); - - // Assert returned result - validateAccountAndAuthTokenResult(resultBundle); - - validateOptions(null, mockAuthenticator.mOptionsAddAccount); - validateOptions(null, mockAuthenticator.mOptionsUpdateCredentials); - validateOptions(null, mockAuthenticator.mOptionsConfirmCredentials); - validateOptions(OPTIONS_BUNDLE, mockAuthenticator.mOptionsGetAuthToken); - validateSystemOptions(mockAuthenticator.mOptionsGetAuthToken); - } - - /** * test getAuthToken() with options and callback and handler */ public void testGetAuthTokenWithOptionsAndCallback() throws IOException, @@ -928,15 +1254,14 @@ final CountDownLatch latch = new CountDownLatch(1); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { Bundle resultBundle = null; try { resultBundle = bundleFuture.getResult(); - // Assert returned result validateAccountAndAuthTokenResult(resultBundle); - } catch (OperationCanceledException e) { fail("should not throw an OperationCanceledException"); } catch (IOException e) { @@ -1039,7 +1364,6 @@ validateOptions(null, mockAuthenticator.mOptionsUpdateCredentials); validateOptions(null, mockAuthenticator.mOptionsConfirmCredentials); validateOptions(null, mockAuthenticator.mOptionsGetAuthToken); - } /** @@ -1063,10 +1387,85 @@ } /** + * Tests the setting of lastAuthenticatedTime on adding account + */ + public void testLastAuthenticatedTimeAfterAddAccount() throws IOException, + AuthenticatorException, OperationCanceledException { + assertTrue(addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD) > 0); + } + + /** + * Test confirmCredentials() for account not on device. Just that no error + * should be thrown. + */ + public void testConfirmCredentialsAccountNotOnDevice() throws IOException, + AuthenticatorException, OperationCanceledException { + + Account account = new Account("AccountNotOnThisDevice", ACCOUNT_TYPE); + AccountManagerFuture<Bundle> futureBundle = am.confirmCredentials(account, + OPTIONS_BUNDLE, + mActivity, + null /* callback */, + null /* handler */); + + futureBundle.getResult(); + } + + /** + * Tests the setting of lastAuthenticatedTime on confirmCredentials being + * successful. + */ + public void testLastAuthenticatedTimeAfterConfirmCredentialsSuccess() throws IOException, + AuthenticatorException, OperationCanceledException { + + long accountAddTime = addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD); + + // Now this confirm credentials call returns true, which in turn + // should update the last authenticated timestamp. + Bundle result = am.confirmCredentials(ACCOUNT, + OPTIONS_BUNDLE, /* options */ + null, /* activity */ + null /* callback */, + null /* handler */).getResult(); + long confirmedCredTime = result.getLong( + AccountManager.KEY_LAST_AUTHENTICATED_TIME, -1); + assertTrue(confirmedCredTime > accountAddTime); + } + + /** + * Tests the setting of lastAuthenticatedTime on updateCredentials being + * successful. + */ + public void testLastAuthenticatedTimeAfterUpdateCredentialsSuccess() throws IOException, + AuthenticatorException, OperationCanceledException { + + long accountAddTime = addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD); + + am.updateCredentials(ACCOUNT, + AUTH_TOKEN_TYPE, + OPTIONS_BUNDLE, + mActivity, + null /* callback */, + null /* handler */).getResult(); + long updateCredTime = getLastAuthenticatedTime(ACCOUNT); + assertTrue(updateCredTime > accountAddTime); + } + + /** + * LastAuthenticatedTime on setPassword should not be disturbed. + */ + public void testLastAuthenticatedTimeAfterSetPassword() throws IOException, + AuthenticatorException, OperationCanceledException { + long accountAddTime = addAccountAndReturnAccountAddedTime(ACCOUNT, ACCOUNT_PASSWORD); + mockAuthenticator.callSetPassword(); + long setPasswordTime = getLastAuthenticatedTime(ACCOUNT); + assertTrue(setPasswordTime == accountAddTime); + } + + /** * Test confirmCredentials() with callback */ - public void testConfirmCredentialsWithCallbackAndHandler() throws IOException, - AuthenticatorException, OperationCanceledException { + public void testConfirmCredentialsWithCallbackAndHandler() { addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */); @@ -1074,12 +1473,10 @@ testConfirmCredentialsWithCallbackAndHandler(new Handler(Looper.getMainLooper())); } - private void testConfirmCredentialsWithCallbackAndHandler(Handler handler) throws IOException, - AuthenticatorException, OperationCanceledException { - + private void testConfirmCredentialsWithCallbackAndHandler(Handler handler) { final CountDownLatch latch = new CountDownLatch(1); - AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { Bundle resultBundle = null; @@ -1102,18 +1499,14 @@ } } }; - AccountManagerFuture<Bundle> futureBundle = am.confirmCredentials(ACCOUNT, OPTIONS_BUNDLE, mActivity, callback, handler); - - futureBundle.getResult(); - // Wait with timeout for the callback to do its work try { - latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); + latch.await(3 * LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { fail("should not throw an InterruptedException"); } @@ -1160,6 +1553,7 @@ final CountDownLatch latch = new CountDownLatch(1); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { Bundle resultBundle = null; @@ -1231,6 +1625,7 @@ final CountDownLatch latch = new CountDownLatch(1); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { + @Override public void run(AccountManagerFuture<Bundle> bundleFuture) { try { // Assert returned result @@ -1292,6 +1687,7 @@ final CountDownLatch latch = new CountDownLatch(1); OnAccountsUpdateListener listener = new OnAccountsUpdateListener() { + @Override public void onAccountsUpdated(Account[] accounts) { latch.countDown(); } @@ -1334,6 +1730,7 @@ final CountDownLatch latch = new CountDownLatch(1); OnAccountsUpdateListener listener = new OnAccountsUpdateListener() { + @Override public void onAccountsUpdated(Account[] accounts) { fail("should not be called"); } @@ -1424,6 +1821,7 @@ private AccountManagerCallback<Boolean> getAssertTrueCallback(final CountDownLatch latch) { return new AccountManagerCallback<Boolean>() { + @Override public void run(AccountManagerFuture<Boolean> booleanFuture) { try { // Assert returned result should be TRUE @@ -1439,6 +1837,7 @@ private AccountManagerCallback<Boolean> getAssertFalseCallback(final CountDownLatch latch) { return new AccountManagerCallback<Boolean>() { + @Override public void run(AccountManagerFuture<Boolean> booleanFuture) { try { // Assert returned result should be FALSE @@ -1519,11 +1918,37 @@ waitForLatch(latch); } + private long getLastAuthenticatedTime(Account account) throws OperationCanceledException, + AuthenticatorException, IOException { + Bundle options = new Bundle(); + options.putBoolean(MockAccountAuthenticator.KEY_RETURN_INTENT, true); + // Not really confirming, but a way to get last authenticated timestamp + Bundle result = am.confirmCredentials(account, + options,// OPTIONS_BUNDLE, + null, /* activity */ + null /* callback */, + null /* handler */).getResult(); + return result.getLong( + AccountManager.KEY_LAST_AUTHENTICATED_TIME, -1); + } + + private long addAccountAndReturnAccountAddedTime(Account account, String password) + throws OperationCanceledException, AuthenticatorException, IOException { + addAccount(am, + ACCOUNT_TYPE, + AUTH_TOKEN_TYPE, + REQUIRED_FEATURES, + OPTIONS_BUNDLE, + mActivity, + null /* callback */, + null /* handler */); + return getLastAuthenticatedTime(account); + } + /** * Tests that AccountManagerService is properly caching data. */ - public void testGetsAreCached() throws IOException, AuthenticatorException, - OperationCanceledException { + public void testGetsAreCached() { // Add an account, assertEquals(false, isAccountPresent(am.getAccounts(), ACCOUNT));
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java new file mode 100644 index 0000000..2068f4c --- /dev/null +++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerUnaffiliatedAuthenticatorTests.java
@@ -0,0 +1,226 @@ +/* + * Copyright (C) 2015 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 android.accounts.cts; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.accounts.AuthenticatorException; +import android.accounts.OperationCanceledException; +import android.accounts.cts.common.AuthenticatorContentProvider; +import android.accounts.cts.common.Fixtures; +import android.content.ContentProviderClient; +import android.content.ContentResolver; +import android.os.RemoteException; +import android.test.AndroidTestCase; + +import java.io.IOException; + +/** + * Tests for AccountManager and AbstractAccountAuthenticator related behavior using {@link + * android.accounts.cts.common.TestAccountAuthenticator} instances signed with different keys than + * the caller. This is important to test that portion of the {@link AccountManager} API intended + * for {@link android.accounts.AbstractAccountAuthenticator} implementers. + * <p> + * You can run those unit tests with the following command line: + * <p> + * adb shell am instrument + * -e debug false -w + * -e class android.accounts.cts.AccountManagerUnaffiliatedAuthenticatorTests + * android.accounts.cts/android.support.test.runner.AndroidJUnitRunner + */ +public class AccountManagerUnaffiliatedAuthenticatorTests extends AndroidTestCase { + + private AccountManager mAccountManager; + private ContentProviderClient mProviderClient; + + @Override + public void setUp() throws Exception { + // bind to the diagnostic service and set it up. + mAccountManager = AccountManager.get(getContext()); + ContentResolver resolver = getContext().getContentResolver(); + mProviderClient = resolver.acquireContentProviderClient( + AuthenticatorContentProvider.AUTHORITY); + /* + * This will install a bunch of accounts on the device + * (see Fixtures.getFixtureAccountNames()). + */ + mProviderClient.call(AuthenticatorContentProvider.METHOD_SETUP, null, null); + } + + @Override + public void tearDown() throws RemoteException { + try { + mProviderClient.call(AuthenticatorContentProvider.METHOD_TEARDOWN, null, null); + } finally { + mProviderClient.release(); + } + } + + public void testNotifyAccountAuthenticated() { + try { + mAccountManager.notifyAccountAuthenticated( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS); + fail("Expected to just barf if the caller doesn't share a signature."); + } catch (SecurityException expected) {} + } + + public void testEditProperties() { + try { + mAccountManager.editProperties( + Fixtures.TYPE_STANDARD_UNAFFILIATED, + null, // activity + null, // callback + null); // handler + fail("Expecting a OperationCanceledException."); + } catch (SecurityException expected) { + + } + } + + public void testAddAccountExplicitly() { + try { + mAccountManager.addAccountExplicitly( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "shouldn't matter", // password + null); // bundle + fail("addAccountExplicitly should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testRemoveAccount_withBooleanResult() { + try { + mAccountManager.removeAccount( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + null, + null); + fail("removeAccount should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testRemoveAccount_withBundleResult() { + try { + mAccountManager.removeAccount( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + null, // Activity + null, + null); + fail("removeAccount should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testRemoveAccountExplicitly() { + try { + mAccountManager.removeAccountExplicitly( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS); + fail("removeAccountExplicitly should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testGetPassword() { + try { + mAccountManager.getPassword( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS); + fail("getPassword should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testSetPassword() { + try { + mAccountManager.setPassword( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "Doesn't matter"); + fail("setPassword should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testClearPassword() { + try { + mAccountManager.clearPassword( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS); + fail("clearPassword should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testGetUserData() { + try { + mAccountManager.getUserData( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "key"); + fail("getUserData should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testSetUserData() { + try { + mAccountManager.setUserData( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "key", + "value"); + fail("setUserData should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void setAuthToken() { + try { + mAccountManager.setAuthToken( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "tokenType", + "token"); + fail("setAuthToken should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testPeekAuthToken() { + try { + mAccountManager.peekAuthToken( + Fixtures.ACCOUNT_UNAFFILIATED_FIXTURE_SUCCESS, + "tokenType"); + fail("peekAuthToken should just barf if the caller isn't permitted."); + } catch (SecurityException expected) {} + } + + public void testGetAccounts() { + Account[] accounts = mAccountManager.getAccounts(); + assertEquals(0, accounts.length); + } + + public void testGetAccountsByType() { + Account[] accounts = mAccountManager.getAccountsByType( + Fixtures.TYPE_STANDARD_UNAFFILIATED); + assertEquals(0, accounts.length); + } + + public void testGetAccountsByTypeAndFeatures() + throws OperationCanceledException, AuthenticatorException, IOException { + AccountManagerFuture<Account[]> future = mAccountManager.getAccountsByTypeAndFeatures( + Fixtures.TYPE_STANDARD_UNAFFILIATED, + new String[] { "doesn't matter" }, + null, // Callback + null); // Handler + Account[] accounts = future.getResult(); + assertEquals(0, accounts.length); + } + + public void testGetAccountsByTypeForPackage() { + Account[] accounts = mAccountManager.getAccountsByTypeForPackage( + Fixtures.TYPE_STANDARD_UNAFFILIATED, + getContext().getPackageName()); + assertEquals(0, accounts.length); + } +} +
diff --git a/tests/tests/accounts/src/android/accounts/cts/MockAccountAuthenticator.java b/tests/tests/accounts/src/android/accounts/cts/MockAccountAuthenticator.java index b5804d9..c1b08de 100644 --- a/tests/tests/accounts/src/android/accounts/cts/MockAccountAuthenticator.java +++ b/tests/tests/accounts/src/android/accounts/cts/MockAccountAuthenticator.java
@@ -24,19 +24,29 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.util.Log; import java.util.ArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; /** * A simple Mock Account Authenticator */ public class MockAccountAuthenticator extends AbstractAccountAuthenticator { + private static String TAG = "AccountManagerTest"; public static String KEY_ACCOUNT_INFO = "key_account_info"; public static String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "key_account_authenticator_response"; public static String ACCOUNT_NAME_FOR_NEW_REMOVE_API = "call new removeAccount api"; + // Key for triggering return intent flow + public static String KEY_RETURN_INTENT = "return an intent"; + public static String ACCOUNT_NAME_FOR_NEW_REMOVE_API1 = "call new removeAccount api"; private final Context mContext; + private final AtomicInteger mTokenCounter = new AtomicInteger(0); + private final AtomicBoolean mIsRecentlyCalled = new AtomicBoolean(false); + AccountAuthenticatorResponse mResponse; String mAccountType; String mAuthTokenType; @@ -49,6 +59,7 @@ String[] mFeatures; final ArrayList<String> mockFeatureList = new ArrayList<String>(); + private final long mTokenDurationMillis = 1000; // 1 second public MockAccountAuthenticator(Context context) { super(context); @@ -59,6 +70,18 @@ mockFeatureList.add(AccountManagerTest.FEATURE_2); } + public long getTokenDurationMillis() { + return mTokenDurationMillis; + } + + public boolean isRecentlyCalled() { + return mIsRecentlyCalled.getAndSet(false); + } + + public String getLastTokenServed() { + return Integer.toString(mTokenCounter.get()); + } + public AccountAuthenticatorResponse getResponse() { return mResponse; } @@ -96,12 +119,23 @@ mFeatures = null; } + public void callAccountAuthenticated() { + AccountManager am = AccountManager.get(mContext); + am.notifyAccountAuthenticated(mAccount); + } + + public void callSetPassword() { + AccountManager am = AccountManager.get(mContext); + am.setPassword(mAccount, "password"); + } + private Bundle createResultBundle() { Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, AccountManagerTest.ACCOUNT_NAME); result.putString(AccountManager.KEY_ACCOUNT_TYPE, AccountManagerTest.ACCOUNT_TYPE); - result.putString(AccountManager.KEY_AUTHTOKEN, AccountManagerTest.AUTH_TOKEN); - + result.putString( + AccountManager.KEY_AUTHTOKEN, + Integer.toString(mTokenCounter.incrementAndGet())); return result; } @@ -112,13 +146,13 @@ public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { - this.mResponse = response; this.mAccountType = accountType; this.mAuthTokenType = authTokenType; this.mRequiredFeatures = requiredFeatures; this.mOptionsAddAccount = options; - + AccountManager am = AccountManager.get(mContext); + am.addAccountExplicitly(AccountManagerTest.ACCOUNT, "fakePassword", null); return createResultBundle(); } @@ -128,12 +162,10 @@ @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { - this.mResponse = response; this.mAccount = account; this.mAuthTokenType = authTokenType; this.mOptionsUpdateCredentials = options; - return createResultBundle(); } @@ -144,10 +176,8 @@ */ @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { - this.mResponse = response; this.mAccountType = accountType; - return createResultBundle(); } @@ -157,13 +187,17 @@ @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { - this.mResponse = response; this.mAccount = account; this.mOptionsConfirmCredentials = options; - Bundle result = new Bundle(); - result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + if (options.containsKey(KEY_RETURN_INTENT)) { + Intent intent = new Intent(); + intent.setClassName("android.accounts.cts", "android.accounts.cts.AccountDummyActivity"); + result.putParcelable(AccountManager.KEY_INTENT, intent); + } else { + result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true); + } return result; } @@ -172,15 +206,35 @@ * Gets the authtoken for an account. */ @Override - public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, - String authTokenType, Bundle options) throws NetworkErrorException { - + public Bundle getAuthToken( + AccountAuthenticatorResponse response, + Account account, + String authTokenType, + Bundle options) throws NetworkErrorException { + Log.w(TAG, "MockAuth - getAuthToken@" + System.currentTimeMillis()); + mIsRecentlyCalled.set(true); this.mResponse = response; this.mAccount = account; this.mAuthTokenType = authTokenType; this.mOptionsGetAuthToken = options; + Bundle result = new Bundle(); - return createResultBundle(); + result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); + result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); + String token; + if (AccountManagerTest.AUTH_EXPIRING_TOKEN_TYPE.equals(authTokenType)) { + /* + * The resultant token should simply be the expiration timestamp. E.g. the time after + * which getting a new AUTH_EXPIRING_TOKEN_TYPE typed token will return a different + * value. + */ + long expiry = System.currentTimeMillis() + mTokenDurationMillis; + result.putLong(AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, expiry); + } + result.putString( + AccountManager.KEY_AUTHTOKEN, + Integer.toString(mTokenCounter.incrementAndGet())); + return result; } /** @@ -189,7 +243,6 @@ @Override public String getAuthTokenLabel(String authTokenType) { this.mAuthTokenType = authTokenType; - return AccountManagerTest.AUTH_TOKEN_LABEL; } @@ -242,4 +295,4 @@ } return result; } -} \ No newline at end of file +}
diff --git a/tests/tests/accounts/src/android/accounts/cts/MockCustomTokenAccountService.java b/tests/tests/accounts/src/android/accounts/cts/MockCustomTokenAccountService.java new file mode 100644 index 0000000..ea06a41 --- /dev/null +++ b/tests/tests/accounts/src/android/accounts/cts/MockCustomTokenAccountService.java
@@ -0,0 +1,13 @@ +package android.accounts.cts; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +public class MockCustomTokenAccountService extends Service { + + @Override + public IBinder onBind(Intent intent) { + return AccountManagerTest.getMockAuthenticator(this).getIBinder(); + } +}
diff --git a/tests/tests/admin/AndroidTest.xml b/tests/tests/admin/AndroidTest.xml new file mode 100644 index 0000000..c29d404 --- /dev/null +++ b/tests/tests/admin/AndroidTest.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="CTS device admin test config"> + <include name="common-config" /> + <option name="run-command:run-command" value="dpm set-active-admin android.deviceadmin.cts/.CtsDeviceAdminReceiver" /> + <option name="run-command:run-command" value="dpm set-active-admin android.deviceadmin.cts/.CtsDeviceAdminReceiver2" /> +</configuration>
diff --git a/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java b/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java index 513b67e..66e12c0 100644 --- a/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java +++ b/tests/tests/admin/src/android/admin/cts/DevicePolicyManagerTest.java
@@ -68,6 +68,8 @@ "VcUyQ1/e7WQgOaBHi9TefUJi+4PSVSluOXon\n" + "-----END CERTIFICATE-----"; + private static final String MANAGED_PROVISIONING_PKG = "com.android.managedprovisioning"; + @Override protected void setUp() throws Exception { super.setUp(); @@ -133,26 +135,29 @@ mDevicePolicyManager.getPasswordQuality(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertTrue(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); - assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); + String caseDescription = "initial"; + assertPasswordSucceeds("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10); + caseDescription = "minimum password length = 10"; assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordFails("abcd1234", caseDescription); - mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3); - assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); + mDevicePolicyManager.setPasswordMinimumLength(mComponent, 4); + caseDescription = "minimum password length = 4"; + assertEquals(4, mDevicePolicyManager.getPasswordMinimumLength( + mComponent)); assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); - assertTrue(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordSucceeds("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); } public void testPasswordQuality_numeric() { @@ -166,26 +171,29 @@ mDevicePolicyManager.getPasswordQuality(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertTrue(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); - assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); + String caseDescription = "initial"; + assertPasswordSucceeds("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10); + caseDescription = "minimum password length = 10"; assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordFails("abcd1234", caseDescription); - mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3); - assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); + mDevicePolicyManager.setPasswordMinimumLength(mComponent, 4); + caseDescription = "minimum password length = 4"; + assertEquals(4, mDevicePolicyManager.getPasswordMinimumLength( + mComponent)); assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); - assertTrue(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordSucceeds("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); } public void testPasswordQuality_alphabetic() { @@ -199,26 +207,29 @@ mDevicePolicyManager.getPasswordQuality(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); - assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); + String caseDescription = "initial"; + assertPasswordFails("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10); + caseDescription = "minimum password length = 10"; assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordFails("abcd1234", caseDescription); - mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3); - assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); + mDevicePolicyManager.setPasswordMinimumLength(mComponent, 4); + caseDescription = "minimum password length = 4"; + assertEquals(4, mDevicePolicyManager.getPasswordMinimumLength( + mComponent)); assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordSucceeds("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); } public void testPasswordQuality_alphanumeric() { @@ -232,26 +243,29 @@ mDevicePolicyManager.getPasswordQuality(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); - assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); + String caseDescription = "initial"; + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10); + caseDescription = "minimum password length = 10"; assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); assertFalse(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordFails("abcd1234", caseDescription); - mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3); - assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent)); + mDevicePolicyManager.setPasswordMinimumLength(mComponent, 4); + caseDescription = "minimum password length = 4"; + assertEquals(4, mDevicePolicyManager.getPasswordMinimumLength( + mComponent)); assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); - assertFalse(mDevicePolicyManager.resetPassword("123", 0)); - assertFalse(mDevicePolicyManager.resetPassword("abcd", 0)); - assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0)); + assertPasswordFails("1234", caseDescription); + assertPasswordFails("abcd", caseDescription); + assertPasswordSucceeds("abcd1234", caseDescription); } public void testPasswordQuality_complexUpperCase() { @@ -265,26 +279,29 @@ resetComplexPasswordRestrictions(); String caseDescription = "minimum UpperCase=0"; - assertPasswordSucceeds("abc", caseDescription); - assertPasswordSucceeds("aBc", caseDescription); - assertPasswordSucceeds("ABC", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); + assertPasswordSucceeds("aBc1", caseDescription); + assertPasswordSucceeds("ABC1", caseDescription); assertPasswordSucceeds("ABCD", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent)); caseDescription = "minimum UpperCase=1"; - assertPasswordFails("abc", caseDescription); - assertPasswordSucceeds("aBc", caseDescription); - assertPasswordSucceeds("ABC", caseDescription); + assertPasswordFails("abc1", caseDescription); + assertPasswordSucceeds("aBc1", caseDescription); + assertPasswordSucceeds("ABC1", caseDescription); assertPasswordSucceeds("ABCD", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent)); caseDescription = "minimum UpperCase=3"; - assertPasswordFails("abc", caseDescription); - assertPasswordFails("aBC", caseDescription); - assertPasswordSucceeds("ABC", caseDescription); + assertPasswordFails("abc1", caseDescription); + assertPasswordFails("aBC1", caseDescription); + assertPasswordSucceeds("ABC1", caseDescription); assertPasswordSucceeds("ABCD", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordQuality_complexLowerCase() { @@ -299,25 +316,28 @@ String caseDescription = "minimum LowerCase=0"; assertPasswordSucceeds("ABCD", caseDescription); - assertPasswordSucceeds("aBC", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordSucceeds("aBC1", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent)); caseDescription = "minimum LowerCase=1"; assertPasswordFails("ABCD", caseDescription); - assertPasswordSucceeds("aBC", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordSucceeds("aBC1", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent)); caseDescription = "minimum LowerCase=3"; assertPasswordFails("ABCD", caseDescription); - assertPasswordFails("aBC", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordFails("aBC1", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordQuality_complexLetters() { @@ -332,25 +352,28 @@ String caseDescription = "minimum Letters=0"; assertPasswordSucceeds("1234", caseDescription); - assertPasswordSucceeds("a23", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordSucceeds("a123", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumLetters(mComponent)); caseDescription = "minimum Letters=1"; assertPasswordFails("1234", caseDescription); - assertPasswordSucceeds("a23", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordSucceeds("a123", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumLetters(mComponent)); caseDescription = "minimum Letters=3"; assertPasswordFails("1234", caseDescription); - assertPasswordFails("a23", caseDescription); - assertPasswordSucceeds("abc", caseDescription); + assertPasswordFails("a123", caseDescription); + assertPasswordSucceeds("abc1", caseDescription); assertPasswordSucceeds("abcd", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordQuality_complexNumeric() { @@ -365,25 +388,28 @@ String caseDescription = "minimum Numeric=0"; assertPasswordSucceeds("abcd", caseDescription); - assertPasswordSucceeds("1bc", caseDescription); - assertPasswordSucceeds("123", caseDescription); + assertPasswordSucceeds("1abc", caseDescription); + assertPasswordSucceeds("123a", caseDescription); assertPasswordSucceeds("1234", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent)); caseDescription = "minimum Numeric=1"; assertPasswordFails("abcd", caseDescription); - assertPasswordSucceeds("1bc", caseDescription); - assertPasswordSucceeds("123", caseDescription); + assertPasswordSucceeds("1abc", caseDescription); + assertPasswordSucceeds("123a", caseDescription); assertPasswordSucceeds("1234", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent)); caseDescription = "minimum Numeric=3"; assertPasswordFails("abcd", caseDescription); - assertPasswordFails("1bc", caseDescription); - assertPasswordSucceeds("123", caseDescription); + assertPasswordFails("1abc", caseDescription); + assertPasswordSucceeds("123a", caseDescription); assertPasswordSucceeds("1234", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordQuality_complexSymbols() { @@ -398,25 +424,28 @@ String caseDescription = "minimum Symbols=0"; assertPasswordSucceeds("abcd", caseDescription); - assertPasswordSucceeds("_bc", caseDescription); - assertPasswordSucceeds("@#!", caseDescription); + assertPasswordSucceeds("_bc1", caseDescription); + assertPasswordSucceeds("@#!1", caseDescription); assertPasswordSucceeds("_@#!", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent)); caseDescription = "minimum Symbols=1"; assertPasswordFails("abcd", caseDescription); - assertPasswordSucceeds("_bc", caseDescription); - assertPasswordSucceeds("@#!", caseDescription); + assertPasswordSucceeds("_bc1", caseDescription); + assertPasswordSucceeds("@#!1", caseDescription); assertPasswordSucceeds("_@#!", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent)); caseDescription = "minimum Symbols=3"; assertPasswordFails("abcd", caseDescription); - assertPasswordFails("_bc", caseDescription); - assertPasswordSucceeds("@#!", caseDescription); + assertPasswordFails("_bc1", caseDescription); + assertPasswordSucceeds("@#!1", caseDescription); assertPasswordSucceeds("_@#!", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordQuality_complexNonLetter() { @@ -435,6 +464,7 @@ assertPasswordSucceeds("3bcd", caseDescription); assertPasswordSucceeds("_@3c", caseDescription); assertPasswordSucceeds("_25!", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 1); assertEquals(1, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent)); @@ -444,6 +474,7 @@ assertPasswordSucceeds("3bcd", caseDescription); assertPasswordSucceeds("_@3c", caseDescription); assertPasswordSucceeds("_25!", caseDescription); + assertPasswordFails("123", caseDescription); // too short mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 3); assertEquals(3, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent)); @@ -451,8 +482,9 @@ assertPasswordFails("Abcd", caseDescription); assertPasswordFails("_bcd", caseDescription); assertPasswordFails("3bcd", caseDescription); - assertPasswordSucceeds("c_@3c", caseDescription); + assertPasswordSucceeds("_@3c", caseDescription); assertPasswordSucceeds("_25!", caseDescription); + assertPasswordFails("123", caseDescription); // too short } public void testPasswordHistoryLength() { @@ -494,6 +526,23 @@ } } + public void testKeyguardDisabledFeatures() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testKeyguardDisabledFeatures"); + return; + } + int originalValue = mDevicePolicyManager.getKeyguardDisabledFeatures(mComponent); + try { + for (int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; + which < 2 * DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT; ++which) { + mDevicePolicyManager.setKeyguardDisabledFeatures(mComponent, which); + assertEquals(which, mDevicePolicyManager.getKeyguardDisabledFeatures(mComponent)); + } + } finally { + mDevicePolicyManager.setKeyguardDisabledFeatures(mComponent, originalValue); + } + } + public void testCreateUser_failIfNotDeviceOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testCreateUser_failIfNotDeviceOwner"); @@ -679,6 +728,19 @@ } } + public void testInstallCaCert_failIfNotCertInstaller() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testInstallCaCert_failIfNotCertInstaller"); + return; + } + try { + // Delegated cert installer is identified by using null as the first argument. + mDevicePolicyManager.installCaCert(null, TEST_CA_STRING1.getBytes()); + fail("did not throw expected SecurityException"); + } catch (SecurityException expected) { + } + } + public void testUninstallCaCert_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testUninstallCaCert_failIfNotProfileOwner"); @@ -693,6 +755,19 @@ } } + public void testUninstallCaCert_failIfNotCertInstaller() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testUninstallCaCert_failIfNotCertInstaller"); + return; + } + try { + // Delegated cert installer is identified by using null as the first argument. + mDevicePolicyManager.uninstallCaCert(null, TEST_CA_STRING1.getBytes()); + fail("did not throw expected SecurityException"); + } catch (SecurityException expected) { + } + } + public void testGetInstalledCaCerts_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testGetInstalledCaCerts_failIfNotProfileOwner"); @@ -706,6 +781,19 @@ } } + public void testGetInstalledCaCerts_failIfNotCertInstaller() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testGetInstalledCaCerts_failIfNotCertInstaller"); + return; + } + try { + // Delegated cert installer is identified by using null as the first argument. + mDevicePolicyManager.getInstalledCaCerts(null); + fail("did not throw expected SecurityException"); + } catch (SecurityException expected) { + } + } + public void testHasCaCertInstalled_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testHasCaCertInstalled_failIfNotProfileOwner"); @@ -720,6 +808,19 @@ } } + public void testHasCaCertInstalled_failIfNotCertInstaller() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testHasCaCertInstalled_failIfNotCertInstaller"); + return; + } + try { + // Delegated cert installer is identified by using null as the first argument. + mDevicePolicyManager.hasCaCertInstalled(null, TEST_CA_STRING1.getBytes()); + fail("did not throw expected SecurityException"); + } catch (SecurityException expected) { + } + } + public void testUninstallAllUserCaCerts_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testUninstallAllUserCaCerts_failIfNotProfileOwner"); @@ -733,6 +834,19 @@ } } + public void testUninstallAllUserCaCerts_failIfNotCertInstaller() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testUninstallAllUserCaCerts_failIfNotCertInstaller"); + return; + } + try { + // Delegated cert installer is identified by using null as the first argument. + mDevicePolicyManager.uninstallAllUserCaCerts(null); + fail("did not throw expected SecurityException"); + } catch (SecurityException expected) { + } + } + public void testSetScreenCaptureDisabled_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testSetScreenCaptureDisabled_failIfNotProfileOwner"); @@ -871,6 +985,19 @@ } } + public void testSetBluetoothContactSharingDisabled_failIfNotProfileOwner() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testSetBluetoothContactSharingDisabled_failIfNotProfileOwner"); + return; + } + try { + mDevicePolicyManager.setBluetoothContactSharingDisabled(mComponent, true); + fail("did not throw expected SecurityException"); + } catch (SecurityException e) { + assertProfileOwnerMessage(e.getMessage()); + } + } + public void testSetPermittedInputMethods_failIfNotProfileOwner() { if (!mDeviceAdmin) { Log.w(TAG, "Skipping testSetPermittedInputMethods_failIfNotProfileOwner"); @@ -910,6 +1037,14 @@ fail("No system launcher with version L+ present present on device."); } + /** + * Test that managed provisioning is pre-installed if and only if the device declares the + * device admin feature. + */ + public void testManagedProvisioningPreInstalled() throws Exception { + assertEquals(mDeviceAdmin, isPackageInstalledOnSystemImage(MANAGED_PROVISIONING_PKG)); + } + private void assertDeviceOwnerMessage(String message) { assertTrue("message is: "+ message, message.contains("does not own the device") || message.contains("can only be called by the device owner")); @@ -938,9 +1073,13 @@ } private void assertPasswordFails(String password, String restriction) { - boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0); - assertFalse("Password '" + password + "' should have failed on " + restriction, - passwordResetResult); + try { + boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0); + assertFalse("Password '" + password + "' should have failed on " + restriction, + passwordResetResult); + } catch (IllegalArgumentException e) { + // yesss, we have failed! + } } private void assertPasswordSucceeds(String password, String restriction) { @@ -948,4 +1087,53 @@ assertTrue("Password '" + password + "' failed on " + restriction, passwordResetResult); assertTrue(mDevicePolicyManager.isActivePasswordSufficient()); } + + public void testSetDelegatedCertInstaller_failIfNotProfileOwner() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testSetDelegatedCertInstaller_failIfNotProfileOwner"); + return; + } + try { + mDevicePolicyManager.setCertInstallerPackage(mComponent, "com.test.package"); + fail("did not throw expected SecurityException"); + } catch (SecurityException e) { + assertProfileOwnerMessage(e.getMessage()); + } + } + + public void testGetDelegatedCertInstaller_failIfNotProfileOwner() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testGetDelegatedCertInstaller_failIfNotProfileOwner"); + return; + } + try { + mDevicePolicyManager.getCertInstallerPackage(mComponent); + fail("did not throw expected SecurityException"); + } catch (SecurityException e) { + assertProfileOwnerMessage(e.getMessage()); + } + } + + public void testSetSystemUpdatePolicy_failIfNotDeviceOwner() { + if (!mDeviceAdmin) { + Log.w(TAG, "Skipping testSetSystemUpdatePolicy_failIfNotDeviceOwner"); + return; + } + try { + mDevicePolicyManager.setSystemUpdatePolicy(mComponent, null); + fail("did not throw expected SecurityException"); + } catch (SecurityException e) { + assertDeviceOwnerMessage(e.getMessage()); + } + } + + private boolean isPackageInstalledOnSystemImage(String packagename) { + try { + ApplicationInfo info = mPackageManager.getApplicationInfo(packagename, + 0 /* default flags */); + return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; + } catch (NameNotFoundException e) { + return false; + } + } }
diff --git a/tests/tests/alarmclock/Android.mk b/tests/tests/alarmclock/Android.mk new file mode 100644 index 0000000..6c30bc7 --- /dev/null +++ b/tests/tests/alarmclock/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_STATIC_JAVA_LIBRARIES := CtsAlarmClockCommon ctstestrunner ctsdeviceutil + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsAlarmClockTestCases + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE) +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/alarmclock/AndroidManifest.xml b/tests/tests/alarmclock/AndroidManifest.xml new file mode 100644 index 0000000..c0193dd --- /dev/null +++ b/tests/tests/alarmclock/AndroidManifest.xml
@@ -0,0 +1,47 @@ +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.alarmclock.cts"> + + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> + <uses-permission android:name="com.android.alarm.permission.SET_ALARM" /> + + <application> + <uses-library android:name="android.test.runner" /> + + <activity android:name="TestStartActivity" + android:label="The Target Activity for AlarmClock CTS Test"> + <intent-filter> + <action android:name="android.intent.action.TEST_START_ACTIVITY_DISMISS_ALARM" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_SET_ALARM" /> + <action android:name= + "android.intent.action.TEST_START_ACTIVITY_SET_ALARM_FOR_DISMISSAL" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_SNOOZE_ALARM" /> + <category android:name="android.intent.category.LAUNCHER" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.alarmclock.cts" + android:label="CTS tests of android.alarmclock"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> +</manifest> +
diff --git a/tests/tests/alarmclock/AndroidTest.xml b/tests/tests/alarmclock/AndroidTest.xml new file mode 100644 index 0000000..aafdb61 --- /dev/null +++ b/tests/tests/alarmclock/AndroidTest.xml
@@ -0,0 +1,21 @@ +<!-- Copyright (C) 2015 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. +--> +<configuration description="Test module config for AlarmClock"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsAlarmClockService.apk" /> + <option name="run-command:run-command" + value="settings put secure voice_interaction_service android.alarmclock.service/.MainInteractionService" /> + <option name="cts-apk-installer:test-file-name" value="CtsAlarmClockTestCases.apk" /> +</configuration>
diff --git a/tests/tests/alarmclock/common/Android.mk b/tests/tests/alarmclock/common/Android.mk new file mode 100644 index 0000000..d460ade --- /dev/null +++ b/tests/tests/alarmclock/common/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_MODULE := CtsAlarmClockCommon + +LOCAL_SDK_VERSION := current + +include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/tests/alarmclock/common/src/android/alarmclock/common/Utils.java b/tests/tests/alarmclock/common/src/android/alarmclock/common/Utils.java new file mode 100644 index 0000000..d469592 --- /dev/null +++ b/tests/tests/alarmclock/common/src/android/alarmclock/common/Utils.java
@@ -0,0 +1,51 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.common; + +import android.os.Bundle; + +public class Utils { + // private constructor - so it can't be instantiated. + private Utils() { + } + + public enum TestcaseType { + DISMISS_ALARM, + SET_ALARM, + SET_ALARM_FOR_DISMISSAL, + SNOOZE_ALARM, + } + public static final String TESTCASE_TYPE = "Testcase_type"; + public static final String BROADCAST_INTENT = + "android.intent.action.FROM_ALARMCLOCK_CTS_TEST_"; + public static final String TEST_RESULT = "test_result"; + public static final String COMPLETION_RESULT = "completion"; + public static final String ABORT_RESULT = "abort"; + + public static final String toBundleString(Bundle bundle) { + if (bundle == null) { + return "*** Bundle is null ****"; + } + StringBuilder buf = new StringBuilder(); + if (bundle != null) { + buf.append("extras: "); + for (String s : bundle.keySet()) { + buf.append("(" + s + " = " + bundle.get(s) + "), "); + } + } + return buf.toString(); + } +}
diff --git a/tests/tests/alarmclock/res/xml/interaction_service.xml b/tests/tests/alarmclock/res/xml/interaction_service.xml new file mode 100644 index 0000000..e37017c --- /dev/null +++ b/tests/tests/alarmclock/res/xml/interaction_service.xml
@@ -0,0 +1,20 @@ +<!-- Copyright (C) 2015 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. +--> + +<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android" + android:sessionService="android.alarmclock.service.MainInteractionSessionService" + android:recognitionService="android.alarmclock.service.MainRecognitionService" + android:settingsActivity="android.alarmclock.service.SettingsActivity" + android:supportsAssist="false" />
diff --git a/tests/tests/alarmclock/service/Android.mk b/tests/tests/alarmclock/service/Android.mk new file mode 100644 index 0000000..53dc564 --- /dev/null +++ b/tests/tests/alarmclock/service/Android.mk
@@ -0,0 +1,32 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_STATIC_JAVA_LIBRARIES := CtsAlarmClockCommon ctstestrunner ctsdeviceutil + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsAlarmClockService + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/tests/alarmclock/service/AndroidManifest.xml b/tests/tests/alarmclock/service/AndroidManifest.xml new file mode 100644 index 0000000..074df26 --- /dev/null +++ b/tests/tests/alarmclock/service/AndroidManifest.xml
@@ -0,0 +1,64 @@ +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.alarmclock.service"> + <uses-permission android:name="com.android.alarm.permission.SET_ALARM" /> + + <application> + <uses-library android:name="android.test.runner" /> + <service android:name=".MainInteractionService" + android:label="CTS test voice interaction service" + android:permission="android.permission.BIND_VOICE_INTERACTION" + android:process=":interactor" + android:exported="true"> + <meta-data android:name="android.voice_interaction" + android:resource="@xml/interaction_service" /> + <intent-filter> + <action android:name="android.service.voice.VoiceInteractionService" /> + </intent-filter> + </service> + <activity android:name=".VoiceInteractionMain" > + <intent-filter> + <action android:name="android.intent.action.VIMAIN_DISMISS_ALARM" /> + <action android:name="android.intent.action.VIMAIN_SET_ALARM" /> + <action android:name="android.intent.action.VIMAIN_SET_ALARM_FOR_DISMISSAL" /> + <action android:name="android.intent.action.VIMAIN_SNOOZE_ALARM" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + <activity android:name=".SettingsActivity" + android:label="Voice Interaction Settings"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + <service android:name=".MainInteractionSessionService" + android:permission="android.permission.BIND_VOICE_INTERACTION" + android:process=":session"> + </service> + <service android:name=".MainRecognitionService" + android:label="CTS Voice Recognition Service"> + <intent-filter> + <action android:name="android.speech.RecognitionService" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <meta-data android:name="android.speech" android:resource="@xml/recognition_service" /> + </service> + </application> +</manifest> +
diff --git a/tests/tests/alarmclock/service/res/xml/interaction_service.xml b/tests/tests/alarmclock/service/res/xml/interaction_service.xml new file mode 100644 index 0000000..e37017c --- /dev/null +++ b/tests/tests/alarmclock/service/res/xml/interaction_service.xml
@@ -0,0 +1,20 @@ +<!-- Copyright (C) 2015 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. +--> + +<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android" + android:sessionService="android.alarmclock.service.MainInteractionSessionService" + android:recognitionService="android.alarmclock.service.MainRecognitionService" + android:settingsActivity="android.alarmclock.service.SettingsActivity" + android:supportsAssist="false" />
diff --git a/tests/tests/alarmclock/service/res/xml/recognition_service.xml b/tests/tests/alarmclock/service/res/xml/recognition_service.xml new file mode 100644 index 0000000..132c987 --- /dev/null +++ b/tests/tests/alarmclock/service/res/xml/recognition_service.xml
@@ -0,0 +1,17 @@ +<!-- Copyright (C) 2015 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. +--> + +<recognition-service xmlns:android="http://schemas.android.com/apk/res/android" + android:settingsActivity="android.alarmclock.service.SettingsActivity" />
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionService.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionService.java new file mode 100644 index 0000000..f96140e --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionService.java
@@ -0,0 +1,64 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.alarmclock.common.Utils; +import android.content.ComponentName; +import android.content.Intent; +import android.os.Bundle; +import android.service.voice.VoiceInteractionService; +import android.util.Log; + +public class MainInteractionService extends VoiceInteractionService { + static final String TAG = "MainInteractionService"; + private Intent mIntent; + private boolean mReady = false; + + @Override + public void onReady() { + super.onReady(); + mReady = true; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Log.i(TAG, "onStartCommand received"); + mIntent = intent; + Log.i(TAG, "received_testcasetype = " + mIntent.getStringExtra(Utils.TESTCASE_TYPE)); + maybeStart(); + return START_NOT_STICKY; + } + + private void maybeStart() { + if (mIntent == null || !mReady) { + Log.wtf(TAG, "Can't start session because either intent is null or onReady() " + + "is not called yet. mIntent = " + mIntent + ", mReady = " + mReady); + } else { + Log.i(TAG, + "Yay! about to start MainInteractionSession as the voice_interaction_service"); + if (isActiveService(this, new ComponentName(this, getClass()))) { + Bundle args = new Bundle(); + args.putString(Utils.TESTCASE_TYPE, mIntent.getStringExtra(Utils.TESTCASE_TYPE)); + Log.i(TAG, "xferring_testcasetype = " + args.getString(Utils.TESTCASE_TYPE)); + showSession(args, 0); + } else { + Log.wtf(TAG, "**** Not starting MainInteractionService because" + + " it is not set as the current voice_interaction_service"); + } + } + } +}
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSession.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSession.java new file mode 100644 index 0000000..ede762a --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSession.java
@@ -0,0 +1,174 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.alarmclock.common.Utils; +import android.alarmclock.common.Utils.TestcaseType; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; +import android.os.Bundle; +import android.provider.AlarmClock; +import android.service.voice.VoiceInteractionSession; +import android.util.Log; + +import java.util.ArrayList; +import java.util.List; + +public class MainInteractionSession extends VoiceInteractionSession { + static final String TAG = "MainInteractionSession"; + + private List<MyTask> mUsedTasks = new ArrayList<MyTask>(); + private Context mContext; + private TestcaseType mTestType; + private String mTestResult = ""; + + MainInteractionSession(Context context) { + super(context); + mContext = context; + } + + @Override + public void onCreate() { + super.onCreate(); + } + + @Override + public void onDestroy() { + Log.i(TAG, "Canceling the Asynctasks in onDestroy()"); + for (MyTask t : mUsedTasks) { + t.cancel(true); + } + super.onDestroy(); + } + + @Override + public void onShow(Bundle args, int showFlags) { + super.onShow(args, showFlags); + String testCaseType = args.getString(Utils.TESTCASE_TYPE); + Log.i(TAG, "received_testcasetype = " + testCaseType); + try { + mTestType = TestcaseType.valueOf(testCaseType); + } catch (IllegalArgumentException e) { + Log.wtf(TAG, e); + return; + } catch (NullPointerException e) { + Log.wtf(TAG, e); + return; + } + Intent intent; + switch(mTestType) { + case DISMISS_ALARM: + intent = new Intent(AlarmClock.ACTION_DISMISS_ALARM); + intent.putExtra(AlarmClock.EXTRA_ALARM_SEARCH_MODE, + AlarmClock.ALARM_SEARCH_MODE_NEXT); + break; + + case SET_ALARM_FOR_DISMISSAL: + case SET_ALARM: + intent = new Intent(AlarmClock.ACTION_SET_ALARM); + intent.putExtra(AlarmClock.EXTRA_HOUR, 14); + break; + + case SNOOZE_ALARM: + intent = new Intent(AlarmClock.ACTION_SNOOZE_ALARM); + break; + + default: + Log.e(TAG, "Unexpected value"); + return; + } + Log.i(TAG, "starting_voiceactivity: " + intent.toString()); + startVoiceActivity(intent); + } + + @Override + public void onTaskFinished(Intent intent, int taskId) { + // extras contain the info on what the activity started above did. + // we probably could verify this also. + Bundle extras = intent.getExtras(); + Log.i(TAG, "in onTaskFinished: testcasetype = " + mTestType + ", intent: " + + intent.toString() + Utils.toBundleString(extras)); + Intent broadcastIntent = new Intent(Utils.BROADCAST_INTENT + mTestType.toString()); + broadcastIntent.putExtra(Utils.TEST_RESULT, mTestResult); + broadcastIntent.putExtra(Utils.TESTCASE_TYPE, mTestType.toString()); + Log.i(TAG, "sending_broadcast for testcase+type = " + + broadcastIntent.getStringExtra(Utils.TESTCASE_TYPE) + + ", test_result = " + broadcastIntent.getStringExtra(Utils.TEST_RESULT)); + mContext.sendBroadcast(broadcastIntent); + } + + synchronized MyTask newTask() { + MyTask t = new MyTask(); + mUsedTasks.add(t); + return t; + } + + @Override + public void onRequestCompleteVoice(CompleteVoiceRequest request) { + mTestResult = Utils.COMPLETION_RESULT; + CharSequence prompt = request.getVoicePrompt().getVoicePromptAt(0); + Log.i(TAG, "in Session testcasetype = " + mTestType + + ", onRequestCompleteVoice recvd. message = " + prompt); + AsyncTaskArg asyncTaskArg = new AsyncTaskArg().setRequest(request).setCompleteReq(true); + newTask().execute(asyncTaskArg); + } + + @Override + public void onRequestAbortVoice(AbortVoiceRequest request) { + mTestResult = Utils.ABORT_RESULT; + AsyncTaskArg asyncTaskArg = new AsyncTaskArg().setRequest(request).setCompleteReq(false); + Log.i(TAG, "in Session sending sendAbortResult for testcasetype = " + mTestType); + newTask().execute(asyncTaskArg); + } + + private class AsyncTaskArg { + CompleteVoiceRequest mCompReq; + AbortVoiceRequest mAbortReq; + boolean isCompleteRequest = true; + + AsyncTaskArg setRequest(CompleteVoiceRequest r) { + mCompReq = r; + return this; + } + + AsyncTaskArg setRequest(AbortVoiceRequest r) { + mAbortReq = r; + return this; + } + + AsyncTaskArg setCompleteReq(boolean flag) { + isCompleteRequest = flag; + return this; + } + } + + private class MyTask extends AsyncTask<AsyncTaskArg, Void, Void> { + @Override + protected Void doInBackground(AsyncTaskArg... params) { + AsyncTaskArg arg = params[0]; + Log.i(TAG, "in MyTask - doInBackground: testType = " + + MainInteractionSession.this.mTestType); + if (arg.isCompleteRequest) { + arg.mCompReq.sendCompleteResult(new Bundle()); + } else { + arg.mAbortReq.sendAbortResult(new Bundle()); + } + return null; + } + } +}
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSessionService.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSessionService.java new file mode 100644 index 0000000..a83c115 --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainInteractionSessionService.java
@@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.os.Bundle; +import android.service.voice.VoiceInteractionSession; +import android.service.voice.VoiceInteractionSessionService; + +public class MainInteractionSessionService extends VoiceInteractionSessionService { + @Override + public VoiceInteractionSession onNewSession(Bundle args) { + return new MainInteractionSession(this); + } +}
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/MainRecognitionService.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainRecognitionService.java new file mode 100644 index 0000000..15a32d4 --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/MainRecognitionService.java
@@ -0,0 +1,55 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.content.Intent; +import android.speech.RecognitionService; +import android.util.Log; + +/** + * Stub recognition service needed to be a complete voice interactor. + */ +public class MainRecognitionService extends RecognitionService { + private static final String TAG = "MainRecognitionService"; + + @Override + public void onCreate() { + super.onCreate(); + Log.i(TAG, "onCreate"); + } + + @Override + protected void onStartListening(Intent recognizerIntent, Callback listener) { + Log.i(TAG, "onStartListening"); + } + + @Override + protected void onCancel(Callback listener) { + Log.i(TAG, "onCancel"); + } + + @Override + protected void onStopListening(Callback listener) { + Log.i(TAG, "onStopListening"); + } + + @Override + public void onDestroy() { + super.onDestroy(); + Log.i(TAG, "onDestroy"); + } +}
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/SettingsActivity.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/SettingsActivity.java new file mode 100644 index 0000000..0c4d289 --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/SettingsActivity.java
@@ -0,0 +1,30 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.app.Activity; +import android.os.Bundle; + +/** + * Stub activity to test out settings selection for voice interactor. + */ +public class SettingsActivity extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } +}
diff --git a/tests/tests/alarmclock/service/src/android/alarmclock/service/VoiceInteractionMain.java b/tests/tests/alarmclock/service/src/android/alarmclock/service/VoiceInteractionMain.java new file mode 100644 index 0000000..c1f23a0 --- /dev/null +++ b/tests/tests/alarmclock/service/src/android/alarmclock/service/VoiceInteractionMain.java
@@ -0,0 +1,40 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.service; + +import android.alarmclock.common.Utils; +import android.app.Activity; +import android.content.Intent; +import android.content.ComponentName; +import android.os.Bundle; +import android.util.Log; + +public class VoiceInteractionMain extends Activity { + static final String TAG = "VoiceInteractionMain"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = new Intent(); + String testCaseType = getIntent().getStringExtra(Utils.TESTCASE_TYPE); + Log.i(TAG, "received_testcasetype = " + testCaseType); + intent.putExtra(Utils.TESTCASE_TYPE, testCaseType); + intent.setComponent(new ComponentName(this, MainInteractionService.class)); + ComponentName serviceName = startService(intent); + Log.i(TAG, "Started service: " + serviceName); + } +}
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/AlarmClockTestBase.java b/tests/tests/alarmclock/src/android/alarmclock/cts/AlarmClockTestBase.java new file mode 100644 index 0000000..0d434f2 --- /dev/null +++ b/tests/tests/alarmclock/src/android/alarmclock/cts/AlarmClockTestBase.java
@@ -0,0 +1,145 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.cts; + +import android.alarmclock.common.Utils; +import android.alarmclock.common.Utils.TestcaseType; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.provider.AlarmClock; +import android.os.Bundle; +import android.test.ActivityInstrumentationTestCase2; +import android.util.Log; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class AlarmClockTestBase extends ActivityInstrumentationTestCase2<TestStartActivity> { + static final String TAG = "AlarmClockTestBase"; + protected static final int TIMEOUT_MS = 20 * 1000; + + private Context mContext; + private String mTestResult; + private CountDownLatch mLatch; + private ActivityDoneReceiver mActivityDoneReceiver = null; + private TestStartActivity mActivity; + private TestcaseType mTestCaseType; + + public AlarmClockTestBase() { + super(TestStartActivity.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mContext = getInstrumentation().getTargetContext(); + } + + @Override + protected void tearDown() throws Exception { + mContext.unregisterReceiver(mActivityDoneReceiver); + super.tearDown(); + } + + private void registerBroadcastReceiver(TestcaseType testCaseType) throws Exception { + mTestCaseType = testCaseType; + mLatch = new CountDownLatch(1); + if (mActivityDoneReceiver != null) { + mContext.unregisterReceiver(mActivityDoneReceiver); + } + mActivityDoneReceiver = new ActivityDoneReceiver(); + mContext.registerReceiver(mActivityDoneReceiver, + new IntentFilter(Utils.BROADCAST_INTENT + testCaseType.toString())); + } + + private boolean isIntentSupported(TestcaseType testCaseType) { + Intent intent; + switch (testCaseType) { + case DISMISS_ALARM: + intent = new Intent(AlarmClock.ACTION_DISMISS_ALARM); + break; + + case SET_ALARM: + case SET_ALARM_FOR_DISMISSAL: + intent = new Intent(AlarmClock.ACTION_SET_ALARM); + break; + + case SNOOZE_ALARM: + intent = new Intent(AlarmClock.ACTION_SNOOZE_ALARM); + break; + + default: + // shouldn't happen + return false; + } + final PackageManager manager = mContext.getPackageManager(); + assertNotNull(manager); + if (manager.resolveActivity(intent, 0) == null) { + Log.i(TAG, "No Voice Activity found for the intent: " + intent.getAction()); + return false; + } + return true; + } + + protected String runTest(TestcaseType testCaseType) throws Exception { + Log.i(TAG, "Begin Testing: " + testCaseType); + // Make sure the corresponding intent is supported by the platform, before testing. + if (!isIntentSupported(testCaseType)) return Utils.COMPLETION_RESULT; + + if (!startTestActivity(testCaseType)) { + fail("test activity start failed for testcase = " + testCaseType); + return ""; + } + + registerBroadcastReceiver(testCaseType); + mActivity.startTest(testCaseType.toString()); + if (!mLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + fail("Failed to receive broadcast in " + TIMEOUT_MS + "msec"); + return ""; + } + return mTestResult; + } + + private boolean startTestActivity(TestcaseType testCaseType) { + Log.i(TAG, "Starting test activity for test: " + testCaseType); + Intent intent = new Intent(); + intent.setAction("android.intent.action.TEST_START_ACTIVITY_" + testCaseType.toString()); + intent.setComponent(new ComponentName(getInstrumentation().getContext(), + TestStartActivity.class)); + setActivityIntent(intent); + mActivity = getActivity(); + return mActivity != null; + } + + class ActivityDoneReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals( + Utils.BROADCAST_INTENT + AlarmClockTestBase.this.mTestCaseType.toString())) { + AlarmClockTestBase.this.mTestResult = intent.getStringExtra(Utils.TEST_RESULT); + Log.i(TAG, "received_broadcast for testcase_type = " + + Utils.BROADCAST_INTENT + AlarmClockTestBase.this.mTestCaseType + + ", test_result = " + AlarmClockTestBase.this.mTestResult); + mLatch.countDown(); + } + } + } +}
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/DismissAlarmTest.java b/tests/tests/alarmclock/src/android/alarmclock/cts/DismissAlarmTest.java new file mode 100644 index 0000000..64ecf86 --- /dev/null +++ b/tests/tests/alarmclock/src/android/alarmclock/cts/DismissAlarmTest.java
@@ -0,0 +1,31 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.cts; + +import android.alarmclock.common.Utils; +import android.alarmclock.common.Utils.TestcaseType; + +public class DismissAlarmTest extends AlarmClockTestBase { + public DismissAlarmTest() { + super(); + } + + public void testAll() throws Exception { + assertEquals(Utils.COMPLETION_RESULT, runTest(TestcaseType.SET_ALARM_FOR_DISMISSAL)); + assertEquals(Utils.COMPLETION_RESULT, runTest(TestcaseType.DISMISS_ALARM)); + } +}
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java b/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java new file mode 100644 index 0000000..a95a1dd --- /dev/null +++ b/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java
@@ -0,0 +1,30 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.cts; + +import android.alarmclock.common.Utils; +import android.alarmclock.common.Utils.TestcaseType; + +public class SetAlarmTest extends AlarmClockTestBase { + public SetAlarmTest() { + super(); + } + + public void testAll() throws Exception { + assertEquals(Utils.COMPLETION_RESULT, runTest(TestcaseType.SET_ALARM)); + } +}
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/SnoozeAlarmTest.java b/tests/tests/alarmclock/src/android/alarmclock/cts/SnoozeAlarmTest.java new file mode 100644 index 0000000..b67a7cf --- /dev/null +++ b/tests/tests/alarmclock/src/android/alarmclock/cts/SnoozeAlarmTest.java
@@ -0,0 +1,38 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.cts; + +import android.alarmclock.common.Utils; +import android.alarmclock.common.Utils.TestcaseType; + +public class SnoozeAlarmTest extends AlarmClockTestBase { + public SnoozeAlarmTest() { + super(); + } + + public void testAll() throws Exception { + String result = runTest(TestcaseType.SNOOZE_ALARM); + // Since there is no way to figure out if there is a currently-firing alarm, + // we should expect either of the 2 results: + // Utils.COMPLETION_RESULT + // Utils.ABORT_RESULT + // For CTS test purposes, all we can do is to know that snooze-alarm intent + // was picked up and processed by the voice_interaction_service and the associated app. + // The above call to runTest() would have failed the test otherwise. + assertTrue(result.equals(Utils.ABORT_RESULT) || result.equals(Utils.COMPLETION_RESULT)); + } +}
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/TestStartActivity.java b/tests/tests/alarmclock/src/android/alarmclock/cts/TestStartActivity.java new file mode 100644 index 0000000..1a3c4eb --- /dev/null +++ b/tests/tests/alarmclock/src/android/alarmclock/cts/TestStartActivity.java
@@ -0,0 +1,80 @@ +/* + * Copyright (C) 2015 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 android.alarmclock.cts; + +import android.alarmclock.common.Utils; +import android.app.Activity; +import android.content.Intent; +import android.content.ComponentName; +import android.os.Bundle; +import android.util.Log; + +public class TestStartActivity extends Activity { + static final String TAG = "TestStartActivity"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.i(TAG, " in onCreate"); + } + + @Override + protected void onResume() { + super.onResume(); + Log.i(TAG, " in onResume"); + } + + void startTest(String testCaseType) { + Intent intent = new Intent(); + Log.i(TAG, "received_testcasetype = " + testCaseType); + intent.putExtra(Utils.TESTCASE_TYPE, testCaseType); + intent.setAction("android.intent.action.VIMAIN_" + testCaseType); + intent.setComponent(new ComponentName("android.alarmclock.service", + "android.alarmclock.service.VoiceInteractionMain")); + startActivity(intent); + } + + @Override + protected void onPause() { + Log.i(TAG, " in onPause"); + super.onPause(); + } + + @Override + protected void onStart() { + super.onStart(); + Log.i(TAG, " in onStart"); + } + + @Override + protected void onRestart() { + super.onRestart(); + Log.i(TAG, " in onRestart"); + } + + @Override + protected void onStop() { + Log.i(TAG, " in onStop"); + super.onStop(); + } + + @Override + protected void onDestroy() { + Log.i(TAG, " in onDestroy"); + super.onDestroy(); + } +}
diff --git a/tests/tests/app.usage/AndroidManifest.xml b/tests/tests/app.usage/AndroidManifest.xml index 11065d4..7869223 100644 --- a/tests/tests/app.usage/AndroidManifest.xml +++ b/tests/tests/app.usage/AndroidManifest.xml
@@ -21,6 +21,10 @@ <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" /> <uses-permission android:name="android.permission.SET_TIME" /> + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application> <uses-library android:name="android.test.runner" /> @@ -29,6 +33,7 @@ <activity android:name=".Activities$ActivityTwo" /> <activity android:name=".Activities$ActivityThree" /> <activity android:name=".Activities$ActivityFour" /> + <activity android:name=".ActivityTransitionActivity" /> </application> <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/app.usage/res/layout/end.xml b/tests/tests/app.usage/res/layout/end.xml new file mode 100644 index 0000000..2847249 --- /dev/null +++ b/tests/tests/app.usage/res/layout/end.xml
@@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <View android:layout_width="10dp" + android:layout_height="10dp" + android:background="#F00" + android:id="@+id/redSquare"/> + <TextView android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:transitionName="target" + android:text="@string/hello"/> + <View android:layout_width="10dp" + android:layout_height="10dp" + android:background="#0F0" + android:id="@+id/greenSquare"/> +</LinearLayout>
diff --git a/tests/tests/app.usage/res/layout/start.xml b/tests/tests/app.usage/res/layout/start.xml new file mode 100644 index 0000000..793e9b5 --- /dev/null +++ b/tests/tests/app.usage/res/layout/start.xml
@@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <View android:layout_width="10dp" + android:layout_height="10dp" + android:background="#0F0" + android:id="@+id/greenSquare"/> + <View android:layout_width="10dp" + android:layout_height="10dp" + android:background="#F00" + android:id="@+id/redSquare"/> + <TextView android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:transitionName="source" + android:id="@+id/hello" + android:text="@string/hello"/> +</LinearLayout>
diff --git a/tests/tests/app.usage/res/values/strings.xml b/tests/tests/app.usage/res/values/strings.xml new file mode 100644 index 0000000..8ca6f73 --- /dev/null +++ b/tests/tests/app.usage/res/values/strings.xml
@@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<resources> + <string name="hello">Hello</string> +</resources>
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java new file mode 100644 index 0000000..10ac4ea --- /dev/null +++ b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionActivity.java
@@ -0,0 +1,172 @@ +/* + * 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 android.app.usage.cts; + +import android.app.Activity; +import android.app.SharedElementCallback; +import android.app.usage.cts.R; +import android.content.Intent; +import android.os.Bundle; +import android.os.ResultReceiver; +import android.os.SystemClock; +import android.transition.ChangeBounds; +import android.transition.Explode; +import android.transition.Fade; +import android.transition.Transition; +import android.transition.Transition.TransitionListener; +import android.view.View; + +import java.util.List; + +/** + * A simple activity containing the start state for an Activity Transition + */ +public class ActivityTransitionActivity extends Activity { + private static final long DURATION = 50; + private static final long SHARED_ELEMENT_READY_DELAY = 50; + public static final String LAYOUT_ID = "layoutId"; + public static final String TEST = "test"; + public static final String RESULT_RECEIVER = "resultReceiver"; + + public static final int NO_TEST = 0; + public static final int TEST_ARRIVE = 1; + + public static final String ARRIVE_COUNT = "numArrived"; + public static final String ARRIVE_ENTER_START_VISIBILITY = "arriveEnterStartVisibility"; + public static final String ARRIVE_ENTER_DELAY_VISIBILITY = "arriveEnterDelayVisibility"; + public static final String ARRIVE_ENTER_TIME_READY = "arriveEnterTimeReady"; + public static final String ARRIVE_ENTER_TIME = "arriveEnterTime"; + public static final String ARRIVE_RETURN_TIME_READY = "arriveReturnTimeReady"; + public static final String ARRIVE_RETURN_TIME = "arriveReturnTime"; + + private int mLayoutId; + private int mTest; + private ResultReceiver mResultReceiver; + private int mNumSharedElementsArrivedCalled = 0; + private boolean mEntering = true; + + public int resultCode = 0; + public Bundle result = new Bundle(); + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + getWindow().setSharedElementEnterTransition(new ChangeBounds().setDuration(DURATION)); + getWindow().setSharedElementReturnTransition(new ChangeBounds().setDuration(DURATION)); + getWindow().setEnterTransition(new Explode().setDuration(DURATION)); + getWindow().setReturnTransition(new Explode().setDuration(DURATION)); + getWindow().setExitTransition(new Fade().setDuration(DURATION)); + mLayoutId = 0; + if (icicle != null) { + mLayoutId = icicle.getInt(LAYOUT_ID); + mTest = icicle.getInt(TEST); + mResultReceiver = icicle.getParcelable(RESULT_RECEIVER); + } + + if (mLayoutId == 0) { + Intent intent = getIntent(); + mLayoutId = intent.getIntExtra(LAYOUT_ID, R.layout.start); + mTest = intent.getIntExtra(TEST, 0); + mResultReceiver = intent.getParcelableExtra(RESULT_RECEIVER); + } + + setContentView(mLayoutId); + + startTest(); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + outState.putInt(LAYOUT_ID, mLayoutId); + outState.putInt(TEST, mTest); + outState.putParcelable(RESULT_RECEIVER, mResultReceiver); + } + + private void startTest() { + if (mTest == TEST_ARRIVE) { + setEnterSharedElementCallback(new SharedElementCallback() { + @Override + public void onSharedElementsArrived(List<String> sharedElementNames, + final List<View> sharedElements, + final OnSharedElementsReadyListener listener) { + mNumSharedElementsArrivedCalled++; + result.putInt(ARRIVE_COUNT, mNumSharedElementsArrivedCalled); + if (mEntering) { + result.putInt(ARRIVE_ENTER_START_VISIBILITY, sharedElements.get(0).getVisibility()); + result.putLong(ARRIVE_ENTER_TIME, SystemClock.uptimeMillis()); + } else { + result.putLong(ARRIVE_RETURN_TIME, SystemClock.uptimeMillis()); + } + + getWindow().getDecorView().postDelayed(new Runnable() { + @Override + public void run() { + if (mEntering) { + result.putInt(ARRIVE_ENTER_DELAY_VISIBILITY, + sharedElements.get(0).getVisibility()); + result.putLong(ARRIVE_ENTER_TIME_READY, SystemClock.uptimeMillis()); + } else { + result.putLong(ARRIVE_RETURN_TIME_READY, + SystemClock.uptimeMillis()); + mResultReceiver.send(RESULT_OK, result); + } + listener.onSharedElementsReady(); + } + }, SHARED_ELEMENT_READY_DELAY); + } + }); + getWindow().getEnterTransition().addListener(new TransitionListener() { + @Override + public void onTransitionStart(Transition transition) { + } + + @Override + public void onTransitionEnd(Transition transition) { + mEntering = false; + setResult(RESULT_OK); + getWindow().getDecorView().post(new Runnable() { + @Override + public void run() { + finishAfterTransition(); + } + }); + } + + @Override + public void onTransitionCancel(Transition transition) { + } + + @Override + public void onTransitionPause(Transition transition) { + } + + @Override + public void onTransitionResume(Transition transition) { + } + }); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + synchronized (this) { + super.onActivityResult(requestCode, resultCode, data); + this.resultCode = resultCode; + this.notifyAll(); + } + } +}
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java new file mode 100644 index 0000000..ef126fe --- /dev/null +++ b/tests/tests/app.usage/src/android/app/usage/cts/ActivityTransitionTest.java
@@ -0,0 +1,147 @@ +/* + * Copyright (C) 2015 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 android.app.usage.cts; + +import android.app.ActivityOptions; +import android.app.SharedElementCallback; +import android.app.usage.cts.R; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.ResultReceiver; +import android.os.SystemClock; +import android.test.ActivityInstrumentationTestCase2; +import android.view.View; + +import java.util.List; + +public class ActivityTransitionTest extends + ActivityInstrumentationTestCase2<ActivityTransitionActivity> { + protected ActivityTransitionActivity mActivity; + + private int mNumArrivedCalls; + private PassInfo mReceiver; + private long mExitTime; + private long mExitTimeReady; + private long mReenterTime; + private long mReenterTimeReady; + + public ActivityTransitionTest() { + super(ActivityTransitionActivity.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + mNumArrivedCalls = 0; + } + + public void testOnSharedElementsArrived() throws Throwable { + getInstrumentation().waitForIdleSync(); + runTestOnUiThread(new Runnable() { + @Override + public void run() { + mReceiver = new PassInfo(new Handler()); + mActivity.setExitSharedElementCallback(new SharedElementCallback() { + @Override + public void onSharedElementsArrived(List<String> sharedElementNames, + List<View> sharedElements, + final OnSharedElementsReadyListener listener) { + mNumArrivedCalls++; + final boolean isExiting = mExitTimeReady == 0; + if (isExiting) { + mExitTime = SystemClock.uptimeMillis(); + } else { + mReenterTime = SystemClock.uptimeMillis(); + } + mActivity.getWindow().getDecorView().postDelayed(new Runnable() { + @Override + public void run() { + if (isExiting) { + mExitTimeReady = SystemClock.uptimeMillis(); + } else { + mReenterTimeReady = SystemClock.uptimeMillis(); + } + listener.onSharedElementsReady(); + } + }, 60); + } + }); + + Bundle options = ActivityOptions.makeSceneTransitionAnimation(mActivity, + mActivity.findViewById(R.id.hello), "target").toBundle(); + Intent intent = new Intent(mActivity, ActivityTransitionActivity.class); + intent.putExtra(ActivityTransitionActivity.TEST, + ActivityTransitionActivity.TEST_ARRIVE); + intent.putExtra(ActivityTransitionActivity.LAYOUT_ID, R.layout.end); + intent.putExtra(ActivityTransitionActivity.RESULT_RECEIVER, mReceiver); + mActivity.startActivityForResult(intent, 0, options); + } + }); + + long endTime = SystemClock.uptimeMillis() + 1500; + synchronized (mActivity) { + while (mActivity.resultCode == 0) { + long waitTime = endTime - SystemClock.uptimeMillis(); + if (waitTime <= 0) { + fail("Activity didn't finish!"); + } + mActivity.wait(waitTime); + } + } + assertNotNull(mReceiver.resultData); + assertEquals(2, mReceiver.resultData.getInt( + ActivityTransitionActivity.ARRIVE_COUNT, -1)); + assertEquals(2, mNumArrivedCalls); + assertNotSame(View.VISIBLE, mReceiver.resultData.getInt( + ActivityTransitionActivity.ARRIVE_ENTER_START_VISIBILITY)); + assertNotSame(View.VISIBLE, mReceiver.resultData.getInt( + ActivityTransitionActivity.ARRIVE_ENTER_DELAY_VISIBILITY)); + long enterTimeReady = mReceiver.resultData.getLong( + ActivityTransitionActivity.ARRIVE_ENTER_TIME_READY); + long returnTimeReady = mReceiver.resultData.getLong( + ActivityTransitionActivity.ARRIVE_RETURN_TIME_READY); + long enterTime = mReceiver.resultData.getLong( + ActivityTransitionActivity.ARRIVE_ENTER_TIME); + long returnTime = mReceiver.resultData.getLong( + ActivityTransitionActivity.ARRIVE_RETURN_TIME); + + assertTrue(mExitTime < mExitTimeReady); + assertTrue(mExitTimeReady <= enterTime); + assertTrue(enterTime < enterTimeReady); + assertTrue(enterTimeReady <= returnTime); + assertTrue(returnTime < returnTimeReady); + assertTrue(returnTimeReady <= mReenterTime); + assertTrue(mReenterTime < mReenterTimeReady); + } + + public static class PassInfo extends ResultReceiver { + public int resultCode; + public Bundle resultData; + + public PassInfo(Handler handler) { + super(handler); + } + + @Override + protected void onReceiveResult(int resultCode, Bundle resultData) { + this.resultCode = resultCode; + this.resultData = resultData; + } + } +}
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java b/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java new file mode 100644 index 0000000..a889c02 --- /dev/null +++ b/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java
@@ -0,0 +1,456 @@ +/** + * Copyright (C) 2015 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 android.app.usage.cts; + +import android.app.AppOpsManager; +import android.app.usage.NetworkStatsManager; +import android.app.usage.NetworkStats; +import android.content.Context; +import android.content.pm.PackageManager; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.NetworkInfo; +import android.net.NetworkRequest; +import android.os.ParcelFileDescriptor; +import android.os.Process; +import android.os.RemoteException; +import android.telephony.TelephonyManager; +import android.test.InstrumentationTestCase; +import android.util.Log; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Scanner; +import java.net.HttpURLConnection; + +import libcore.io.IoUtils; +import libcore.io.Streams; + +public class NetworkUsageStatsTest extends InstrumentationTestCase { + private static final String LOG_TAG = "NetworkUsageStatsTest"; + private static final String APPOPS_SET_SHELL_COMMAND = "appops set {0} {1} {2}"; + private static final String APPOPS_GET_SHELL_COMMAND = "appops get {0} {1}"; + + private static final long MINUTE = 1000 * 60; + + private static final int[] sNetworkTypesToTest = new int[] { + ConnectivityManager.TYPE_WIFI, + ConnectivityManager.TYPE_MOBILE, + }; + + private static final String[] sSystemFeaturesToTest = new String[] { + PackageManager.FEATURE_WIFI, + PackageManager.FEATURE_TELEPHONY, + }; + + private static final String[] sFeatureNotConnectedCause = new String[] { + " Please make sure you are connected to a WiFi access point.", + " Please make sure you have added a SIM card with data plan to your phone, have enabled " + + "data over cellular and in case of dual SIM devices, have selected the right SIM " + + "for data connection." + }; + + private NetworkStatsManager mNsm; + private ConnectivityManager mCm; + private PackageManager mPm; + private long mStartTime; + private long mEndTime; + + private long mBytesRead; + private String mWriteSettingsMode; + private String mUsageStatsMode; + + private void exerciseRemoteHost(Network network) throws Exception { + final int timeout = 15000; + NetworkInfo networkInfo = mCm.getNetworkInfo(network); + if (networkInfo == null) { + Log.w(LOG_TAG, "Network info is null"); + } else { + Log.w(LOG_TAG, "Network: " + networkInfo.toString()); + } + InputStreamReader in = null; + HttpURLConnection urlc = null; + String originalKeepAlive = System.getProperty("http.keepAlive"); + System.setProperty("http.keepAlive", "false"); + try { + urlc = (HttpURLConnection) network.openConnection(new URL( + "http://www.265.com/")); + urlc.setConnectTimeout(timeout); + urlc.setUseCaches(false); + urlc.connect(); + boolean ping = urlc.getResponseCode() == 200; + if (ping) { + in = new InputStreamReader( + (InputStream) urlc.getContent()); + + mBytesRead = 0; + while (in.read() != -1) ++mBytesRead; + } + } catch (Exception e) { + Log.i(LOG_TAG, "Badness during exercising remote server: " + e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // don't care + } + } + if (urlc != null) { + urlc.disconnect(); + } + if (originalKeepAlive == null) { + System.clearProperty("http.keepAlive"); + } else { + System.setProperty("http.keepAlive", originalKeepAlive); + } + } + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mNsm = (NetworkStatsManager) getInstrumentation().getContext() + .getSystemService(Context.NETWORK_STATS_SERVICE); + + mCm = (ConnectivityManager) getInstrumentation().getContext() + .getSystemService(Context.CONNECTIVITY_SERVICE); + + mPm = getInstrumentation().getContext().getPackageManager(); + + mWriteSettingsMode = getAppOpsMode(AppOpsManager.OPSTR_WRITE_SETTINGS); + setAppOpsMode(AppOpsManager.OPSTR_WRITE_SETTINGS, "allow"); + mUsageStatsMode = getAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS); + } + + @Override + protected void tearDown() throws Exception { + if (mWriteSettingsMode != null) { + setAppOpsMode(AppOpsManager.OPSTR_WRITE_SETTINGS, mWriteSettingsMode); + } + if (mUsageStatsMode != null) { + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, mUsageStatsMode); + } + super.tearDown(); + } + + private void setAppOpsMode(String appop, String mode) throws Exception { + final String command = MessageFormat.format(APPOPS_SET_SHELL_COMMAND, + getInstrumentation().getContext().getPackageName(), appop, mode); + ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation() + .executeShellCommand(command); + try { + Streams.readFully(new FileInputStream(pfd.getFileDescriptor())); + } finally { + IoUtils.closeQuietly(pfd.getFileDescriptor()); + } + } + + private String getAppOpsMode(String appop) throws Exception { + String result; + final String command = MessageFormat.format(APPOPS_GET_SHELL_COMMAND, + getInstrumentation().getContext().getPackageName(), appop); + ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation() + .executeShellCommand(command); + try { + result = convertStreamToString(new FileInputStream(pfd.getFileDescriptor())); + } finally { + IoUtils.closeQuietly(pfd.getFileDescriptor()); + } + if (result == null) { + Log.w(LOG_TAG, "App op " + appop + " could not be read."); + } + return result; + } + + private static String convertStreamToString(InputStream is) { + try (Scanner scanner = new Scanner(is).useDelimiter("\\A")) { + return scanner.hasNext() ? scanner.next() : null; + } + } + + private boolean shouldTestThisNetworkType(int networkTypeIndex, long tolerance) + throws Exception { + Network[] networks = mCm.getAllNetworks(); + for (Network network : networks) { + NetworkInfo networkInfo = mCm.getNetworkInfo(network); + if (networkInfo != null && networkInfo.isConnected() && + networkInfo.getType() == sNetworkTypesToTest[networkTypeIndex]) { + NetworkCapabilities capabilities = mCm.getNetworkCapabilities(network); + if (capabilities != null && capabilities.hasCapability( + NetworkCapabilities.NET_CAPABILITY_INTERNET)) { + mStartTime = System.currentTimeMillis() - tolerance; + exerciseRemoteHost(network); + mEndTime = System.currentTimeMillis() + tolerance; + return true; + } + } + } + assertFalse (sSystemFeaturesToTest[networkTypeIndex] + " is a reported system feature, " + + "however no corresponding connected network interface was found. " + + sFeatureNotConnectedCause[networkTypeIndex], + mPm.hasSystemFeature(sSystemFeaturesToTest[networkTypeIndex])); + return false; + } + + private String getSubscriberId(int networkType) { + if (ConnectivityManager.TYPE_MOBILE == networkType) { + TelephonyManager tm = (TelephonyManager) getInstrumentation().getContext() + .getSystemService(Context.TELEPHONY_SERVICE); + return tm.getSubscriberId(); + } + return ""; + } + + public void testDeviceSummary() throws Exception { + for (int i = 0; i < sNetworkTypesToTest.length; ++i) { + if (!shouldTestThisNetworkType(i, MINUTE/2)) { + continue; + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "allow"); + NetworkStats.Bucket bucket = null; + try { + bucket = mNsm.querySummaryForDevice( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + } catch (RemoteException | SecurityException e) { + fail("testDeviceSummary fails with exception: " + e.toString()); + } + assertNotNull(bucket); + assertTimestamps(bucket); + assertEquals(bucket.getState(), NetworkStats.Bucket.STATE_ALL); + assertEquals(bucket.getUid(), NetworkStats.Bucket.UID_ALL); + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "deny"); + try { + bucket = mNsm.querySummaryForDevice( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + fail("negative testDeviceSummary fails: no exception thrown."); + } catch (RemoteException e) { + fail("testDeviceSummary fails with exception: " + e.toString()); + } catch (SecurityException e) { + // expected outcome + } + } + } + + public void testUserSummary() throws Exception { + for (int i = 0; i < sNetworkTypesToTest.length; ++i) { + if (!shouldTestThisNetworkType(i, MINUTE/2)) { + continue; + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "allow"); + NetworkStats.Bucket bucket = null; + try { + bucket = mNsm.querySummaryForUser( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + } catch (RemoteException | SecurityException e) { + fail("testUserSummary fails with exception: " + e.toString()); + } + assertNotNull(bucket); + assertTimestamps(bucket); + assertEquals(bucket.getState(), NetworkStats.Bucket.STATE_ALL); + assertEquals(bucket.getUid(), NetworkStats.Bucket.UID_ALL); + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "deny"); + try { + bucket = mNsm.querySummaryForUser( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + fail("negative testUserSummary fails: no exception thrown."); + } catch (RemoteException e) { + fail("testUserSummary fails with exception: " + e.toString()); + } catch (SecurityException e) { + // expected outcome + } + } + } + + public void testAppSummary() throws Exception { + for (int i = 0; i < sNetworkTypesToTest.length; ++i) { + if (!shouldTestThisNetworkType(i, MINUTE/2)) { + continue; + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "allow"); + NetworkStats result = null; + try { + result = mNsm.querySummary( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + assertTrue(result != null); + NetworkStats.Bucket bucket = new NetworkStats.Bucket(); + long totalTxPackets = 0; + long totalRxPackets = 0; + long totalTxBytes = 0; + long totalRxBytes = 0; + while (result.hasNextBucket()) { + assertTrue(result.getNextBucket(bucket)); + assertTimestamps(bucket); + if (bucket.getUid() == Process.myUid()) { + totalTxPackets += bucket.getTxPackets(); + totalRxPackets += bucket.getRxPackets(); + totalTxBytes += bucket.getTxBytes(); + totalRxBytes += bucket.getRxBytes(); + } + } + assertFalse(result.getNextBucket(bucket)); + assertTrue("No Rx bytes usage for uid " + Process.myUid(), totalRxBytes > 0); + assertTrue("No Rx packets usage for uid " + Process.myUid(), totalRxPackets > 0); + assertTrue("No Tx bytes usage for uid " + Process.myUid(), totalTxBytes > 0); + assertTrue("No Tx packets usage for uid " + Process.myUid(), totalTxPackets > 0); + } catch (RemoteException | SecurityException e) { + fail("testAppSummary fails with exception: " + e.toString()); + } finally { + if (result != null) { + result.close(); + } + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "deny"); + try { + result = mNsm.querySummary( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + fail("negative testAppSummary fails: no exception thrown."); + } catch (RemoteException e) { + fail("testAppSummary fails with exception: " + e.toString()); + } catch (SecurityException e) { + // expected outcome + } + } + } + + public void testAppDetails() throws Exception { + for (int i = 0; i < sNetworkTypesToTest.length; ++i) { + // Relatively large tolerance to accommodate for history bucket size. + if (!shouldTestThisNetworkType(i, MINUTE * 120)) { + continue; + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "allow"); + NetworkStats result = null; + try { + result = mNsm.queryDetails( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + assertTrue(result != null); + NetworkStats.Bucket bucket = new NetworkStats.Bucket(); + long totalTxPackets = 0; + long totalRxPackets = 0; + long totalTxBytes = 0; + long totalRxBytes = 0; + while (result.hasNextBucket()) { + assertTrue(result.getNextBucket(bucket)); + assertTimestamps(bucket); + assertEquals(bucket.getState(), NetworkStats.Bucket.STATE_ALL); + if (bucket.getUid() == Process.myUid()) { + totalTxPackets += bucket.getTxPackets(); + totalRxPackets += bucket.getRxPackets(); + totalTxBytes += bucket.getTxBytes(); + totalRxBytes += bucket.getRxBytes(); + } + } + assertFalse(result.getNextBucket(bucket)); + assertTrue("No Rx bytes usage for uid " + Process.myUid(), totalRxBytes > 0); + assertTrue("No Rx packets usage for uid " + Process.myUid(), totalRxPackets > 0); + assertTrue("No Tx bytes usage for uid " + Process.myUid(), totalTxBytes > 0); + assertTrue("No Tx packets usage for uid " + Process.myUid(), totalTxPackets > 0); + } catch (RemoteException | SecurityException e) { + fail("testAppDetails fails with exception: " + e.toString()); + } finally { + if (result != null) { + result.close(); + } + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "deny"); + try { + result = mNsm.queryDetails( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime); + fail("negative testAppDetails fails: no exception thrown."); + } catch (RemoteException e) { + fail("testAppDetails fails with exception: " + e.toString()); + } catch (SecurityException e) { + // expected outcome + } + } + } + + public void testUidDetails() throws Exception { + for (int i = 0; i < sNetworkTypesToTest.length; ++i) { + // Relatively large tolerance to accommodate for history bucket size. + if (!shouldTestThisNetworkType(i, MINUTE * 120)) { + continue; + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "allow"); + NetworkStats result = null; + try { + result = mNsm.queryDetailsForUid( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime, Process.myUid()); + assertTrue(result != null); + NetworkStats.Bucket bucket = new NetworkStats.Bucket(); + long totalTxPackets = 0; + long totalRxPackets = 0; + long totalTxBytes = 0; + long totalRxBytes = 0; + while (result.hasNextBucket()) { + assertTrue(result.getNextBucket(bucket)); + assertTimestamps(bucket); + assertEquals(bucket.getState(), NetworkStats.Bucket.STATE_ALL); + assertEquals(bucket.getUid(), Process.myUid()); + totalTxPackets += bucket.getTxPackets(); + totalRxPackets += bucket.getRxPackets(); + totalTxBytes += bucket.getTxBytes(); + totalRxBytes += bucket.getRxBytes(); + } + assertFalse(result.getNextBucket(bucket)); + assertTrue("No Rx bytes usage for uid " + Process.myUid(), totalRxBytes > 0); + assertTrue("No Rx packets usage for uid " + Process.myUid(), totalRxPackets > 0); + assertTrue("No Tx bytes usage for uid " + Process.myUid(), totalTxBytes > 0); + assertTrue("No Tx packets usage for uid " + Process.myUid(), totalTxPackets > 0); + } catch (RemoteException | SecurityException e) { + fail("testUidDetails fails with exception: " + e.toString()); + } finally { + if (result != null) { + result.close(); + } + } + setAppOpsMode(AppOpsManager.OPSTR_GET_USAGE_STATS, "deny"); + try { + result = mNsm.queryDetailsForUid( + sNetworkTypesToTest[i], getSubscriberId(sNetworkTypesToTest[i]), + mStartTime, mEndTime, Process.myUid()); + fail("negative testUidDetails fails: no exception thrown."); + } catch (RemoteException e) { + fail("testUidDetails fails with exception: " + e.toString()); + } catch (SecurityException e) { + // expected outcome + } + } + } + + private void assertTimestamps(final NetworkStats.Bucket bucket) { + assertTrue("Start timestamp " + bucket.getStartTimeStamp() + " is less than " + + mStartTime, bucket.getStartTimeStamp() >= mStartTime); + assertTrue("End timestamp " + bucket.getEndTimeStamp() + " is greater than " + + mEndTime, bucket.getEndTimeStamp() <= mEndTime); + } +}
diff --git a/tests/tests/app/Android.mk b/tests/tests/app/Android.mk index 39be0dca..301f931 100644 --- a/tests/tests/app/Android.mk +++ b/tests/tests/app/Android.mk
@@ -21,7 +21,7 @@ # and when built explicitly put it in the data partition LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) -LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common voip-common +LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common voip-common org.apache.http.legacy LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner ctstestserver @@ -31,4 +31,6 @@ LOCAL_INSTRUMENTATION_FOR := CtsAppTestStubs +LOCAL_SDK_VERSION := current + include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app/AndroidManifest.xml b/tests/tests/app/AndroidManifest.xml index 7c09cd2..d05648c 100644 --- a/tests/tests/app/AndroidManifest.xml +++ b/tests/tests/app/AndroidManifest.xml
@@ -18,10 +18,12 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.cts.app"> + <uses-sdk android:minSdkVersion="11" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.BODY_SENSORS" /> <application> <uses-library android:name="android.test.runner" /> + <uses-library android:name="org.apache.http.legacy" android:required="false" /> </application> <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/app/AndroidTest.xml b/tests/tests/app/AndroidTest.xml new file mode 100644 index 0000000..01ebbcb --- /dev/null +++ b/tests/tests/app/AndroidTest.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="Base config for CTS package preparer"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsSimpleApp.apk" /> +</configuration>
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java index 88828ea..dfa278a 100644 --- a/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java +++ b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTest.java
@@ -52,9 +52,11 @@ expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_MEDIUM, 32); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_TV, 48); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_HIGH, 48); - expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_XHIGH, 48); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_280, 48); + expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_XHIGH, 48); + expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_360, 64); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_400, 96); + expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_420, 112); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_XXHIGH, 128); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_560, 192); expectedMemorySizeForSmallNormalScreen.put(DisplayMetrics.DENSITY_XXXHIGH, 256); @@ -65,9 +67,11 @@ expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_MEDIUM, 64); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_TV, 80); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_HIGH, 80); - expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_XHIGH, 128); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_280, 96); + expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_XHIGH, 128); + expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_360, 160); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_400, 192); + expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_420, 228); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_XXHIGH, 256); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_560, 384); expectedMemorySizeForLargeScreen.put(DisplayMetrics.DENSITY_XXXHIGH, 512); @@ -78,9 +82,11 @@ expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_MEDIUM, 80); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_TV, 96); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_HIGH, 96); - expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_XHIGH, 192); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_280, 144); + expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_XHIGH, 192); + expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_360, 240); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_400, 288); + expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_420, 336); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_XXHIGH, 384); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_560, 576); expectedMemorySizeForXLargeScreen.put(DisplayMetrics.DENSITY_XXXHIGH, 768); @@ -135,8 +141,8 @@ } private void assertMemoryForScreenDensity(int memoryClass, int screenDensity, int screenSize) { - int expectedMinimumMemory = ExpectedMemorySizesClass.getExpectedMemorySize(screenDensity, - screenSize); + int expectedMinimumMemory = ExpectedMemorySizesClass.getExpectedMemorySize(screenSize, + screenDensity); assertTrue("Expected to have at least " + expectedMinimumMemory + "mb of memory for screen density " + screenDensity,
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerMemoryInfoTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryInfoTest.java index 3248caa..8ac5afb 100644 --- a/tests/tests/app/src/android/app/cts/ActivityManagerMemoryInfoTest.java +++ b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryInfoTest.java
@@ -34,7 +34,7 @@ } public void testWriteToParcel() throws Exception { - final long AVAILMEM = Process.getFreeMemory(); + final long AVAILMEM = 1000l; mMemory.availMem = AVAILMEM; final long THRESHOLD = 500l; mMemory.threshold = THRESHOLD; @@ -59,7 +59,7 @@ } public void testReadFromParcel() throws Exception { - final long AVAILMEM = Process.getFreeMemory(); + final long AVAILMEM = 1000l; mMemory.availMem = AVAILMEM; final long THRESHOLD = 500l; mMemory.threshold = THRESHOLD;
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java index e633f1f..02d13ef 100644 --- a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java +++ b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -16,21 +16,23 @@ package android.app.cts; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import android.app.Activity; import android.app.ActivityManager; -import android.app.Instrumentation; -import android.app.ActivityManager.ProcessErrorStateInfo; import android.app.ActivityManager.RecentTaskInfo; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.ActivityManager.RunningServiceInfo; import android.app.ActivityManager.RunningTaskInfo; +import android.app.ActivityOptions; +import android.app.Instrumentation; import android.app.Instrumentation.ActivityMonitor; import android.app.Instrumentation.ActivityResult; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.content.IntentFilter; import android.content.pm.ConfigurationInfo; import android.test.InstrumentationTestCase; @@ -39,6 +41,27 @@ private static final int WAITFOR_MSEC = 5000; private static final String SERVICE_NAME = "android.app.cts.MockService"; private static final int WAIT_TIME = 2000; + // A secondary test activity from another APK. + private static final String SIMPLE_PACKAGE_NAME = "com.android.cts.launcherapps.simpleapp"; + private static final String SIMPLE_ACTIVITY = ".SimpleActivity"; + private static final String SIMPLE_ACTIVITY_IMMEDIATE_EXIT = ".SimpleActivityImmediateExit"; + private static final String SIMPLE_ACTIVITY_CHAIN_EXIT = ".SimpleActivityChainExit"; + // The action sent back by the SIMPLE_APP after a restart. + private static final String ACTIVITY_LAUNCHED_ACTION = + "com.android.cts.launchertests.LauncherAppsTests.LAUNCHED_ACTION"; + // The action sent back by the SIMPLE_APP_IMMEDIATE_EXIT when it terminates. + private static final String ACTIVITY_EXIT_ACTION = + "com.android.cts.launchertests.LauncherAppsTests.EXIT_ACTION"; + // The action sent back by the SIMPLE_APP_CHAIN_EXIT when the task chain ends. + private static final String ACTIVITY_CHAIN_EXIT_ACTION = + "com.android.cts.launchertests.LauncherAppsTests.CHAIN_EXIT_ACTION"; + // The action sent to identify the time track info. + private static final String ACTIVITY_TIME_TRACK_INFO = "com.android.cts.TIME_TRACK_INFO"; + // Return states of the ActivityReceiverFilter. + public static final int RESULT_PASS = 1; + public static final int RESULT_FAIL = 2; + public static final int RESULT_TIMEOUT = 3; + private Context mContext; private ActivityManager mActivityManager; private Intent mIntent; @@ -119,6 +142,79 @@ } } + public void testGetRecentTasksLimitedToCurrentAPK() throws Exception { + int maxNum = 0; + int flags = 0; + + // Check the number of tasks at this time. + List<RecentTaskInfo> recentTaskList; + recentTaskList = mActivityManager.getRecentTasks(maxNum, flags); + int numberOfEntriesFirstRun = recentTaskList.size(); + + // Start another activity from another APK. + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setClassName(SIMPLE_PACKAGE_NAME, SIMPLE_PACKAGE_NAME + SIMPLE_ACTIVITY); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + ActivityReceiverFilter receiver = new ActivityReceiverFilter(ACTIVITY_LAUNCHED_ACTION); + mContext.startActivity(intent); + + // Make sure the activity has really started. + assertEquals(RESULT_PASS, receiver.waitForActivity()); + receiver.close(); + + // There shouldn't be any more tasks in this list at this time. + recentTaskList = mActivityManager.getRecentTasks(maxNum, flags); + int numberOfEntriesSecondRun = recentTaskList.size(); + assertTrue(numberOfEntriesSecondRun == numberOfEntriesFirstRun); + } + + // The receiver filter needs to be instantiated with the command to filter for before calling + // startActivity. + private class ActivityReceiverFilter extends BroadcastReceiver { + // The activity we want to filter for. + private String mActivityToFilter; + private int result = RESULT_TIMEOUT; + public long mTimeUsed = 0; + private static final int TIMEOUT_IN_MS = 1000; + + // Create the filter with the intent to look for. + public ActivityReceiverFilter(String activityToFilter) { + mActivityToFilter = activityToFilter; + IntentFilter filter = new IntentFilter(); + filter.addAction(mActivityToFilter); + mInstrumentation.getTargetContext().registerReceiver(this, filter); + } + + // Turn off the filter. + public void close() { + mInstrumentation.getTargetContext().unregisterReceiver(this); + } + + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(mActivityToFilter)) { + synchronized(this) { + result = RESULT_PASS; + if (mActivityToFilter.equals(ACTIVITY_TIME_TRACK_INFO)) { + mTimeUsed = intent.getExtras().getLong( + ActivityOptions.EXTRA_USAGE_TIME_REPORT); + } + notifyAll(); + } + } + } + + public int waitForActivity() { + synchronized(this) { + try { + wait(TIMEOUT_IN_MS); + } catch (InterruptedException e) { + } + } + return result; + } + } + private final <T extends Activity> void startSubActivity(Class<T> activityClass) { final Instrumentation.ActivityResult result = new ActivityResult(0, new Intent()); final ActivityMonitor monitor = new ActivityMonitor(activityClass.getName(), result, false); @@ -219,7 +315,8 @@ hasTestProcess = true; } } - assertTrue(hasSystemProcess && hasTestProcess); + // For security reasons the system process is not exposed. + assertTrue(!hasSystemProcess && hasTestProcess); for (RunningAppProcessInfo ra : list) { if (ra.processName.equals("com.android.cts.app.stub:remote")) { @@ -272,4 +369,158 @@ assertFalse("isRunningInTestHarness must be false in production builds", ActivityManager.isRunningInTestHarness()); } + + /** + * Go back to the home screen since running applications can interfere with application + * lifetime tests. + */ + private void launchHome() throws Exception { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.addCategory(Intent.CATEGORY_HOME); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + mContext.startActivity(intent); + Thread.sleep(WAIT_TIME); + } + + /** + * Verify that the TimeTrackingAPI works properly when starting and ending an activity. + */ + public void testTimeTrackingAPI_SimpleStartExit() throws Exception { + launchHome(); + // Prepare to start an activity from another APK. + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setClassName(SIMPLE_PACKAGE_NAME, + SIMPLE_PACKAGE_NAME + SIMPLE_ACTIVITY_IMMEDIATE_EXIT); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // Prepare the time receiver action. + Context context = mInstrumentation.getTargetContext(); + ActivityOptions options = ActivityOptions.makeBasic(); + Intent receiveIntent = new Intent(ACTIVITY_TIME_TRACK_INFO); + options.requestUsageTimeReport(PendingIntent.getBroadcast(context, + 0, receiveIntent, PendingIntent.FLAG_CANCEL_CURRENT)); + + // The application finished tracker. + ActivityReceiverFilter appEndReceiver = new ActivityReceiverFilter(ACTIVITY_EXIT_ACTION); + + // The filter for the time event. + ActivityReceiverFilter timeReceiver = new ActivityReceiverFilter(ACTIVITY_TIME_TRACK_INFO); + + // Run the activity. + mContext.startActivity(intent, options.toBundle()); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, appEndReceiver.waitForActivity()); + appEndReceiver.close(); + + // At this time the timerReceiver should not fire, even though the activity has shut down, + // because we are back to the home screen. + assertEquals(RESULT_TIMEOUT, timeReceiver.waitForActivity()); + assertTrue(timeReceiver.mTimeUsed == 0); + + // Issuing now another activity will trigger the timing information release. + final Intent dummyIntent = new Intent(context, MockApplicationActivity.class); + dummyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Activity activity = mInstrumentation.startActivitySync(dummyIntent); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, timeReceiver.waitForActivity()); + timeReceiver.close(); + assertTrue(timeReceiver.mTimeUsed != 0); + } + + /** + * Verify that the TimeTrackingAPI works properly when switching away from the monitored task. + */ + public void testTimeTrackingAPI_SwitchAwayTriggers() throws Exception { + launchHome(); + + // Prepare to start an activity from another APK. + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setClassName(SIMPLE_PACKAGE_NAME, SIMPLE_PACKAGE_NAME + SIMPLE_ACTIVITY); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // Prepare the time receiver action. + Context context = mInstrumentation.getTargetContext(); + ActivityOptions options = ActivityOptions.makeBasic(); + Intent receiveIntent = new Intent(ACTIVITY_TIME_TRACK_INFO); + options.requestUsageTimeReport(PendingIntent.getBroadcast(context, + 0, receiveIntent, PendingIntent.FLAG_CANCEL_CURRENT)); + + // The application started tracker. + ActivityReceiverFilter appStartedReceiver = new ActivityReceiverFilter( + ACTIVITY_LAUNCHED_ACTION); + + // The filter for the time event. + ActivityReceiverFilter timeReceiver = new ActivityReceiverFilter(ACTIVITY_TIME_TRACK_INFO); + + // Run the activity. + mContext.startActivity(intent, options.toBundle()); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, appStartedReceiver.waitForActivity()); + appStartedReceiver.close(); + + // At this time the timerReceiver should not fire since our app is running. + assertEquals(RESULT_TIMEOUT, timeReceiver.waitForActivity()); + assertTrue(timeReceiver.mTimeUsed == 0); + + // Starting now another activity will put ours into the back hence releasing the timing. + final Intent dummyIntent = new Intent(context, MockApplicationActivity.class); + dummyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Activity activity = mInstrumentation.startActivitySync(dummyIntent); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, timeReceiver.waitForActivity()); + timeReceiver.close(); + assertTrue(timeReceiver.mTimeUsed != 0); + } + + /** + * Verify that the TimeTrackingAPI works properly when handling an activity chain gets started + * and ended. + */ + public void testTimeTrackingAPI_ChainedActivityExit() throws Exception { + launchHome(); + // Prepare to start an activity from another APK. + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setClassName(SIMPLE_PACKAGE_NAME, + SIMPLE_PACKAGE_NAME + SIMPLE_ACTIVITY_CHAIN_EXIT); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // Prepare the time receiver action. + Context context = mInstrumentation.getTargetContext(); + ActivityOptions options = ActivityOptions.makeBasic(); + Intent receiveIntent = new Intent(ACTIVITY_TIME_TRACK_INFO); + options.requestUsageTimeReport(PendingIntent.getBroadcast(context, + 0, receiveIntent, PendingIntent.FLAG_CANCEL_CURRENT)); + + // The application finished tracker. + ActivityReceiverFilter appEndReceiver = new ActivityReceiverFilter( + ACTIVITY_CHAIN_EXIT_ACTION); + + // The filter for the time event. + ActivityReceiverFilter timeReceiver = new ActivityReceiverFilter(ACTIVITY_TIME_TRACK_INFO); + + // Run the activity. + mContext.startActivity(intent, options.toBundle()); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, appEndReceiver.waitForActivity()); + appEndReceiver.close(); + + // At this time the timerReceiver should not fire, even though the activity has shut down. + assertEquals(RESULT_TIMEOUT, timeReceiver.waitForActivity()); + assertTrue(timeReceiver.mTimeUsed == 0); + + // Issue another activity so that the timing information gets released. + final Intent dummyIntent = new Intent(context, MockApplicationActivity.class); + dummyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Activity activity = mInstrumentation.startActivitySync(dummyIntent); + + // Wait until it finishes and end the reciever then. + assertEquals(RESULT_PASS, timeReceiver.waitForActivity()); + timeReceiver.close(); + assertTrue(timeReceiver.mTimeUsed != 0); + } }
diff --git a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java index 9554438..58e69b8 100644 --- a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java +++ b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
@@ -577,26 +577,6 @@ assertEquals(view, mView); } - public void testSetViewCustom() throws Throwable { - final int viewSpacingLeft = 10; - final int viewSpacingTop = 20; - final int viewSpacingRight = 30; - final int viewSpacingBottom = 40; - final View view = new View(mContext); - view.setId(100); - runTestOnUiThread(new Runnable() { - public void run() { - mBuilder = new AlertDialog.Builder(mContext); - mBuilder.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight, - viewSpacingBottom); - mDialog = mBuilder.show(); - mView = mDialog.getWindow().findViewById(100); - } - }); - mInstrumentation.waitForIdleSync(); - assertEquals(view, mView); - } - public void testSetInverseBackgroundForced() throws Throwable { runTestOnUiThread(new Runnable() { public void run() {
diff --git a/tests/tests/app/src/android/app/cts/DownloadManagerTest.java b/tests/tests/app/src/android/app/cts/DownloadManagerTest.java index a68d860..55ad392 100644 --- a/tests/tests/app/src/android/app/cts/DownloadManagerTest.java +++ b/tests/tests/app/src/android/app/cts/DownloadManagerTest.java
@@ -32,13 +32,9 @@ import android.text.format.DateUtils; import android.webkit.cts.CtsTestServer; -import com.google.android.collect.Sets; - import java.io.File; import java.util.Arrays; import java.util.HashSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; public class DownloadManagerTest extends AndroidTestCase { @@ -96,6 +92,82 @@ } } + public void testDownloadManagerSupportsHttp() throws Exception { + final DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); + try { + IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); + mContext.registerReceiver(receiver, intentFilter); + + long id = mDownloadManager.enqueue(new Request(getGoodUrl())); + + assertEquals(1, getTotalNumberDownloads()); + + assertDownloadQueryableById(id); + + receiver.waitForDownloadComplete(SHORT_TIMEOUT, id); + + assertDownloadQueryableByStatus(DownloadManager.STATUS_SUCCESSFUL); + + assertRemoveDownload(id, 0); + } finally { + mContext.unregisterReceiver(receiver); + } + } + + public void testDownloadManagerSupportsHttpWithExternalWebServer() throws Exception { + // As a result of testDownloadManagerSupportsHttpsWithExternalWebServer relying on an + // external resource https://www.example.com this test uses http://www.example.com to help + // disambiguate errors from testDownloadManagerSupportsHttpsWithExternalWebServer. + + final DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); + try { + IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); + mContext.registerReceiver(receiver, intentFilter); + + long id = mDownloadManager.enqueue(new Request(Uri.parse("http://www.example.com"))); + + assertEquals(1, getTotalNumberDownloads()); + + assertDownloadQueryableById(id); + + receiver.waitForDownloadComplete(LONG_TIMEOUT, id); + + assertDownloadQueryableByStatus(DownloadManager.STATUS_SUCCESSFUL); + + assertRemoveDownload(id, 0); + } finally { + mContext.unregisterReceiver(receiver); + } + } + + public void testDownloadManagerSupportsHttpsWithExternalWebServer() throws Exception { + // For HTTPS, DownloadManager trusts only SSL server certs issued by CAs trusted by the + // system. Unfortunately, this means that it cannot trust the mock web server's SSL cert. + // Until this is resolved (e.g., by making it possible to specify additional CA certs to + // trust for a particular download), this test relies on https://www.example.com being + // operational and reachable from the Android under test. + + final DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); + try { + IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); + mContext.registerReceiver(receiver, intentFilter); + + long id = mDownloadManager.enqueue(new Request(Uri.parse("https://www.example.com"))); + + assertEquals(1, getTotalNumberDownloads()); + + assertDownloadQueryableById(id); + + receiver.waitForDownloadComplete(LONG_TIMEOUT, id); + + assertDownloadQueryableByStatus(DownloadManager.STATUS_SUCCESSFUL); + + assertRemoveDownload(id, 0); + } finally { + mContext.unregisterReceiver(receiver); + } + } + public void testMinimumDownload() throws Exception { final DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); try { @@ -233,7 +305,7 @@ } private class DownloadCompleteReceiver extends BroadcastReceiver { - private HashSet<Long> mCompleteIds = Sets.newHashSet(); + private HashSet<Long> mCompleteIds = new HashSet<>(); public DownloadCompleteReceiver() { }
diff --git a/tests/tests/app/src/android/app/cts/FragmentTest.java b/tests/tests/app/src/android/app/cts/FragmentTest.java index 006f0a9..5873ee0 100644 --- a/tests/tests/app/src/android/app/cts/FragmentTest.java +++ b/tests/tests/app/src/android/app/cts/FragmentTest.java
@@ -17,15 +17,8 @@ package android.app.cts; import android.app.Fragment; -import android.content.Context; import android.test.AndroidTestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; -import dalvik.annotation.ToBeFixed; -@TestTargetClass(Fragment.class) public class FragmentTest extends AndroidTestCase { public static class TestFragment extends Fragment {
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java index b21148e..25403f3 100644 --- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java +++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -540,7 +540,6 @@ public void openPanel(int featureId, KeyEvent event) { } - @Override public void alwaysReadCloseOnTouchAttr() { }
diff --git a/tests/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/tests/app/src/android/app/cts/NotificationManagerTest.java index 9a895ea..fbb3060 100644 --- a/tests/tests/app/src/android/app/cts/NotificationManagerTest.java +++ b/tests/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -22,12 +22,16 @@ import android.content.Context; import android.content.Intent; import android.provider.Telephony.Threads; +import android.service.notification.StatusBarNotification; import android.test.AndroidTestCase; +import android.util.Log; import com.android.cts.app.stub.R; public class NotificationManagerTest extends AndroidTestCase { + final String TAG = NotificationManagerTest.class.getSimpleName(); + final boolean DEBUG = false; private NotificationManager mNotificationManager; @@ -36,6 +40,8 @@ super.setUp(); mNotificationManager = (NotificationManager) mContext.getSystemService( Context.NOTIFICATION_SERVICE); + // clear the deck so that our getActiveNotifications results are predictable + mNotificationManager.cancelAll(); } @Override @@ -45,27 +51,54 @@ } public void testNotify() { + mNotificationManager.cancelAll(); + final int id = 1; sendNotification(id, R.drawable.black); + // test updating the same notification + sendNotification(id, R.drawable.blue); + sendNotification(id, R.drawable.yellow); + + // assume that sendNotification tested to make sure individual notifications were present + StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications(); + for (StatusBarNotification sbn : sbns) { + if (sbn.getId() != id) { + fail("we got back other notifications besides the one we posted: " + + sbn.getKey()); + } + } } public void testCancel() { final int id = 9; sendNotification(id, R.drawable.black); mNotificationManager.cancel(id); + + if (!checkNotificationExistence(id, /*shouldExist=*/ false)) { + fail("canceled notification was still alive, id=" + id); + } } public void testCancelAll() { sendNotification(1, R.drawable.black); sendNotification(2, R.drawable.blue); sendNotification(3, R.drawable.yellow); + + if (DEBUG) { + Log.d(TAG, "posted 3 notifications, here they are: "); + StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications(); + for (StatusBarNotification sbn : sbns) { + Log.d(TAG, " " + sbn); + } + Log.d(TAG, "about to cancel..."); + } mNotificationManager.cancelAll(); + + StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications(); + assertTrue("notification list was not empty after cancelAll", sbns.length == 0); } private void sendNotification(final int id, final int icon) { - final Notification notification = new Notification( - icon, "No intent", System.currentTimeMillis()); - final Intent intent = new Intent(Intent.ACTION_MAIN, Threads.CONTENT_URI); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP @@ -73,9 +106,40 @@ intent.setAction(Intent.ACTION_MAIN); final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); - notification.setLatestEventInfo(mContext, "notify#" + id, "This is #" + id - + "notification ", pendingIntent); + final Notification notification = new Notification.Builder(mContext) + .setSmallIcon(icon) + .setWhen(System.currentTimeMillis()) + .setContentTitle("notify#" + id) + .setContentText("This is #" + id + "notification ") + .setContentIntent(pendingIntent) + .build(); mNotificationManager.notify(id, notification); + + + if (!checkNotificationExistence(id, /*shouldExist=*/ true)) { + fail("couldn't find posted notification id=" + id); + } } + private boolean checkNotificationExistence(int id, boolean shouldExist) { + // notification is a bit asynchronous so it may take a few ms to appear in getActiveNotifications() + // we will check for it for up to 200ms before giving up + boolean found = false; + for (int tries=3; tries-->0;) { + final StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications(); + for (StatusBarNotification sbn : sbns) { + if (sbn.getId() == id) { + found = true; + break; + } + } + if (found == shouldExist) break; + try { + Thread.sleep(100); + } catch (InterruptedException ex) { + // pass + } + } + return found == shouldExist; + } }
diff --git a/tests/tests/app/src/android/app/cts/NotificationTest.java b/tests/tests/app/src/android/app/cts/NotificationTest.java index c2f62c3..6179922 100644 --- a/tests/tests/app/src/android/app/cts/NotificationTest.java +++ b/tests/tests/app/src/android/app/cts/NotificationTest.java
@@ -77,7 +77,7 @@ mNotification.tickerText = TICKER_TEXT; final RemoteViews contentView = new RemoteViews(mContext.getPackageName(), - com.android.internal.R.layout.status_bar_latest_event_content); + android.R.layout.simple_list_item_1); mNotification.contentView = contentView; mNotification.defaults = 0; mNotification.flags = 0; @@ -150,13 +150,19 @@ assertNull(result.sound); } - public void testSetLatestEventInfo() { - mNotification = new Notification(); - mNotification.icon = 1; + public void testBuilder() { final Intent intent = new Intent(); final PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); - mNotification.setLatestEventInfo(mContext, CONTENT_TITLE, CONTENT_TEXT, contentIntent); - assertTrue(mNotification.contentView instanceof RemoteViews); + mNotification = new Notification.Builder(mContext) + .setSmallIcon(1) + .setContentTitle(CONTENT_TITLE) + .setContentText(CONTENT_TEXT) + .setContentIntent(contentIntent) + .build(); + assertEquals(CONTENT_TEXT, mNotification.extras.getString(Notification.EXTRA_TEXT)); + assertEquals(CONTENT_TITLE, mNotification.extras.getString(Notification.EXTRA_TITLE)); + assertEquals(1, mNotification.icon); + assertEquals(contentIntent, mNotification.contentIntent); assertNotNull(mNotification.contentView); }
diff --git a/tests/tests/app/src/android/app/cts/ProgressDialogTest.java b/tests/tests/app/src/android/app/cts/ProgressDialogTest.java index 038b57b..b2037b6 100644 --- a/tests/tests/app/src/android/app/cts/ProgressDialogTest.java +++ b/tests/tests/app/src/android/app/cts/ProgressDialogTest.java
@@ -97,8 +97,7 @@ @UiThreadTest public void testShow2() { - ProgressDialog dialog = buildDialog(); - dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, false); + ProgressDialog dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, false); /* * note: the progress bar's style only supports indeterminate mode, @@ -120,11 +119,11 @@ // cancelable is false runTestOnUiThread(new Runnable() { public void run() { - ProgressDialog dialog = buildDialog(); - dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false); + ProgressDialog dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false); dialog.setOnCancelListener(cL); dialog.onBackPressed(); + dialog.dismiss(); } }); mInstrumentation.waitForIdleSync(); @@ -134,8 +133,7 @@ // cancelable is true runTestOnUiThread(new Runnable() { public void run() { - ProgressDialog dialog = buildDialog(); - dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true); + ProgressDialog dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true); assertFalse(mCanceled); dialog.setOnCancelListener(cL); dialog.onBackPressed(); @@ -156,10 +154,11 @@ // cancelable is false runTestOnUiThread(new Runnable() { public void run() { - ProgressDialog dialog = buildDialog(); - dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false, cL); + ProgressDialog dialog = ProgressDialog.show( + mContext, TITLE, MESSAGE, true, false, cL); dialog.onBackPressed(); + dialog.dismiss();; } }); mInstrumentation.waitForIdleSync(); @@ -169,8 +168,8 @@ // cancelable is true runTestOnUiThread(new Runnable() { public void run() { - ProgressDialog dialog = buildDialog(); - dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true, cL); + ProgressDialog dialog = ProgressDialog.show( + mContext, TITLE, MESSAGE, true, true, cL); assertFalse(mCanceled); dialog.onBackPressed();
diff --git a/tests/tests/assist/Android.mk b/tests/tests/assist/Android.mk new file mode 100644 index 0000000..89d2c49 --- /dev/null +++ b/tests/tests/assist/Android.mk
@@ -0,0 +1,33 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_STATIC_JAVA_LIBRARIES := CtsAssistCommon ctstestrunner ctsdeviceutil + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsAssistTestCases + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_PACKAGE) +include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/assist/AndroidManifest.xml b/tests/tests/assist/AndroidManifest.xml new file mode 100644 index 0000000..a81ced2 --- /dev/null +++ b/tests/tests/assist/AndroidManifest.xml
@@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.assist.cts"> + + <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> + <uses-permission android:name="android.permission.BIND_VOICE_INTERACTION" /> + <uses-permission android:name="android.permission.INTERNET" /> + + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name="android.assist.cts.TestStartActivity" + android:label="Assist Test Start Activity"> + <intent-filter> + <action android:name="android.intent.action.TEST_START_ACTIVITY_ASSIST_STRUCTURE" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_DISABLE_CONTEXT" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_FLAG_SECURE" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_LIFECYCLE" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_SCREENSHOT" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_EXTRA_ASSIST" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_TEXTVIEW" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_LARGE_VIEW_HIERARCHY" /> + <action android:name="android.intent.action.TEST_START_ACTIVITY_WEBVIEW" /> + <category android:name="android.intent.category.LAUNCHER" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + </application> + + <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="android.assist.cts" + android:label="CTS tests of android.assist"> + <meta-data android:name="listener" + android:value="com.android.cts.runner.CtsTestRunListener" /> + </instrumentation> +</manifest> +
diff --git a/tests/tests/assist/AndroidTest.xml b/tests/tests/assist/AndroidTest.xml new file mode 100644 index 0000000..329692d --- /dev/null +++ b/tests/tests/assist/AndroidTest.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<configuration description="Test module config for Assist"> + <include name="common-config" /> + <option name="cts-apk-installer:test-file-name" value="CtsAssistService.apk" /> + <option name="cts-apk-installer:test-file-name" value="CtsAssistApp.apk" /> + <option name="run-command:run-command" + value="settings put secure voice_interaction_service android.assist.service/.MainInteractionService" /> + <option name="cts-apk-installer:test-file-name" value="CtsAssistTestCases.apk" /> +</configuration>
diff --git a/tests/tests/assist/common/Android.mk b/tests/tests/assist/common/Android.mk new file mode 100644 index 0000000..88c90ee --- /dev/null +++ b/tests/tests/assist/common/Android.mk
@@ -0,0 +1,30 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_MODULE := CtsAssistCommon + +LOCAL_SDK_VERSION := current + +include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/tests/assist/common/src/android/assist/common/Utils.java b/tests/tests/assist/common/src/android/assist/common/Utils.java new file mode 100644 index 0000000..54416b4 --- /dev/null +++ b/tests/tests/assist/common/src/android/assist/common/Utils.java
@@ -0,0 +1,236 @@ +/* + * Copyright (C) 2015 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 android.assist.common; + +import android.R; +import android.content.ComponentName; +import android.os.Bundle; + +import org.json.JSONException; +import org.json.JSONObject; +import java.util.ArrayList; + +public class Utils { + public static final String TESTCASE_TYPE = "testcase_type"; + public static final String TESTINFO = "testinfo"; + public static final String ACTION_PREFIX = "android.intent.action."; + public static final String BROADCAST_INTENT = ACTION_PREFIX + "ASSIST_TESTAPP"; + public static final String BROADCAST_ASSIST_DATA_INTENT = ACTION_PREFIX + "ASSIST_DATA"; + public static final String BROADCAST_INTENT_START_ASSIST = ACTION_PREFIX + "START_ASSIST"; + public static final String ASSIST_RECEIVER_REGISTERED = ACTION_PREFIX + "ASSIST_READY"; + + public static final String ACTION_INVALIDATE = "invalidate_action"; + public static final String GET_CONTENT_VIEW_HEIGHT = ACTION_PREFIX + "GET_CONTENT_VIEW_HEIGHT"; + public static final String BROADCAST_CONTENT_VIEW_HEIGHT = ACTION_PREFIX + "VIEW_HEIGHT"; + public static final String SCROLL_TEXTVIEW_ACTION = ACTION_PREFIX + "TEXTVIEW_SCROLL"; + public static final String SCROLL_SCROLLVIEW_ACTION = ACTION_PREFIX + "SCROLLVIEW_SCROLL"; + public static final String TEST_ERROR = "Error In Test:"; + + public static final String ASSIST_STRUCTURE_KEY = "assist_structure"; + public static final String ASSIST_CONTENT_KEY = "assist_content"; + public static final String ASSIST_BUNDLE_KEY = "assist_bundle"; + public static final String ASSIST_SCREENSHOT_KEY = "assist_screenshot"; + public static final String SCREENSHOT_COLOR_KEY = "set_screenshot_color"; + public static final String COMPARE_SCREENSHOT_KEY = "compare_screenshot"; + public static final String DISPLAY_WIDTH_KEY = "display_width"; + public static final String DISPLAY_HEIGHT_KEY = "dislay_height"; + public static final String SCROLL_X_POSITION = "scroll_x_position"; + public static final String SCROLL_Y_POSITION = "scroll_y_position"; + + /** Lifecycle Test intent constants */ + public static final String LIFECYCLE_PREFIX = ACTION_PREFIX + "lifecycle_"; + public static final String LIFECYCLE_HASRESUMED = LIFECYCLE_PREFIX + "hasResumed"; + public static final String LIFECYCLE_ONPAUSE = LIFECYCLE_PREFIX + "onpause"; + public static final String LIFECYCLE_ONSTOP = LIFECYCLE_PREFIX + "onstop"; + public static final String LIFECYCLE_ONDESTROY = LIFECYCLE_PREFIX + "ondestroy"; + + /** Focus Change Test intent constants */ + public static final String GAINED_FOCUS = ACTION_PREFIX + "focus_changed"; + public static final String LOST_FOCUS = ACTION_PREFIX + "lost_focus"; + + /** Flag Secure Test intent constants */ + public static final String FLAG_SECURE_HASRESUMED = ACTION_PREFIX + "flag_secure_hasResumed"; + public static final String APP_3P_HASRESUMED = ACTION_PREFIX + "app_3p_hasResumed"; + public static final String TEST_ACTIVITY_LOADED = ACTION_PREFIX + "test_activity_hasResumed"; + + /** Two second timeout for getting back assist context */ + public static final int TIMEOUT_MS = 2 * 1000; + /** Four second timeout for an activity to resume */ + public static final int ACTIVITY_ONRESUME_TIMEOUT_MS = 4000; + + public static final String EXTRA_REGISTER_RECEIVER = "register_receiver"; + + /** Extras for passing the Assistant's ContentView's dimensions*/ + public static final String EXTRA_CONTENT_VIEW_HEIGHT = "extra_content_view_height"; + public static final String EXTRA_CONTENT_VIEW_WIDTH = "extra_content_view_width"; + public static final String EXTRA_DISPLAY_POINT = "extra_display_point"; + + /** Test name suffixes */ + public static final String ASSIST_STRUCTURE = "ASSIST_STRUCTURE"; + public static final String DISABLE_CONTEXT = "DISABLE_CONTEXT"; + public static final String FLAG_SECURE = "FLAG_SECURE"; + public static final String LIFECYCLE = "LIFECYCLE"; + public static final String SCREENSHOT = "SCREENSHOT"; + public static final String EXTRA_ASSIST = "EXTRA_ASSIST"; + public static final String VERIFY_CONTENT_VIEW = "VERIFY_CONTENT_VIEW"; + public static final String TEXTVIEW = "TEXTVIEW"; + public static final String LARGE_VIEW_HIERARCHY = "LARGE_VIEW_HIERARCHY"; + public static final String WEBVIEW = "WEBVIEW"; + public static final String FOCUS_CHANGE = "FOCUS_CHANGE"; + + /** Session intent constants */ + public static final String HIDE_SESSION = "android.intent.action.hide_session"; + + /** Stub html view to load into WebView */ + public static final String WEBVIEW_HTML_GREETING = "Hello WebView!"; + public static final String WEBVIEW_HTML = "<html><body><div><p>" + WEBVIEW_HTML_GREETING + + "</p></div></body></html>"; + + /** Extra data to add to assist data and assist content */ + private static Bundle EXTRA_ASSIST_BUNDLE; + private static String STRUCTURED_JSON; + + public static final String getStructuredJSON() throws Exception { + if (STRUCTURED_JSON == null) { + STRUCTURED_JSON = new JSONObject() + .put("@type", "MusicRecording") + .put("@id", "https://example/music/recording") + .put("url", "android-app://com.example/https/music/album") + .put("name", "Album Title") + .put("hello", "hi there") + .put("knownNull", null) + .put("unicode value", "\ud800\udc35") + .put("empty string", "") + .put("LongString", + "lkasdjfalsdkfjalsdjfalskj9i9234jl1w23j4o123j412l3j421l3kj412l3kj1l3k4j32") + .put("\ud800\udc35", "any-value") + .put("key with spaces", "any-value") + .toString(); + } + return STRUCTURED_JSON; + } + + public static final Bundle getExtraAssistBundle() { + if (EXTRA_ASSIST_BUNDLE == null) { + EXTRA_ASSIST_BUNDLE = new Bundle(); + addExtraAssistDataToBundle(EXTRA_ASSIST_BUNDLE); + } + return EXTRA_ASSIST_BUNDLE; + } + + public static void addExtraAssistDataToBundle(Bundle data) { + data.putString("hello", "there"); + data.putBoolean("isthis_true_or_false", true); + data.putInt("number", 123); + } + + /** The shim activity that starts the service associated with each test. */ + public static final String getTestActivity(String testCaseType) { + switch (testCaseType) { + case DISABLE_CONTEXT: + // doesn't need to wait for activity to resume + // can be activated on top of any non-secure activity. + return "service.DisableContextActivity"; + case ASSIST_STRUCTURE: + case FLAG_SECURE: + case LIFECYCLE: + case SCREENSHOT: + case EXTRA_ASSIST: + case VERIFY_CONTENT_VIEW: + case TEXTVIEW: + case LARGE_VIEW_HIERARCHY: + case WEBVIEW: + case FOCUS_CHANGE: + return "service.DelayedAssistantActivity"; + default: + return ""; + } + } + + /** + * The test app associated with each test. + */ + public static final ComponentName getTestAppComponent(String testCaseType) { + switch (testCaseType) { + case ASSIST_STRUCTURE: + case LARGE_VIEW_HIERARCHY: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.TestApp"); + case DISABLE_CONTEXT: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.TestApp"); + case FLAG_SECURE: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.SecureActivity"); + case LIFECYCLE: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.LifecycleActivity"); + case SCREENSHOT: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.ScreenshotActivity"); + case EXTRA_ASSIST: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.ExtraAssistDataActivity"); + case TEXTVIEW: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.TextViewActivity"); + case WEBVIEW: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.WebViewActivity"); + case FOCUS_CHANGE: + return new ComponentName( + "android.assist.testapp", "android.assist.testapp.FocusChangeActivity"); + default: + return new ComponentName("",""); + } + } + + /** + * Returns the amount of time to wait for assist data. + */ + public static final int getAssistDataTimeout(String testCaseType) { + switch (testCaseType) { + case SCREENSHOT: + // needs to wait for 3p activity to resume before receiving assist data. + return TIMEOUT_MS + ACTIVITY_ONRESUME_TIMEOUT_MS; + default: + return TIMEOUT_MS; + } + } + + public static final String toBundleString(Bundle bundle) { + if (bundle == null) { + return "*** Bundle is null ****"; + } + StringBuffer buf = new StringBuffer("Bundle is: "); + String testType = bundle.getString(TESTCASE_TYPE); + if (testType != null) { + buf.append("testcase type = " + testType); + } + ArrayList<String> info = bundle.getStringArrayList(TESTINFO); + if (info != null) { + for (String s : info) { + buf.append(s + "\n\t\t"); + } + } + return buf.toString(); + } + + public static final void addErrorResult(final Bundle testinfo, final String msg) { + testinfo.getStringArrayList(testinfo.getString(Utils.TESTCASE_TYPE)) + .add(TEST_ERROR + " " + msg); + } +}
diff --git a/tests/tests/assist/res/layout/multiple_text_views.xml b/tests/tests/assist/res/layout/multiple_text_views.xml new file mode 100644 index 0000000..455d5e3 --- /dev/null +++ b/tests/tests/assist/res/layout/multiple_text_views.xml
@@ -0,0 +1,79 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + + <ScrollView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1"> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + </ScrollView> +</LinearLayout> \ No newline at end of file
diff --git a/tests/tests/assist/res/layout/screenshot_activity.xml b/tests/tests/assist/res/layout/screenshot_activity.xml new file mode 100644 index 0000000..05051dc --- /dev/null +++ b/tests/tests/assist/res/layout/screenshot_activity.xml
@@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<RelativeLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/screenshot_activity" + android:layout_width="match_parent" + android:layout_height="match_parent"> +</RelativeLayout> \ No newline at end of file
diff --git a/tests/tests/assist/res/layout/test_app.xml b/tests/tests/assist/res/layout/test_app.xml new file mode 100644 index 0000000..3fbfd6d --- /dev/null +++ b/tests/tests/assist/res/layout/test_app.xml
@@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/welcome" /> + <LinearLayout + android:layout_width="match_parent" + android:layout_height="350dp" + android:orientation="vertical" + android:layout_gravity="bottom"> + <FrameLayout + android:id="@+id/card1" + android:layout_width="match_parent" + android:layout_height="150dp" + android:layout_marginStart="8dp" + android:layout_marginEnd="8dp" + android:layout_marginTop="16dp" + android:elevation="3dp"> + </FrameLayout> + <View + android:id="@+id/card2" + android:layout_width="match_parent" + android:layout_height="200dp" + android:layout_marginStart="8dp" + android:layout_marginEnd="8dp" + android:layout_marginTop="16dp" + android:elevation="3dp"/> + </LinearLayout> +</RelativeLayout> \ No newline at end of file
diff --git a/tests/tests/assist/res/layout/text_view.xml b/tests/tests/assist/res/layout/text_view.xml new file mode 100644 index 0000000..9964ab6 --- /dev/null +++ b/tests/tests/assist/res/layout/text_view.xml
@@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <TextView + android:id="@+id/text_view" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1" + android:focusable="false" + android:focusableInTouchMode="false" + android:scrollbars="vertical" + android:clickable="true" + android:text="@string/text_too_large_to_fit" /> + + <ScrollView + android:id="@+id/scroll_view" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_weight="1"> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:scrollbars="vertical" + android:text="@string/text_too_large_to_fit" /> + </ScrollView> +</LinearLayout> \ No newline at end of file
diff --git a/tests/tests/assist/res/layout/webview.xml b/tests/tests/assist/res/layout/webview.xml new file mode 100644 index 0000000..bdb8082 --- /dev/null +++ b/tests/tests/assist/res/layout/webview.xml
@@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + <WebView + android:id="@+id/webview" + android:layout_width="match_parent" + android:layout_height="match_parent"> + </WebView> +</LinearLayout> \ No newline at end of file
diff --git a/tests/tests/assist/res/values/strings.xml b/tests/tests/assist/res/values/strings.xml new file mode 100644 index 0000000..8170d70 --- /dev/null +++ b/tests/tests/assist/res/values/strings.xml
@@ -0,0 +1,284 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> +<resources> + <string name="welcome">Hello there!</string> + <string name="testAppTitle">Assist Structure Test Activity</string> + <string name="screenshotActivityTitle">Screenshot Test Activity</string> + <string name="textViewActivityTitle">TextView Test Activity</string> + <string name="webViewActivityTitle">WebView Test Activity</string> + <string name="text_too_large_to_fit">❤ ☀ ☆ ☂ ☻ ♞ ☯ ☭ ☢ € →Hello هتاف للترحيب שלום + përshëndetje Добры дзень 您好 হ্যালো здравей მიესალმები Χαίρετε હેલો नमस्ते Nnọọ こんにちは ಹಲೋ + Сәлеметсіз бе ជំរាបសួរ 안녕하세요 ສະບາຍດີ ഹലോ हॅलो Сайн байна уу नमस्ते سلامהעלא ہیلو + မင်္ဂလာပါ ਸਤ ਸ੍ਰੀ ਅਕਾਲ Здравствуйте здраво ආයුබෝවන් ஹலோ హలో สวัสดี Pẹlẹ o + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + convallis nunc et vestibulum. Sed et consequat quam, blandit varius tortor. Curabitur + accumsan nulla lectus, placerat condimentum odio elementum vel. Nulla erat ex, accumsan ut + enim sagittis, scelerisque efficitur ante. Nullam quis orci nec magna maximus malesuada ac + id sem. Nam sagittis erat risus, a accumsan neque congue sit amet. Nullam risus velit, + faucibus eget scelerisque et, maximus eget arcu. Sed porta sed libero ac imperdiet. + + Nulla sem lectus, ullamcorper id dui vel, rutrum interdum augue. Proin aliquam nisi vitae + hendrerit tempor. Mauris porttitor velit et egestas feugiat. Vivamus eu dapibus libero, + quis fringilla urna. Suspendisse non turpis dui. Vivamus facilisis diam vitae est auctor + luctus. Etiam quis lectus viverra, interdum turpis eu, aliquam sem. Nulla vulputate lacinia + nisi a dictum. Cras faucibus vitae tortor at ullamcorper. Quisque sit amet sapien maximus, + ornare nisi non, imperdiet magna. Vestibulum tempor metus ac mi ultrices dapibus. + + Suspendisse potenti. Mauris pellentesque lacinia tristique. Pellentesque vel dui quis sem + lacinia imperdiet feugiat vitae sem. Proin a arcu magna. Sed quis augue eu mi accumsan + pellentesque pretium in leo. Duis euismod purus mauris, ac tempor erat auctor non. Quisque + bibendum est pulvinar ex dapibus, ac tincidunt nibh tempus. Mauris sodales sem id purus + commodo iaculis. Pellentesque a quam dapibus, vehicula lectus at, tincidunt arcu. In + placerat porttitor urna quis consequat. Nullam feugiat nisl sed urna hendrerit, sed + elementum massa iaculis. Fusce sit amet turpis hendrerit, varius lorem sed, luctus mi. + Phasellus sit amet ex orci. Duis scelerisque nisl quis efficitur maximus. Curabitur vitae + accumsan nunc, eget varius nisi. + + Fusce efficitur malesuada luctus. Aliquam dapibus tortor sit amet purus semper, sit amet + pretium lorem feugiat. Maecenas gravida sed arcu et placerat. Nulla facilisi. Cras placerat + rutrum mi, in rutrum mauris maximus at. Mauris eu suscipit ante. Nullam pharetra egestas + diam a viverra. Donec sem turpis, tempor malesuada est vel, blandit accumsan magna. In + iaculis velit in efficitur hendrerit. Nulla facilisi. Curabitur eget ligula lorem. Sed sit + amet dolor ut ligula malesuada condimentum. Phasellus molestie augue eget libero commodo, + vel blandit ex blandit. + + Morbi cursus tortor ante, et tempus nisi tempus et. Suspendisse quis gravida diam. Aliquam + efficitur dolor sit amet sollicitudin varius. Etiam libero purus, ornare nec nulla vel, + ullamcorper blandit nisl. Sed vel consequat diam, id placerat sem. Donec quis elementum + urna. In posuere bibendum nunc, in condimentum justo blandit ac. Quisque enim lorem, + gravida at purus at, sollicitudin imperdiet erat. Ut consectetur rutrum ante, et pretium + odio iaculis a. Nullam a nibh vulputate, volutpat lectus eu, pellentesque felis. Nam + vehicula suscipit diam nec convallis. Quisque congue maximus sem, sit amet hendrerit leo + tempor et. + + Nam eu consequat dui. Sed semper dignissim mattis. Integer tortor eros, tempor in lectus a, + lobortis aliquam dolor. Phasellus at sagittis magna. Nulla eleifend orci ac urna auctor, + sit amet luctus urna vulputate. Nulla venenatis venenatis erat ac finibus. Etiam + ullamcorper elementum suscipit. Morbi nec velit non mauris porta finibus. Nullam in + sagittis odio. Praesent eget nisl ut mauris vestibulum feugiat. Sed vulputate at elit et + cursus. Praesent viverra erat blandit nunc egestas, vel feugiat ex condimentum. Class + aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. + + Nulla fermentum mattis urna, non gravida eros vestibulum et. Fusce porttitor augue turpis, + sit amet aliquam augue sodales non. Nunc neque odio, sagittis sed gravida euismod, commodo + at libero. Donec porttitor pulvinar neque vitae lobortis. Aliquam accumsan velit nec sapien + placerat egestas. Aliquam at tincidunt massa, et dignissim justo. Donec sapien ante, rutrum + et tristique a, commodo a massa. + + Nunc placerat lobortis magna, et molestie lacus semper porta. Lorem ipsum dolor sit amet, + consectetur adipiscing elit. Phasellus ac ligula dui. Duis ultrices viverra eros fermentum + finibus. Integer ultrices, felis in accumsan volutpat, mi ligula hendrerit nunc, nec + accumsan mauris tellus sit amet metus. Ut pharetra enim et sapien sollicitudin, nec + ultricies urna pharetra. Morbi non tortor nec dui feugiat rutrum. Aliquam malesuada sodales + risus, sed congue nunc accumsan vitae. Etiam nunc magna, tempus non suscipit eu, feugiat ut + nibh. Maecenas et libero ut nisl pellentesque tempor nec vel quam. Etiam sem ligula, + ullamcorper non dolor a, viverra placerat nulla. Nullam dictum commodo dui, sed ultrices + enim sagittis eget. Morbi non consectetur lectus. In gravida, augue vitae pulvinar + molestie, ligula orci vulputate ex, at bibendum urna felis nec nibh. Sed nisl nunc, iaculis + at augue venenatis, fringilla accumsan velit. Curabitur nec augue porttitor, rutrum nisi + vitae, elementum orci. + + Vestibulum eu tortor iaculis, dignissim velit quis, rhoncus dolor. Donec et tincidunt + nulla. Duis faucibus auctor erat ac ultricies. In a fermentum mi. Fusce vitae mi id sem + interdum tincidunt. Nulla hendrerit orci turpis, in maximus elit mollis eget. Aliquam erat + volutpat. Phasellus mattis est nibh, ut scelerisque ligula egestas eu. Ut molestie orci a + malesuada tempor. Sed tempus arcu id orci gravida faucibus. Vivamus ac lacinia neque, at + vehicula magna. + + Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; + Nullam aliquam, justo scelerisque egestas sodales, purus odio posuere arcu, ac ultrices + nunc felis non massa. Aliquam vulputate ipsum sed aliquet auctor. In pulvinar, eros sit + amet ultricies tristique, lacus ipsum scelerisque eros, nec vestibulum est lectus quis + lorem. Pellentesque ac augue ut eros mattis viverra vitae ut lacus. Phasellus imperdiet + efficitur elit eget tincidunt. Donec sodales metus at dolor pulvinar, at gravida nibh + facilisis. Sed nec tellus luctus, cursus lacus sed, euismod orci. Maecenas sit amet leo + orci. Nulla non leo non mi eleifend consequat sit amet vitae dui. Sed gravida gravida + justo, tincidunt ultrices justo semper vitae. Fusce at nisi nisl. Morbi molestie quis justo + a convallis. Curabitur massa lacus, feugiat quis mauris ac, malesuada viverra est. + + Phasellus bibendum faucibus velit, ac scelerisque velit tincidunt eu. Curabitur quis + suscipit erat, ac feugiat odio. Nullam et sapien et nibh maximus posuere. Vivamus faucibus + justo eget dictum sollicitudin. Etiam at leo eget elit facilisis lobortis. Maecenas + bibendum tortor non erat pretium dignissim. Fusce id imperdiet augue. Suspendisse dignissim + magna vel odio viverra varius. Maecenas suscipit ante et lorem sodales vehicula. Quisque + vel magna id sem suscipit iaculis. Etiam in elementum risus. + + Suspendisse odio nisi, pharetra et purus sit amet, placerat lobortis diam. Phasellus enim + nunc, posuere sed porta in, ornare eu ipsum. Phasellus imperdiet porta neque, vitae dapibus + tellus feugiat eget. Nulla sodales leo ac efficitur luctus. Vivamus eget ipsum quis ante + pulvinar blandit. Vestibulum a justo convallis justo elementum viverra ut sit amet nisl. + Suspendisse eget augue fermentum, sagittis risus a, rhoncus elit. Vestibulum in maximus + tortor, non vestibulum libero. Nunc accumsan neque a nisl dapibus, id laoreet neque congue. + Pellentesque sapien odio, fringilla non nulla nec, varius placerat diam. Aliquam + consectetur neque eu ipsum posuere, nec dignissim sem faucibus. Donec sit amet tempor + sapien. Nam at libero vel lorem dapibus ultrices a vel augue. Nunc facilisis justo ante, + mollis tristique velit aliquet quis. Mauris consectetur odio at urna bibendum aliquam. + + Nullam lectus orci, hendrerit ut ultrices in, dapibus pellentesque nibh. Aliquam arcu + metus, lobortis vel dignissim id, tempus ut ante. Integer vitae ante augue. In hac habitasse + platea dictumst. Vestibulum in tellus ante. Cras nisi tellus, congue ac velit quis, rhoncus + ornare ligula. Sed facilisis gravida pellentesque. Praesent id ultrices orci, ac ultricies + arcu. Donec at ante quis augue faucibus congue. Donec mattis quam dui, ut vestibulum orci + tempor mattis. Phasellus in quam id tortor varius ullamcorper ac ac ante. Proin cursus + accumsan sem, vel finibus lectus eleifend ut. Donec efficitur feugiat diam id ultricies. In + quis euismod nisi. Vestibulum eget viverra sapien. Donec scelerisque nec elit vel viverra. + + Sed mi urna, rutrum quis augue vel, aliquet placerat diam. Proin faucibus in odio et + consequat. Proin ut ex in mauris eleifend efficitur. Praesent ullamcorper sollicitudin urna, + sed mollis elit hendrerit non. Duis leo lorem, efficitur eu auctor sit amet, scelerisque + scelerisque magna. Mauris eget massa auctor, viverra arcu a, elementum nibh. Sed + pellentesque, nulla sed condimentum posuere, tortor metus congue sem, nec placerat neque + magna vitae purus. + + Etiam at risus vitae sapien aliquam condimentum. Vestibulum id libero placerat purus + vehicula consectetur. Pellentesque sapien sapien, posuere at pulvinar at, ultrices sed est. + Maecenas nec condimentum ante. Aenean volutpat, ex condimentum hendrerit hendrerit, quam + nisl pharetra nibh, vitae bibendum nisl odio vel lacus. Morbi mi tellus, bibendum id mauris + eu, facilisis volutpat turpis. Maecenas rutrum convallis felis. Quisque eget feugiat felis. + Duis pellentesque iaculis massa ut facilisis. Donec nec commodo magna. Integer aliquet orci + a odio eleifend elementum. Quisque molestie, urna ut molestie eleifend, odio neque maximus + enim, eget viverra metus lectus eget quam. Fusce nec urna ac neque bibendum aliquam vel quis + dui. Fusce ac quam consequat, feugiat leo vitae, auctor felis. + + Sed ac metus mauris. Sed sed velit ut tortor aliquam vestibulum at eu arcu. Etiam eu + posuere lacus. Maecenas id lacus quis sem mollis sodales. Quisque justo sapien, vulputate ac + mi ut, congue vestibulum orci. Donec euismod erat rutrum, laoreet urna sed, accumsan purus. + Donec eu quam a sapien condimentum accumsan. Sed at tellus lorem. Curabitur bibendum, arcu + sit amet finibus sodales, mi sem finibus sem, eget scelerisque tellus neque vel urna. + Suspendisse eu augue nec erat suscipit luctus sed non metus. + + Suspendisse porttitor ex ipsum. Pellentesque tristique eros sed pharetra porttitor. + Quisque ut elit vehicula, aliquet est nec, faucibus tellus. Donec ex augue, congue eu + dignissim maximus, vestibulum at purus. Nulla quam enim, laoreet sit amet molestie vel, + dapibus nec tortor. Sed interdum massa ac orci gravida, vel viverra lacus lacinia. Donec + nisl lacus, fermentum at faucibus ac, consequat ut nibh. Praesent laoreet est augue, vitae + maximus dui efficitur sit amet. Cras ipsum tellus, tincidunt at volutpat non, tincidunt ut + elit. Morbi commodo sagittis gravida. Pellentesque sed ante massa. Phasellus a turpis non + turpis cursus consequat sed nec tortor. Proin et augue elit. + + Duis finibus sem commodo rutrum pulvinar. In sollicitudin ante magna, vel facilisis + tellus fringilla vel. Nam purus ex, tincidunt eget varius at, euismod nec elit. Curabitur + consequat nulla vel nisi iaculis, ut mattis odio congue. Nulla et mollis tortor, a maximus + justo. Donec semper eros sed nunc rhoncus condimentum. Donec nibh purus, interdum non lectus + id, porta convallis eros. + + Sed hendrerit, dui non sagittis sollicitudin, enim ex imperdiet sapien, et maximus lorem + dolor a enim. Nulla risus nisl, vestibulum at ornare posuere, congue in felis. Duis sagittis + id diam a varius. Donec viverra eu orci sodales commodo. Cras metus tortor, sodales vitae + auctor non, scelerisque a ante. Quisque sodales nisi libero, ut lobortis enim suscipit ut. + Cras mi ipsum, maximus non bibendum sit amet, pharetra quis ipsum. Vestibulum venenatis, odi + at hendrerit pretium, tellus diam auctor justo, non posuere quam mauris id nisl. Nam dolor + nibh, molestie et lectus et, scelerisque porta elit. Vestibulum viverra condimentum auctor. + In eros tortor, convallis sed quam eu, ultrices malesuada purus. Integer lorem quam, + ultricies at est consectetur, sagittis porttitor eros. Proin non risus vitae lacus + consectetur malesuada non pulvinar justo. Aliquam mollis nisi nunc, sit amet vulputate metus + sollicitudin vel. + + Quisque auctor varius fermentum. Praesent mollis justo sit amet est consectetur, in + volutpat tellus mollis. Aenean at bibendum eros, at finibus nibh. Phasellus nec mi sem. + Mauris pellentesque dui sit amet lobortis aliquam. Ut nec massa at urna aliquam gravida vel + in magna. Donec consectetur sapien magna, a auctor sapien placerat eu. + + Pellentesque aliquet ante sed lacus gravida rutrum. Maecenas euismod varius felis, nec + tempus metus tempus et. Nam convallis augue a massa scelerisque, vel pharetra dolor + scelerisque. Fusce porttitor mi a magna rutrum condimentum. Aliquam fermentum at turpis at + auctor. Nulla ut suscipit dui. Donec rutrum viverra aliquam. Donec elementum nisl sapien, ac + blandit risus porta facilisis. Proin tellus dolor, ornare vel magna sit amet, maximus + volutpat felis. Aenean euismod aliquet purus, at finibus nunc elementum eu. Ut faucibus + ullamcorper consectetur. Aenean egestas arcu id mauris elementum, at sollicitudin est + congue. Sed a odio mattis, sollicitudin erat ut, tristique dolor. Aliquam luctus risus quis + tellus semper, a vestibulum nulla viverra. + + Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos + himenaeos. Vestibulum sit amet nisi felis. Praesent condimentum consequat lacus pulvinar + imperdiet. Praesent vel condimentum quam. Maecenas eu aliquet odio. Vestibulum sed nulla + mattis lacus porta bibendum a ac eros. Nunc porttitor sagittis laoreet. Duis porta eros at + congue tristique. Pellentesque quis fringilla neque, a hendrerit tellus. Pellentesque ac + nibh ac tellus pulvinar porttitor et in est. Integer blandit lorem libero, eu pulvinar + tellus posuere eget. Vivamus pretium nulla ligula, ut dapibus massa fringilla in. + Suspendisse consectetur sem non elit porta, id pellentesque erat dapibus. Quisque ex mi, + tempus et hendrerit nec, gravida quis odio. Ut at mi in leo scelerisque venenatis. + + Ut sed tellus in risus tincidunt tempor ut at arcu. Maecenas ut convallis justo. In + rutrum urna eu massa rhoncus, eget condimentum augue vehicula. Nullam eget placerat erat. + Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. + Aenean at volutpat orci, a lobortis dolor. Sed consequat facilisis interdum. Fusce libero + neque, fringilla in congue a, vehicula rutrum ipsum. Nam ornare placerat vestibulum. Proin + nec orci velit. Pellentesque scelerisque gravida diam, ut tristique libero tempus eu. Nam + semper lacus nec nulla volutpat imperdiet non eget tortor. Sed et pellentesque ligula. + + Aenean a dolor dolor. Curabitur ut placerat lacus, sit amet aliquet orci. Aliquam erat + volutpat. Cras mollis sit amet lectus ornare pretium. Vestibulum fringilla orci vel est + iaculis, at mattis quam condimentum. Vivamus semper elit consectetur lectus gravida, in + sollicitudin mi fringilla. Donec eget lorem in orci blandit aliquam. Pellentesque libero + tellus, dignissim id augue et, vulputate viverra nisl. Cum sociis natoque penatibus et + magnis dis parturient montes, nascetur ridiculus mus. Donec ac vulputate metus, eu suscipit + sem. Donec placerat, nulla at sodales hendrerit, orci tortor vestibulum purus, non pharetra + nulla purus posuere arcu. + + Quisque feugiat elit sem, ac interdum diam pharetra nec. Curabitur sem libero, vulputate + eu libero vitae, volutpat facilisis ligula. Aenean maximus erat laoreet, interdum ante in, + ultrices nisi. Nullam nec efficitur sapien. Integer feugiat et tortor ac bibendum. Donec a + scelerisque tortor. Cras quis viverra diam, vitae viverra ipsum. Aliquam ultrices neque sem, + congue sodales elit tempus sit amet. Pellentesque habitant morbi tristique senectus et netus + et malesuada fames ac turpis egestas. Sed dignissim ipsum eget diam rhoncus, ut finibus + nulla pretium. Morbi suscipit nibh vel nisl posuere molestie. Maecenas posuere turpis et + rutrum consectetur. Morbi venenatis arcu non gravida vulputate. Vivamus auctor tellus + ullamcorper ligula vestibulum cursus. Nunc gravida sit amet nisl quis facilisis. + + Praesent ut justo vestibulum, accumsan mi et, feugiat purus. Nullam pulvinar iaculis + pharetra. Aliquam pulvinar risus sit amet elit suscipit tincidunt. In hac habitasse platea + dictumst. Etiam eget velit ac magna lacinia efficitur. Vestibulum ante ipsum primis in + faucibus orci luctus et ultrices posuere cubilia Curae; Cras volutpat tempus sollicitudin. + Ut et ante elit. + + Sed ac tortor justo. Fusce sed metus libero. Duis sagittis tortor ac ante sollicitudin, + nec efficitur nibh euismod. Donec porttitor cursus quam, in aliquam lorem feugiat ut. + Aliquam tempor lacus eu feugiat feugiat. Nunc pulvinar, libero at auctor commodo, metus diam + commodo lorem, in feugiat elit ex non ligula. Quisque at vestibulum sapien, nec facilisis + neque. Aenean luctus, arcu ut rhoncus luctus, est massa rhoncus mauris, nec luctus urna sem + quis massa. Nam elit felis, congue et ligula eget, ultricies tincidunt erat. Vivamus + eleifend no dui ac dictum. In nulla justo, pulvinar ut tristique sed, congue et orci. + + Quisque imperdiet mi lectus, ac scelerisque augue posuere ut. Duis non pulvinar ipsum, + finibus risus. Donec ullamcorper nisl at sodales lobortis. Mauris neque leo, vestibulum sit + amet placerat vel, aliquet vel sapien. Morbi massa tellus, scelerisque quis nisl in, feugiat + posuere augue. Aenean congue sem ut ipsum vulputate rhoncus vitae at eros. Maecenas in velit + orci pellentesque lobortis ac at felis. Vestibulum odio quam, lacinia dapibus ornare eu, + vulputate a eros. Curabitur eleifend ornare tellus, non sollicitudin justo viverra in. Sed + sodales neque et lacus semper, in pharetra est consequat. Nunc vehicula volutpat lectus, sit + amet scelerisque nisi. Aenean sollicitudin, sem at ultricies efficitur, eros metus + nisl, et fringilla felis lacus non orci. Praesent eros libero, finibus in purus id, + tempor ipsum. Donec suscipit libero velit. Aliquam quis diam pharetra, cursus ipsum in, + gravida metus. Maecenas ultrices ligula a ullamcorper scelerisque. + + Donec tincidunt felis turpis, id venenatis neque convallis in. Proin euismod ligula nec + urna vulputate, sed elementum mauris ultrices. Ut efficitur sem vel mi vestibulum placerat. + Sed fermentum lacus nec metus dictum, a commodo quam fermentum. Sed vel vulputate magna. + Integer convallis nisi sit amet mi lobortis pellentesque. In egestas porttitor elit eu + scelerisque. Suspendisse eleifend vel enim quis tincidunt. Sed placerat risus et pretium + porttitor. Nam justo mi, cursus eu pellentesque vel, bibendum ut nisl. Nulla condimentum + lorem, non sagittis lorem volutpat vitae. Mauris nec libero lorem. Vestibulum lacus ex, + vulputate non massa vitae, pellentesque vestibulum dolor. + + Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; + Suspendisse vitae erat nisl. Vestibulum elit ante, semper et semper sit amet, fringilla + sapien. Morbi ac nisi sit amet turpis tincidunt mattis ac eget nisl. Nunc a venenatis quam, + facilisis maximus odio. Aliquam erat volutpat. Maecenas leo enim, ornare a magna quis, + venenatis ornare nulla. Aliquam venenatis nibh et elit tincidunt, ut egestas lorem finibus. + Integer iaculis dolor sed enim blandit vestibulum. Nullam vel libero ultricies, sagittis + tortor non, molestie eros.</string> +</resources>
diff --git a/tests/tests/assist/res/xml/interaction_service.xml b/tests/tests/assist/res/xml/interaction_service.xml new file mode 100644 index 0000000..c968795 --- /dev/null +++ b/tests/tests/assist/res/xml/interaction_service.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android" + android:sessionService="android.assist.service.MainInteractionSessionService" + android:recognitionService="android.assist.service.MainRecognitionService" + android:settingsActivity="android.assist.service.SettingsActivity" + android:supportsAssist="false" />
diff --git a/tests/tests/assist/service/Android.mk b/tests/tests/assist/service/Android.mk new file mode 100644 index 0000000..07dc228 --- /dev/null +++ b/tests/tests/assist/service/Android.mk
@@ -0,0 +1,32 @@ +# Copyright (C) 2015 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. + +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +# don't include this package in any target +LOCAL_MODULE_TAGS := optional +# and when built explicitly put it in the data partition +LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) + +LOCAL_STATIC_JAVA_LIBRARIES := CtsAssistCommon ctstestrunner ctsdeviceutil + +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_PACKAGE_NAME := CtsAssistService + +LOCAL_SDK_VERSION := current + +include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/tests/assist/service/AndroidManifest.xml b/tests/tests/assist/service/AndroidManifest.xml new file mode 100644 index 0000000..354d771 --- /dev/null +++ b/tests/tests/assist/service/AndroidManifest.xml
@@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2015 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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="android.assist.service"> + + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> + + <application> + <uses-library android:name="android.test.runner" /> + <service android:name=".MainInteractionService" + android:label="CTS test voice interaction service" + android:permission="android.permission.BIND_VOICE_INTERACTION" + android:process=":interactor" + android:exported="true"> + <meta-data android:name="android.voice_interaction" + android:resource="@xml/interaction_service" /> + <intent-filter> + <action android:name="android.service.voice.VoiceInteractionService" /> + </intent-filter> + </service> + <activity android:name=".DisableContextActivity" > + <intent-filter> + <action android:name="android.intent.action.START_TEST_DISABLE_CONTEXT" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + <activity android:name=".DelayedAssistantActivity" + android:label="Delay Assistant Start Activity"> + <intent-filter> + <action android:name="android.intent.action.START_TEST_ASSIST_STRUCTURE" /> + <action android:name="android.intent.action.START_TEST_LIFECYCLE" /> + <action android:name="android.intent.action.START_TEST_FLAG_SECURE" /> + <action android:name="android.intent.action.START_TEST_SCREENSHOT" /> + <action android:name="android.intent.action.START_TEST_EXTRA_ASSIST" /> + <action android:name="android.intent.action.START_TEST_TEXTVIEW" /> + <action android:name="android.intent.action.START_TEST_LARGE_VIEW_HIERARCHY" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + <service android:name=".MainInteractionSessionService" + android:permission="android.permission.BIND_VOICE_INTERACTION" + android:process=":session"> + </service> + <service android:name=".MainRecognitionService" + android:label="CTS Voice Recognition Service"> + <intent-filter> + <action android:name="android.speech.RecognitionService" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + <meta-data android:name="android.speech" android:resource="@xml/recognition_service" /> + </service> + </application> +</manifest> +
diff --git a/tests/tests/assist/service/res/layout/assist_layer.xml b/tests/tests/assist/service/res/layout/assist_layer.xml new file mode 100644 index 0000000..3677208 --- /dev/null +++ b/tests/tests/assist/service/res/layout/assist_layer.xml
@@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<RelativeLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/assist_layer" + android:layout_width="match_parent" + android:background="@color/assist_layer_background" + android:layout_height="match_parent"> + <TextView + android:layout_centerInParent="true" + android:text="@string/test_assistant_text" + android:textColor="@android:color/white" + android:layout_width="wrap_content" + android:layout_height="wrap_content"/> +</RelativeLayout>
diff --git a/tests/tests/assist/service/res/values/colors.xml b/tests/tests/assist/service/res/values/colors.xml new file mode 100644 index 0000000..4423140 --- /dev/null +++ b/tests/tests/assist/service/res/values/colors.xml
@@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="assist_layer_background">#aa000000</color> +</resources>
diff --git a/tests/tests/assist/service/res/values/strings.xml b/tests/tests/assist/service/res/values/strings.xml new file mode 100644 index 0000000..ea959e6 --- /dev/null +++ b/tests/tests/assist/service/res/values/strings.xml
@@ -0,0 +1,18 @@ +<!-- + Copyright 2015 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. --> + +<resources> + <string name="test_assistant_text">I am an Assistant</string> +</resources>
diff --git a/tests/tests/assist/service/res/xml/interaction_service.xml b/tests/tests/assist/service/res/xml/interaction_service.xml new file mode 100644 index 0000000..3ca7161 --- /dev/null +++ b/tests/tests/assist/service/res/xml/interaction_service.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android" + android:sessionService="android.assist.service.MainInteractionSessionService" + android:recognitionService="android.assist.service.MainRecognitionService" + android:settingsActivity="android.assist.service.SettingsActivity" + android:supportsAssist="true" />
diff --git a/tests/tests/assist/service/res/xml/recognition_service.xml b/tests/tests/assist/service/res/xml/recognition_service.xml new file mode 100644 index 0000000..3f763b1 --- /dev/null +++ b/tests/tests/assist/service/res/xml/recognition_service.xml
@@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2015 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. +--> + +<recognition-service xmlns:android="http://schemas.android.com/apk/res/android" + android:settingsActivity="android.assist.service.SettingsActivity" />
diff --git a/tests/tests/assist/service/src/android/voiceinteraction/service/DelayedAssistantActivity.java b/tests/tests/assist/service/src/android/voiceinteraction/service/DelayedAssistantActivity.java new file mode 100644 index 0000000..ddf43bd --- /dev/null +++ b/tests/tests/assist/service/src/android/voiceinteraction/service/DelayedAssistantActivity.java
@@ -0,0 +1,44 @@ +/* + * 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 android.assist.service; + +import android.app.Activity; +import android.assist.common.Utils; +import android.content.Intent; +import android.content.ComponentName; +import android.os.Bundle; +import android.util.Log; + +public class DelayedAssistantActivity extends Activity { + static final String TAG = "DelayedAssistantActivity"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = new Intent(); + intent.setComponent(new ComponentName(this, MainInteractionService.class)); + intent.putExtra(Utils.EXTRA_REGISTER_RECEIVER, true); + intent.putExtra(Utils.TESTCASE_TYPE, getIntent().getStringExtra(Utils.TESTCASE_TYPE)); + intent.putExtra(Utils.DISPLAY_WIDTH_KEY, + getIntent().getIntExtra(Utils.DISPLAY_WIDTH_KEY, 0)); + intent.putExtra(Utils.DISPLAY_HEIGHT_KEY, + getIntent().getIntExtra(Utils.DISPLAY_HEIGHT_KEY, 0)); + finish(); + ComponentName serviceName = startService(intent); + Log.i(TAG, "Started service: " + serviceName); + } +}
diff --git a/tests/tests/assist/service/src/android/voiceinteraction/service/DisableContextActivity.java b/tests/tests/assist/service/src/android/voiceinteraction/service/DisableContextActivity.java new file mode 100644 index 0000000..2fd540b --- /dev/null +++ b/tests/tests/assist/service/src/android/voiceinteraction/service/DisableContextActivity.java
@@ -0,0 +1,42 @@ +/* + * 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 android.assist.service; + +import android.app.Activity; +import android.content.Intent; +import android.content.ComponentName; +import android.os.Bundle; +import android.util.Log; + +public class DisableContextActivity extends Activity { + static final String TAG = "DisableContextActivity"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public void onStart() { + super.onStart(); + Intent intent = new Intent(); + intent.setComponent(new ComponentName(this, MainInteractionService.class)); + Log.i(TAG, "Starting service."); + finish(); + startService(intent); + } +}
diff --git a/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionService.java b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionService.java new file mode 100644 index 0000000..916d676 --- /dev/null +++ b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionService.java
@@ -0,0 +1,153 @@ +/* + * Copyright (C) 2015 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 android.assist.service; + +import static android.service.voice.VoiceInteractionSession.SHOW_WITH_ASSIST; +import static android.service.voice.VoiceInteractionSession.SHOW_WITH_SCREENSHOT; + +import android.assist.common.Utils; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.service.voice.VoiceInteractionService; +import android.service.voice.VoiceInteractionSession; +import android.util.Log; + +import java.lang.Exception; +import java.lang.Override; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class MainInteractionService extends VoiceInteractionService { + static final String TAG = "MainInteractionService"; + private Intent mIntent; + private boolean mReady = false; + private BroadcastReceiver mBroadcastReceiver, mResumeReceiver; + private CountDownLatch mResumeLatch; + + @Override + public void onReady() { + super.onReady(); + mReady = true; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Log.i(TAG, "onStartCommand received - intent: " + intent); + mIntent = intent; + maybeStart(); + return START_NOT_STICKY; + } + + private void maybeStart() { + if (mIntent == null || !mReady) { + Log.wtf(TAG, "Can't start session because either intent is null or onReady() " + + "has not been called yet. mIntent = " + mIntent + ", mReady = " + mReady); + } else { + if (isActiveService(this, new ComponentName(this, getClass()))) { + if (mIntent.getBooleanExtra(Utils.EXTRA_REGISTER_RECEIVER, false)) { + mResumeLatch = new CountDownLatch(1); + if (mBroadcastReceiver == null) { + mBroadcastReceiver = new MainInteractionServiceBroadcastReceiver(); + IntentFilter filter = new IntentFilter(); + filter.addAction(Utils.BROADCAST_INTENT_START_ASSIST); + registerReceiver(mBroadcastReceiver, filter); + Log.i(TAG, "Registered receiver to start session later"); + + IntentFilter resumeFilter = new IntentFilter(Utils.APP_3P_HASRESUMED); + mResumeReceiver = new MainServiceAppResumeReceiver(); + registerReceiver(mResumeReceiver, resumeFilter); + Log.i(TAG, "Registered receiver for resuming activity"); + } + sendBroadcast(new Intent(Utils.ASSIST_RECEIVER_REGISTERED)); + } else { + Log.i(TAG, "Yay! about to start session"); + Bundle bundle = new Bundle(); + bundle.putString(Utils.TESTCASE_TYPE, + mIntent.getStringExtra(Utils.TESTCASE_TYPE)); + showSession(bundle, VoiceInteractionSession.SHOW_WITH_ASSIST | + VoiceInteractionSession.SHOW_WITH_SCREENSHOT); + } + } else { + Log.wtf(TAG, "**** Not starting MainInteractionService because" + + " it is not set as the current voice interaction service"); + } + } + } + + private class MainInteractionServiceBroadcastReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + Log.i(MainInteractionService.TAG, "Recieved broadcast to start session now."); + if (intent.getAction().equals(Utils.BROADCAST_INTENT_START_ASSIST)) { + String testCaseName = intent.getStringExtra(Utils.TESTCASE_TYPE); + Log.i(MainInteractionService.TAG, "trying to start 3p activity: " + testCaseName); + Bundle extras = intent.getExtras(); + if (extras == null) { + extras = new Bundle(); + } + if (testCaseName.equals(Utils.SCREENSHOT)) { + try { + // extra info to pass along to 3p activity. + + Intent intent3p = new Intent(); + Log.i(TAG, "starting the 3p app again"); + intent3p.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent3p.setAction("android.intent.action.TEST_APP_" + testCaseName); + intent3p.setComponent(Utils.getTestAppComponent(testCaseName)); + intent3p.putExtras(extras); + startActivity(intent3p); + if (!MainInteractionService.this.mResumeLatch + .await(Utils.ACTIVITY_ONRESUME_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + Log.i(TAG, "waited for 3p activity to resume"); + } + } catch (Exception e) { + Log.i(TAG, "failed so reload 3p app: " + e.toString()); + } + } + extras.putString(Utils.TESTCASE_TYPE, mIntent.getStringExtra(Utils.TESTCASE_TYPE)); + MainInteractionService.this.showSession( + extras, SHOW_WITH_ASSIST | SHOW_WITH_SCREENSHOT); + } + } + } + + private class MainServiceAppResumeReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(Utils.APP_3P_HASRESUMED)) { + Log.i(MainInteractionService.TAG, + "3p activity has resumed in this new receiver"); + if (MainInteractionService.this.mResumeLatch != null) { + MainInteractionService.this.mResumeLatch.countDown(); + } else { + Log.i(TAG, "mResumeLatch was null"); + } + } + } + } + + @Override + public void onDestroy() { + if (mBroadcastReceiver != null) { + unregisterReceiver(mBroadcastReceiver); + } + } +} \ No newline at end of file
diff --git a/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java new file mode 100644 index 0000000..7bca9be --- /dev/null +++ b/tests/tests/assist/service/src/android/voiceinteraction/service/MainInteractionSession.java
@@ -0,0 +1,214 @@ +/* + * Copyright (C) 2015 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 spe