Reset MANAGE_EXTERNAL_STORAGE between tests

Open
#1,658 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
java

Research direction

Start with the provided toggleAllFilesAccess() instrumentation helper and reproduce the MANAGE_EXTERNAL_STORAGE change while the app is in the Settings screen. Investigate how the Android instrumentation test and UiAutomator session behave after the app is killed; done means tests can revoke or reset the permission and return to the test activity reliably.

Written by the indexing model from the issue text.

Description

I have setup my Android instrumentationTest so that all data is cleared between each test thanks to testInstrumentationRunnerArguments clearPackageData: 'true'

This works fine except for the "All files access" that remains in the state of the last test.

I can grant "all files access" through UiAutomator from within the app.

But I can't revoke it because when I'm in the "All files access" window, logcat reports that my app was killed because "MANAGE_EXTERNAL_STORAGE" changed. So the myDevice.pressBack() to revert to my activity is innefective: nothing happens, I'm staying on that window without leaving it.

log
system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.
log context
24511-24533/<my.app>.debug I/QueryController: Matched selector: UiSelector[TEXT_REGEX=(?i)Allow access to manage all files] <<==>> [android.view.accessibility.AccessibilityNodeInfo@13b0b; boundsInParent: Rect(0, 0 - 753, 71); boundsInScreen: Rect(63, 954 - 816, 1025); packageName: com.android.settings; className: android.widget.TextView; text: Allow access to manage all files; error: null; maxTextLength: -1; stateDescription: null; contentDescription: null; tooltipText: null; viewIdResName: android:id/title; checkable: false; checked: false; focusable: false; focused: false; selected: false; clickable: false; longClickable: false; contextClickable: false; enabled: true; password: false; scrollable: false; importantForAccessibility: true; visible: true; actions: [AccessibilityAction: ACTION_SELECT - null, AccessibilityAction: ACTION_CLEAR_SELECTION - null, AccessibilityAction: ACTION_ACCESSIBILITY_FOCUS - null, AccessibilityAction: ACTION_NEXT_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY - null, AccessibilityAction: ACTION_SET_SELECTION - null, AccessibilityAction: ACTION_SHOW_ON_SCREEN - null]]
24511-24533/<my.app>.debug D/InteractionController: clickAndSync(439, 989)
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166666, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-606474784 }
1227-1227/com.google.android.apps.nexuslauncher D/TaplEvents: TIS / TouchInteractionService.onInputEvent: MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=439.0, y[0]=989.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=19166784, downTime=19166666, deviceId=-1, source=0x1002, displayId=0, eventId=-468631845 }
1680-8178/com.google.android.providers.media.module I/MediaProvider: Invalidating LocalCallingIdentity cache for package <my.app>.debug. Reason: op android:read_external_storage
351-538/? E/android.hardware.audio@7.0-impl.ranchu: device/generic/goldfish/audio/stream_out.cpp:updateSourceMetadata:377 failure: Result::NOT_SUPPORTED
607-3275/system_process I/ActivityManager: Killing 24511:<my.app>.debug/u0a162 (adj 0): MANAGE_EXTERNAL_STORAGE changed.
607-3275/system_process W/ActivityManager: Crash of app <my.app>.debug running instrumentation ComponentInfo{<my.app>.debug.test/androidx.test.runner.AndroidJUnitRunner}
607-3275/system_process I/ActivityManager: Force stopping <my.app>.debug appid=10162 user=0: finished inst
607-3275/system_process I/WindowManager:   Force removing ActivityRecord{27550bc u0 <my.app>.debug/<my.app>.MainActivity t123}
607-3275/system_process W/InputManager-JNI: Input channel object '10c60ec <my.app>.debug/<my.app>.MainActivity (client)' was disposed without first being removed with the input manager!
607-659/system_process I/libprocessgroup: Successfully killed process cgroup uid 10162 pid 24511 in 5ms
607-649/system_process D/ContentCapturePerUserService: onActivityEvent(): no remote service
1545-1545/com.google.android.inputmethod.latin I/AppBase: AppBase.onTrimMemory():738 onTrimMemory(): 5
1545-1545/com.google.android.inputmethod.latin I/GoogleInputMethodService: GoogleInputMethodService.onTrimMemory():4463 onTrimMemory(): 5
23224-23251/com.google.android.apps.messaging W/Bugle: TextClassifierLibManagerImpl: Reclaiming memory at level: 80
607-656/system_process W/UsageStatsService: Unexpected activity event reported! (<my.app>.debug/<my.app>.MainActivity event : 23 instanceId : 96015535)
24497-24497/? D/AndroidRuntime: Shutting down VM
24555-24585/? D/EGL_emulation: app_time_stats: avg=147.68ms min=4.52ms max=627.87ms count=10
349-349/? I/Zygote: Process 24511 exited due to signal 9 (Killed)
24497-24510/? W/Binder: Caught a RuntimeException from the binder stub implementation.
    java.lang.SecurityException: Calling from not trusted UID!
        at android.app.UiAutomationConnection.throwIfCalledByNotTrustedUidLocked(UiAutomationConnection.java:601)
        at android.app.UiAutomationConnection.shutdown(UiAutomationConnection.java:505)
        at android.app.IUiAutomationConnection$Stub.onTransact(IUiAutomationConnection.java:437)
        at android.os.Binder.execTransactInternal(Binder.java:1184)
        at android.os.Binder.execTransact(Binder.java:1143)
607-649/system_process W/ActivityManager: setHasOverlayUi called on unknown pid: 24511
607-1541/system_process V/ActivityManager: Got obituary of 24511:<my.app>.debug
Code to toggle from within my app.
    public static void toggleAllFilesAccess() throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
                ! Environment.isExternalStorageManager() &&
                ! Environment.isExternalStorageLegacy()) {

            UiDevice device = UiDevice.getInstance(getInstrumentation());

            Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
            String permit_manage_external_storage = new String();
            int resId;

            PackageManager manager = context.getPackageManager();

            // Identifier names are taken here:
            // https://cs.android.com/android/platform/superproject/+/master:packages/apps/Settings/res/values/strings.xml
            Resources resources = manager.getResourcesForApplication("com.android.settings");
            resId = resources.getIdentifier("permit_manage_external_storage", "string", "com.android.settings");
            permit_manage_external_storage = resources.getString(resId);

            onView(withText(R.string.pref_allFilesAccess_title)).perform(click());

            UiObject uiElement2 = device.findObject(new UiSelector().textMatches("(?i)" + permit_manage_external_storage));
            uiElement2.click();
            device.pressBack();
        }
    }

Any suggestion on how to achieve this?

Dominant language
Java
Stars
1.2k
Forks
342
Avg merge
1d 14h
Merged PRs (30d)
5

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from android/android-test

All issues in android/android-test

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.