RuleDatabaseUpdateTask extends AsyncTask<Void, Void, Void> { void releaseGarbagePermissions() { ContentResolver contentResolver = context.getContentResolver(); for (UriPermission permission : contentResolver.getPersistedUriPermissions()) { if (isGarbage(permission.getUri())) { Log.i(TAG, "releaseGarbagePermissions: Releasing permission for " + permission.getUri()); contentResolver.releasePersistableUriPermission(permission.getUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { Log.v(TAG, "releaseGarbagePermissions: Keeping permission for " + permission.getUri()); } } } RuleDatabaseUpdateTask(Context context, Configuration configuration, boolean notifications);  static final AtomicReference<List<String>> lastErrors; }
@Test public void testReleaseGarbagePermissions() throws Exception { Context mockContext = mock(Context.class); ContentResolver mockResolver = mock(ContentResolver.class); when(mockContext.getContentResolver()).thenReturn(mockResolver); final List<UriPermission> persistedPermissions = new LinkedList<>(); when(mockResolver.getPersistedUriPermissions()).thenReturn(persistedPermissions); UriPermission usedPermission = mock(UriPermission.class); when(usedPermission.getUri()).thenReturn(newUri("content: persistedPermissions.add(usedPermission); UriPermission garbagePermission = mock(UriPermission.class); when(garbagePermission.getUri()).thenReturn(newUri("content: persistedPermissions.add(garbagePermission); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Iterator<UriPermission> iter = persistedPermissions.iterator(); while (iter.hasNext()) { UriPermission perm = iter.next(); if (perm.getUri() == invocation.getArgumentAt(0, Uri.class)) iter.remove(); } return null; } }).when(mockResolver, "releasePersistableUriPermission", any(Uri.class), anyInt()); Configuration configuration = new Configuration(); configuration.hosts.items.add(newItemForLocation("content: assertTrue(persistedPermissions.contains(usedPermission)); assertTrue(persistedPermissions.contains(garbagePermission)); new RuleDatabaseUpdateTask(mockContext, configuration, false).releaseGarbagePermissions(); assertTrue(persistedPermissions.contains(usedPermission)); assertFalse(persistedPermissions.contains(garbagePermission)); }