1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.content.cts; 18 19 import static android.Manifest.permission.READ_WALLPAPER_INTERNAL; 20 import static android.content.pm.PackageManager.PERMISSION_DENIED; 21 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 22 23 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; 24 25 import android.app.Activity; 26 import android.app.AppOpsManager; 27 import android.app.BroadcastOptions; 28 import android.app.Instrumentation; 29 import android.app.WallpaperManager; 30 import android.content.ActivityNotFoundException; 31 import android.content.AttributionSource; 32 import android.content.BroadcastReceiver; 33 import android.content.ComponentName; 34 import android.content.Context; 35 import android.content.ContextParams; 36 import android.content.Intent; 37 import android.content.IntentFilter; 38 import android.content.ServiceConnection; 39 import android.content.SharedPreferences; 40 import android.content.pm.PackageManager; 41 import android.content.res.ColorStateList; 42 import android.content.res.Resources.NotFoundException; 43 import android.content.res.Resources.Theme; 44 import android.content.res.TypedArray; 45 import android.content.res.XmlResourceParser; 46 import android.database.Cursor; 47 import android.database.sqlite.SQLiteCursorDriver; 48 import android.database.sqlite.SQLiteDatabase; 49 import android.database.sqlite.SQLiteQuery; 50 import android.graphics.Bitmap; 51 import android.graphics.drawable.BitmapDrawable; 52 import android.graphics.drawable.Drawable; 53 import android.net.Uri; 54 import android.net.wifi.WifiManager; 55 import android.os.Binder; 56 import android.os.Bundle; 57 import android.os.Handler; 58 import android.os.IBinder; 59 import android.os.Looper; 60 import android.os.Process; 61 import android.os.UserHandle; 62 import android.platform.test.annotations.AppModeFull; 63 import android.preference.PreferenceManager; 64 import android.test.AndroidTestCase; 65 import android.util.AttributeSet; 66 import android.util.Log; 67 import android.util.Xml; 68 import android.view.WindowManager; 69 70 import com.android.compatibility.common.util.PollingCheck; 71 import com.android.compatibility.common.util.ShellIdentityUtils; 72 import com.android.compatibility.common.util.SystemUtil; 73 import com.android.cts.IBinderPermissionTestService; 74 75 import junit.framework.Assert; 76 77 import org.xmlpull.v1.XmlPullParser; 78 import org.xmlpull.v1.XmlPullParserException; 79 80 import java.io.File; 81 import java.io.FileOutputStream; 82 import java.io.IOException; 83 import java.io.InputStream; 84 import java.util.ArrayList; 85 import java.util.Arrays; 86 import java.util.List; 87 88 @AppModeFull // TODO(Instant) Figure out which APIs should work. 89 public class ContextTest extends AndroidTestCase { 90 private static final String TAG = "ContextTest"; 91 private static final String ACTUAL_RESULT = "ResultSetByReceiver"; 92 93 private static final String INTIAL_RESULT = "IntialResult"; 94 95 private static final String VALUE_ADDED = "ValueAdded"; 96 private static final String KEY_ADDED = "AddedByReceiver"; 97 98 private static final String VALUE_REMOVED = "ValueWillBeRemove"; 99 private static final String KEY_REMOVED = "ToBeRemoved"; 100 101 private static final String VALUE_KEPT = "ValueKept"; 102 private static final String KEY_KEPT = "ToBeKept"; 103 104 private static final String MOCK_STICKY_ACTION = "android.content.cts.ContextTest." 105 + "STICKY_BROADCAST_RESULT"; 106 107 private static final String ACTION_BROADCAST_TESTORDER = 108 "android.content.cts.ContextTest.BROADCAST_TESTORDER"; 109 private final static String MOCK_ACTION1 = ACTION_BROADCAST_TESTORDER + "1"; 110 private final static String MOCK_ACTION2 = ACTION_BROADCAST_TESTORDER + "2"; 111 112 // Note: keep these constants in sync with the permissions used by BinderPermissionTestService. 113 // 114 // A permission that's granted to this test package. 115 public static final String GRANTED_PERMISSION = "android.permission.USE_CREDENTIALS"; 116 // A permission that's not granted to this test package. 117 public static final String NOT_GRANTED_PERMISSION = "android.permission.HARDWARE_TEST"; 118 119 private static final int BROADCAST_TIMEOUT = 10000; 120 private static final int ROOT_UID = 0; 121 122 /** 123 * Shell command to broadcast {@link ResultReceiver#MOCK_ACTION} as an external app. 124 */ 125 private static final String EXTERNAL_APP_BROADCAST_COMMAND = 126 "am broadcast -a " + ResultReceiver.MOCK_ACTION + " -f " 127 + Intent.FLAG_RECEIVER_FOREGROUND; 128 129 private Object mLockObj; 130 131 private ArrayList<BroadcastReceiver> mRegisteredReceiverList; 132 133 private boolean mWallpaperChanged; 134 private BitmapDrawable mOriginalWallpaper = null; 135 private volatile IBinderPermissionTestService mBinderPermissionTestService; 136 private ServiceConnection mBinderPermissionTestConnection; 137 138 protected Context mContext; 139 140 /** 141 * Returns the Context object that's being tested. 142 */ getContextUnderTest()143 protected Context getContextUnderTest() { 144 return getContext(); 145 } 146 147 @Override setUp()148 protected void setUp() throws Exception { 149 super.setUp(); 150 mContext = getContextUnderTest(); 151 mContext.setTheme(R.style.Test_Theme); 152 153 mLockObj = new Object(); 154 155 mRegisteredReceiverList = new ArrayList<BroadcastReceiver>(); 156 } 157 158 @Override tearDown()159 protected void tearDown() throws Exception { 160 if (mOriginalWallpaper != null && mWallpaperChanged) { 161 mContext.setWallpaper(mOriginalWallpaper.getBitmap()); 162 } 163 164 for (BroadcastReceiver receiver : mRegisteredReceiverList) { 165 mContext.unregisterReceiver(receiver); 166 } 167 168 super.tearDown(); 169 } 170 testGetString()171 public void testGetString() { 172 String testString = mContext.getString(R.string.context_test_string1); 173 assertEquals("This is %s string.", testString); 174 175 testString = mContext.getString(R.string.context_test_string1, "expected"); 176 assertEquals("This is expected string.", testString); 177 178 testString = mContext.getString(R.string.context_test_string2); 179 assertEquals("This is test string.", testString); 180 181 // Test wrong resource id 182 try { 183 testString = mContext.getString(0, "expected"); 184 fail("Wrong resource id should not be accepted."); 185 } catch (NotFoundException e) { 186 } 187 188 // Test wrong resource id 189 try { 190 testString = mContext.getString(0); 191 fail("Wrong resource id should not be accepted."); 192 } catch (NotFoundException e) { 193 } 194 } 195 testGetText()196 public void testGetText() { 197 CharSequence testCharSequence = mContext.getText(R.string.context_test_string2); 198 assertEquals("This is test string.", testCharSequence.toString()); 199 200 // Test wrong resource id 201 try { 202 testCharSequence = mContext.getText(0); 203 fail("Wrong resource id should not be accepted."); 204 } catch (NotFoundException e) { 205 } 206 } 207 testCreateAttributionContext()208 public void testCreateAttributionContext() throws Exception { 209 final String tag = "testCreateAttributionContext"; 210 final Context attrib = mContext.createAttributionContext(tag); 211 assertEquals(tag, attrib.getAttributionTag()); 212 assertEquals(null, mContext.getAttributionTag()); 213 } 214 testCreateAttributionContextFromParams()215 public void testCreateAttributionContextFromParams() throws Exception { 216 final ContextParams params = new ContextParams.Builder() 217 .setAttributionTag("foo") 218 .setNextAttributionSource(new AttributionSource.Builder(1) 219 .setPackageName("bar") 220 .setAttributionTag("baz") 221 .build()) 222 .build(); 223 final Context attributionContext = getContext().createContext(params); 224 225 assertEquals(params, attributionContext.getParams()); 226 assertEquals(params.getNextAttributionSource(), 227 attributionContext.getAttributionSource().getNext()); 228 assertEquals(params.getAttributionTag(), 229 attributionContext.getAttributionSource().getAttributionTag()); 230 } 231 testContextParams()232 public void testContextParams() throws Exception { 233 final ContextParams params = new ContextParams.Builder() 234 .setAttributionTag("foo") 235 .setNextAttributionSource(new AttributionSource.Builder(1) 236 .setPackageName("bar") 237 .setAttributionTag("baz") 238 .build()) 239 .build(); 240 241 assertEquals("foo", params.getAttributionTag()); 242 assertEquals(1, params.getNextAttributionSource().getUid()); 243 assertEquals("bar", params.getNextAttributionSource().getPackageName()); 244 assertEquals("baz", params.getNextAttributionSource().getAttributionTag()); 245 } 246 testAttributionSourceSetNext()247 public void testAttributionSourceSetNext() throws Exception { 248 final AttributionSource next = new AttributionSource.Builder(2) 249 .setPackageName("nextBar") 250 .setAttributionTag("nextBaz") 251 .build(); 252 final ContextParams params = new ContextParams.Builder() 253 .setAttributionTag("foo") 254 .setNextAttributionSource(new AttributionSource.Builder(1) 255 .setPackageName("bar") 256 .setAttributionTag("baz") 257 .setNext(next) 258 .build()) 259 .build(); 260 261 // Setting a 'next' should not affect prev. 262 assertEquals("foo", params.getAttributionTag()); 263 assertEquals(1, params.getNextAttributionSource().getUid()); 264 assertEquals("bar", params.getNextAttributionSource().getPackageName()); 265 assertEquals("baz", params.getNextAttributionSource().getAttributionTag()); 266 267 final AttributionSource check = 268 params.getNextAttributionSource().getNext(); 269 assertEquals(2, check.getUid()); 270 assertEquals("nextBar", check.getPackageName()); 271 assertEquals("nextBaz", check.getAttributionTag()); 272 } 273 testContextParams_Inherit()274 public void testContextParams_Inherit() throws Exception { 275 final ContextParams orig = new ContextParams.Builder() 276 .setAttributionTag("foo").build(); 277 { 278 final ContextParams params = new ContextParams.Builder(orig).build(); 279 assertEquals("foo", params.getAttributionTag()); 280 } 281 { 282 final ContextParams params = new ContextParams.Builder(orig) 283 .setAttributionTag("bar").build(); 284 assertEquals("bar", params.getAttributionTag()); 285 } 286 { 287 final ContextParams params = new ContextParams.Builder(orig) 288 .setAttributionTag(null).build(); 289 assertEquals(null, params.getAttributionTag()); 290 } 291 } 292 293 /** 294 * Ensure that default and device encrypted storage areas are stored 295 * separately on disk. All devices must support these storage areas, even if 296 * they don't have file-based encryption, so that apps can go through a 297 * backup/restore cycle between FBE and non-FBE devices. 298 */ testCreateDeviceProtectedStorageContext()299 public void testCreateDeviceProtectedStorageContext() throws Exception { 300 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 301 302 assertFalse(mContext.isDeviceProtectedStorage()); 303 assertTrue(deviceContext.isDeviceProtectedStorage()); 304 305 final File defaultFile = new File(mContext.getFilesDir(), "test"); 306 final File deviceFile = new File(deviceContext.getFilesDir(), "test"); 307 308 assertFalse(deviceFile.equals(defaultFile)); 309 310 deviceFile.createNewFile(); 311 312 // Make sure storage areas are mutually exclusive 313 assertFalse(defaultFile.exists()); 314 assertTrue(deviceFile.exists()); 315 } 316 testMoveSharedPreferencesFrom()317 public void testMoveSharedPreferencesFrom() throws Exception { 318 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 319 320 mContext.getSharedPreferences("test", Context.MODE_PRIVATE).edit().putInt("answer", 42) 321 .commit(); 322 323 // Verify that we can migrate 324 assertTrue(deviceContext.moveSharedPreferencesFrom(mContext, "test")); 325 assertEquals(0, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 326 .getInt("answer", 0)); 327 assertEquals(42, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 328 .getInt("answer", 0)); 329 330 // Trying to migrate again when already done is a no-op 331 assertTrue(deviceContext.moveSharedPreferencesFrom(mContext, "test")); 332 assertEquals(0, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 333 .getInt("answer", 0)); 334 assertEquals(42, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 335 .getInt("answer", 0)); 336 337 // Add a new value and verify that we can migrate back 338 deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE).edit() 339 .putInt("question", 24).commit(); 340 341 assertTrue(mContext.moveSharedPreferencesFrom(deviceContext, "test")); 342 assertEquals(42, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 343 .getInt("answer", 0)); 344 assertEquals(24, mContext.getSharedPreferences("test", Context.MODE_PRIVATE) 345 .getInt("question", 0)); 346 assertEquals(0, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 347 .getInt("answer", 0)); 348 assertEquals(0, deviceContext.getSharedPreferences("test", Context.MODE_PRIVATE) 349 .getInt("question", 0)); 350 } 351 testMoveDatabaseFrom()352 public void testMoveDatabaseFrom() throws Exception { 353 final Context deviceContext = mContext.createDeviceProtectedStorageContext(); 354 355 SQLiteDatabase db = mContext.openOrCreateDatabase("test.db", 356 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 357 db.execSQL("CREATE TABLE list(item TEXT);"); 358 db.execSQL("INSERT INTO list VALUES ('cat')"); 359 db.execSQL("INSERT INTO list VALUES ('dog')"); 360 db.close(); 361 362 // Verify that we can migrate 363 assertTrue(deviceContext.moveDatabaseFrom(mContext, "test.db")); 364 db = deviceContext.openOrCreateDatabase("test.db", 365 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 366 Cursor c = db.query("list", null, null, null, null, null, null); 367 assertEquals(2, c.getCount()); 368 assertTrue(c.moveToFirst()); 369 assertEquals("cat", c.getString(0)); 370 assertTrue(c.moveToNext()); 371 assertEquals("dog", c.getString(0)); 372 c.close(); 373 db.execSQL("INSERT INTO list VALUES ('mouse')"); 374 db.close(); 375 376 // Trying to migrate again when already done is a no-op 377 assertTrue(deviceContext.moveDatabaseFrom(mContext, "test.db")); 378 379 // Verify that we can migrate back 380 assertTrue(mContext.moveDatabaseFrom(deviceContext, "test.db")); 381 db = mContext.openOrCreateDatabase("test.db", 382 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null); 383 c = db.query("list", null, null, null, null, null, null); 384 assertEquals(3, c.getCount()); 385 assertTrue(c.moveToFirst()); 386 assertEquals("cat", c.getString(0)); 387 assertTrue(c.moveToNext()); 388 assertEquals("dog", c.getString(0)); 389 assertTrue(c.moveToNext()); 390 assertEquals("mouse", c.getString(0)); 391 c.close(); 392 db.close(); 393 } 394 testAccessTheme()395 public void testAccessTheme() { 396 mContext.setTheme(R.style.Test_Theme); 397 final Theme testTheme = mContext.getTheme(); 398 assertNotNull(testTheme); 399 400 int[] attrs = { 401 android.R.attr.windowNoTitle, 402 android.R.attr.panelColorForeground, 403 android.R.attr.panelColorBackground 404 }; 405 TypedArray attrArray = null; 406 try { 407 attrArray = testTheme.obtainStyledAttributes(attrs); 408 assertTrue(attrArray.getBoolean(0, false)); 409 assertEquals(0xff000000, attrArray.getColor(1, 0)); 410 assertEquals(0xffffffff, attrArray.getColor(2, 0)); 411 } finally { 412 if (attrArray != null) { 413 attrArray.recycle(); 414 attrArray = null; 415 } 416 } 417 418 // setTheme only works for the first time 419 mContext.setTheme(android.R.style.Theme_Black); 420 assertSame(testTheme, mContext.getTheme()); 421 } 422 testObtainStyledAttributes()423 public void testObtainStyledAttributes() { 424 // Test obtainStyledAttributes(int[]) 425 TypedArray testTypedArray = mContext 426 .obtainStyledAttributes(android.R.styleable.View); 427 assertNotNull(testTypedArray); 428 assertTrue(testTypedArray.length() > 2); 429 assertTrue(testTypedArray.length() > 0); 430 testTypedArray.recycle(); 431 432 // Test obtainStyledAttributes(int, int[]) 433 testTypedArray = mContext.obtainStyledAttributes(android.R.style.TextAppearance_Small, 434 android.R.styleable.TextAppearance); 435 assertNotNull(testTypedArray); 436 assertTrue(testTypedArray.length() > 2); 437 testTypedArray.recycle(); 438 439 // Test wrong null array pointer 440 try { 441 testTypedArray = mContext.obtainStyledAttributes(-1, null); 442 fail("obtainStyledAttributes will throw a NullPointerException here."); 443 } catch (NullPointerException e) { 444 } 445 446 // Test obtainStyledAttributes(AttributeSet, int[]) with unavailable resource id. 447 int testInt[] = { 0, 0 }; 448 testTypedArray = mContext.obtainStyledAttributes(-1, testInt); 449 // fail("Wrong resource id should not be accepted."); 450 assertNotNull(testTypedArray); 451 assertEquals(2, testTypedArray.length()); 452 testTypedArray.recycle(); 453 454 // Test obtainStyledAttributes(AttributeSet, int[]) 455 int[] attrs = android.R.styleable.DatePicker; 456 testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout), 457 attrs); 458 assertNotNull(testTypedArray); 459 assertEquals(attrs.length, testTypedArray.length()); 460 testTypedArray.recycle(); 461 462 // Test obtainStyledAttributes(AttributeSet, int[], int, int) 463 testTypedArray = mContext.obtainStyledAttributes(getAttributeSet(R.layout.context_layout), 464 attrs, 0, 0); 465 assertNotNull(testTypedArray); 466 assertEquals(attrs.length, testTypedArray.length()); 467 testTypedArray.recycle(); 468 } 469 testGetSystemService()470 public void testGetSystemService() { 471 // Test invalid service name 472 assertNull(mContext.getSystemService("invalid")); 473 474 // Test valid service name 475 assertNotNull(mContext.getSystemService(Context.WINDOW_SERVICE)); 476 } 477 testGetSystemServiceByClass()478 public void testGetSystemServiceByClass() { 479 // Test invalid service class 480 assertNull(mContext.getSystemService(Object.class)); 481 482 // Test valid service name 483 assertNotNull(mContext.getSystemService(WindowManager.class)); 484 assertEquals(mContext.getSystemService(Context.WINDOW_SERVICE), 485 mContext.getSystemService(WindowManager.class)); 486 } 487 testGetColorStateList()488 public void testGetColorStateList() { 489 try { 490 mContext.getColorStateList(0); 491 fail("Failed at testGetColorStateList"); 492 } catch (NotFoundException e) { 493 //expected 494 } 495 496 final ColorStateList colorStateList = mContext.getColorStateList(R.color.color2); 497 final int[] focusedState = {android.R.attr.state_focused}; 498 final int focusColor = colorStateList.getColorForState(focusedState, R.color.failColor); 499 assertEquals(0xffff0000, focusColor); 500 } 501 testGetColor()502 public void testGetColor() { 503 try { 504 mContext.getColor(0); 505 fail("Failed at testGetColor"); 506 } catch (NotFoundException e) { 507 //expected 508 } 509 510 final int color = mContext.getColor(R.color.color2); 511 assertEquals(0xffffff00, color); 512 } 513 514 /** 515 * Developers have come to expect at least ext4-style filename behavior, so 516 * verify that the underlying filesystem supports them. 517 */ testFilenames()518 public void testFilenames() throws Exception { 519 final File base = mContext.getFilesDir(); 520 assertValidFile(new File(base, "foo")); 521 assertValidFile(new File(base, ".bar")); 522 assertValidFile(new File(base, "foo.bar")); 523 assertValidFile(new File(base, "\u2603")); 524 assertValidFile(new File(base, "\uD83D\uDCA9")); 525 526 final int pid = android.os.Process.myPid(); 527 final StringBuilder sb = new StringBuilder(255); 528 while (sb.length() <= 255) { 529 sb.append(pid); 530 sb.append(mContext.getPackageName()); 531 } 532 sb.setLength(255); 533 534 final String longName = sb.toString(); 535 final File longDir = new File(base, longName); 536 assertValidFile(longDir); 537 longDir.mkdir(); 538 final File longFile = new File(longDir, longName); 539 assertValidFile(longFile); 540 } 541 testMainLooper()542 public void testMainLooper() throws Exception { 543 final Thread mainThread = Looper.getMainLooper().getThread(); 544 final Handler handler = new Handler(mContext.getMainLooper()); 545 handler.post(() -> { 546 assertEquals(mainThread, Thread.currentThread()); 547 }); 548 } 549 testMainExecutor()550 public void testMainExecutor() throws Exception { 551 final Thread mainThread = Looper.getMainLooper().getThread(); 552 mContext.getMainExecutor().execute(() -> { 553 assertEquals(mainThread, Thread.currentThread()); 554 }); 555 } 556 assertValidFile(File file)557 private void assertValidFile(File file) throws Exception { 558 Log.d(TAG, "Checking " + file); 559 if (file.exists()) { 560 assertTrue("File already exists and couldn't be deleted before test: " + file, 561 file.delete()); 562 } 563 assertTrue("Failed to create " + file, file.createNewFile()); 564 assertTrue("Doesn't exist after create " + file, file.exists()); 565 assertTrue("Failed to delete after create " + file, file.delete()); 566 new FileOutputStream(file).close(); 567 assertTrue("Doesn't exist after stream " + file, file.exists()); 568 assertTrue("Failed to delete after stream " + file, file.delete()); 569 } 570 beginDocument(XmlPullParser parser, String firstElementName)571 static void beginDocument(XmlPullParser parser, String firstElementName) 572 throws XmlPullParserException, IOException 573 { 574 int type; 575 while ((type=parser.next()) != parser.START_TAG 576 && type != parser.END_DOCUMENT) { 577 ; 578 } 579 580 if (type != parser.START_TAG) { 581 throw new XmlPullParserException("No start tag found"); 582 } 583 584 if (!parser.getName().equals(firstElementName)) { 585 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() + 586 ", expected " + firstElementName); 587 } 588 } 589 getAttributeSet(int resourceId)590 private AttributeSet getAttributeSet(int resourceId) { 591 final XmlResourceParser parser = mContext.getResources().getXml( 592 resourceId); 593 594 try { 595 beginDocument(parser, "RelativeLayout"); 596 } catch (XmlPullParserException e) { 597 e.printStackTrace(); 598 } catch (IOException e) { 599 e.printStackTrace(); 600 } 601 602 final AttributeSet attr = Xml.asAttributeSet(parser); 603 assertNotNull(attr); 604 return attr; 605 } 606 registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter)607 private void registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter) { 608 registerBroadcastReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED); 609 } 610 registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags)611 private void registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter, 612 int flags) { 613 mContext.registerReceiver(receiver, filter, flags); 614 615 mRegisteredReceiverList.add(receiver); 616 } 617 testSendOrderedBroadcast1()618 public void testSendOrderedBroadcast1() throws InterruptedException { 619 final HighPriorityBroadcastReceiver highPriorityReceiver = 620 new HighPriorityBroadcastReceiver(); 621 final LowPriorityBroadcastReceiver lowPriorityReceiver = 622 new LowPriorityBroadcastReceiver(); 623 624 final IntentFilter filterHighPriority = new IntentFilter(ResultReceiver.MOCK_ACTION); 625 filterHighPriority.setPriority(1); 626 final IntentFilter filterLowPriority = new IntentFilter(ResultReceiver.MOCK_ACTION); 627 registerBroadcastReceiver(highPriorityReceiver, filterHighPriority); 628 registerBroadcastReceiver(lowPriorityReceiver, filterLowPriority); 629 630 final Intent broadcastIntent = new Intent(ResultReceiver.MOCK_ACTION) 631 .setPackage(mContext.getPackageName()); 632 broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 633 mContext.sendOrderedBroadcast(broadcastIntent, null); 634 new PollingCheck(BROADCAST_TIMEOUT) { 635 @Override 636 protected boolean check() { 637 return highPriorityReceiver.hasReceivedBroadCast() 638 && !lowPriorityReceiver.hasReceivedBroadCast(); 639 } 640 }.run(); 641 642 synchronized (highPriorityReceiver) { 643 highPriorityReceiver.notify(); 644 } 645 646 new PollingCheck(BROADCAST_TIMEOUT) { 647 @Override 648 protected boolean check() { 649 return highPriorityReceiver.hasReceivedBroadCast() 650 && lowPriorityReceiver.hasReceivedBroadCast(); 651 } 652 }.run(); 653 } 654 testSendOrderedBroadcast2()655 public void testSendOrderedBroadcast2() throws InterruptedException { 656 final TestBroadcastReceiver broadcastReceiver = new TestBroadcastReceiver(); 657 broadcastReceiver.mIsOrderedBroadcasts = true; 658 659 Bundle bundle = new Bundle(); 660 bundle.putString(KEY_KEPT, VALUE_KEPT); 661 bundle.putString(KEY_REMOVED, VALUE_REMOVED); 662 Intent intent = new Intent(ResultReceiver.MOCK_ACTION) 663 .setPackage(mContext.getPackageName()); 664 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 665 mContext.sendOrderedBroadcast(intent, null, broadcastReceiver, null, 1, 666 INTIAL_RESULT, bundle); 667 668 synchronized (mLockObj) { 669 try { 670 mLockObj.wait(BROADCAST_TIMEOUT); 671 } catch (InterruptedException e) { 672 fail("unexpected InterruptedException."); 673 } 674 } 675 676 assertTrue("Receiver didn't make any response.", broadcastReceiver.hadReceivedBroadCast()); 677 assertEquals("Incorrect code: " + broadcastReceiver.getResultCode(), 3, 678 broadcastReceiver.getResultCode()); 679 assertEquals(ACTUAL_RESULT, broadcastReceiver.getResultData()); 680 Bundle resultExtras = broadcastReceiver.getResultExtras(false); 681 assertEquals(VALUE_ADDED, resultExtras.getString(KEY_ADDED)); 682 assertEquals(VALUE_KEPT, resultExtras.getString(KEY_KEPT)); 683 assertNull(resultExtras.getString(KEY_REMOVED)); 684 } 685 testSendOrderedBroadcastWithAppOp()686 public void testSendOrderedBroadcastWithAppOp() { 687 // we use a HighPriorityBroadcastReceiver because the final receiver should get the 688 // broadcast only at the end. 689 final ResultReceiver receiver = new HighPriorityBroadcastReceiver(); 690 final ResultReceiver finalReceiver = new ResultReceiver(); 691 692 AppOpsManager aom = 693 (AppOpsManager) getContextUnderTest().getSystemService(Context.APP_OPS_SERVICE); 694 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(aom, 695 (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 696 Process.myUid(), AppOpsManager.MODE_ALLOWED)); 697 698 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 699 700 mContext.sendOrderedBroadcast( 701 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 702 null, // permission 703 AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 704 finalReceiver, 705 null, // scheduler 706 0, // initial code 707 null, //initial data 708 null); // initial extras 709 710 new PollingCheck(BROADCAST_TIMEOUT){ 711 @Override 712 protected boolean check() { 713 return receiver.hasReceivedBroadCast() 714 && !finalReceiver.hasReceivedBroadCast(); 715 } 716 }.run(); 717 718 synchronized (receiver) { 719 receiver.notify(); 720 } 721 722 new PollingCheck(BROADCAST_TIMEOUT){ 723 @Override 724 protected boolean check() { 725 // ensure that first receiver has received broadcast before final receiver 726 return receiver.hasReceivedBroadCast() 727 && finalReceiver.hasReceivedBroadCast(); 728 } 729 }.run(); 730 } 731 testSendOrderedBroadcastWithAppOp_NotGranted()732 public void testSendOrderedBroadcastWithAppOp_NotGranted() { 733 final ResultReceiver receiver = new ResultReceiver(); 734 735 AppOpsManager aom = 736 (AppOpsManager) getContextUnderTest().getSystemService(Context.APP_OPS_SERVICE); 737 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(aom, 738 (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 739 Process.myUid(), AppOpsManager.MODE_ERRORED)); 740 741 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 742 743 mContext.sendOrderedBroadcast( 744 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 745 null, // permission 746 AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 747 null, // final receiver 748 null, // scheduler 749 0, // initial code 750 null, //initial data 751 null); // initial extras 752 753 boolean broadcastNeverSent = false; 754 try { 755 new PollingCheck(BROADCAST_TIMEOUT) { 756 @Override 757 protected boolean check() { 758 return receiver.hasReceivedBroadCast(); 759 } 760 761 public void runWithInterruption() throws InterruptedException { 762 if (check()) { 763 return; 764 } 765 766 long timeout = BROADCAST_TIMEOUT; 767 while (timeout > 0) { 768 try { 769 Thread.sleep(50 /* time slice */); 770 } catch (InterruptedException e) { 771 fail("unexpected InterruptedException"); 772 } 773 774 if (check()) { 775 return; 776 } 777 778 timeout -= 50; // time slice 779 } 780 throw new InterruptedException(); 781 } 782 }.runWithInterruption(); 783 } catch (InterruptedException e) { 784 broadcastNeverSent = true; 785 } 786 787 assertTrue(broadcastNeverSent); 788 } 789 testRegisterReceiver1()790 public void testRegisterReceiver1() throws InterruptedException { 791 final FilteredReceiver broadcastReceiver = new FilteredReceiver(); 792 final IntentFilter filter = new IntentFilter(MOCK_ACTION1); 793 794 // Test registerReceiver 795 mContext.registerReceiver(broadcastReceiver, filter, Context.RECEIVER_EXPORTED_UNAUDITED); 796 797 // Test unwanted intent(action = MOCK_ACTION2) 798 broadcastReceiver.reset(); 799 waitForFilteredIntent(mContext, MOCK_ACTION2); 800 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 801 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 802 803 // Send wanted intent(action = MOCK_ACTION1) 804 broadcastReceiver.reset(); 805 waitForFilteredIntent(mContext, MOCK_ACTION1); 806 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 807 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 808 809 mContext.unregisterReceiver(broadcastReceiver); 810 811 // Test unregisterReceiver 812 FilteredReceiver broadcastReceiver2 = new FilteredReceiver(); 813 mContext.registerReceiver(broadcastReceiver2, filter, Context.RECEIVER_EXPORTED_UNAUDITED); 814 mContext.unregisterReceiver(broadcastReceiver2); 815 816 // Test unwanted intent(action = MOCK_ACTION2) 817 broadcastReceiver2.reset(); 818 waitForFilteredIntent(mContext, MOCK_ACTION2); 819 assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); 820 assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); 821 822 // Send wanted intent(action = MOCK_ACTION1), but the receiver is unregistered. 823 broadcastReceiver2.reset(); 824 waitForFilteredIntent(mContext, MOCK_ACTION1); 825 assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); 826 assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); 827 } 828 testRegisterReceiver2()829 public void testRegisterReceiver2() throws InterruptedException { 830 FilteredReceiver broadcastReceiver = new FilteredReceiver(); 831 IntentFilter filter = new IntentFilter(); 832 filter.addAction(MOCK_ACTION1); 833 834 // Test registerReceiver 835 mContext.registerReceiver(broadcastReceiver, filter, null, null, 836 Context.RECEIVER_EXPORTED_UNAUDITED); 837 838 // Test unwanted intent(action = MOCK_ACTION2) 839 broadcastReceiver.reset(); 840 waitForFilteredIntent(mContext, MOCK_ACTION2); 841 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 842 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 843 844 // Send wanted intent(action = MOCK_ACTION1) 845 broadcastReceiver.reset(); 846 waitForFilteredIntent(mContext, MOCK_ACTION1); 847 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 848 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 849 850 mContext.unregisterReceiver(broadcastReceiver); 851 } 852 testRegisterReceiverForAllUsers()853 public void testRegisterReceiverForAllUsers() throws InterruptedException { 854 FilteredReceiver broadcastReceiver = new FilteredReceiver(); 855 IntentFilter filter = new IntentFilter(); 856 filter.addAction(MOCK_ACTION1); 857 858 // Test registerReceiverForAllUsers without permission: verify SecurityException. 859 try { 860 mContext.registerReceiverForAllUsers(broadcastReceiver, filter, null, null, 861 Context.RECEIVER_EXPORTED_UNAUDITED); 862 fail("testRegisterReceiverForAllUsers: " 863 + "SecurityException expected on registerReceiverForAllUsers"); 864 } catch (SecurityException se) { 865 // expected 866 } 867 868 // Test registerReceiverForAllUsers with permission. 869 try { 870 ShellIdentityUtils.invokeMethodWithShellPermissions( 871 mContext, 872 (ctx) -> ctx.registerReceiverForAllUsers(broadcastReceiver, filter, null, null, 873 Context.RECEIVER_EXPORTED_UNAUDITED) 874 ); 875 } catch (SecurityException se) { 876 fail("testRegisterReceiverForAllUsers: SecurityException not expected"); 877 } 878 879 // Test unwanted intent(action = MOCK_ACTION2) 880 broadcastReceiver.reset(); 881 waitForFilteredIntent(mContext, MOCK_ACTION2); 882 assertFalse(broadcastReceiver.hadReceivedBroadCast1()); 883 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 884 885 // Send wanted intent(action = MOCK_ACTION1) 886 broadcastReceiver.reset(); 887 waitForFilteredIntent(mContext, MOCK_ACTION1); 888 assertTrue(broadcastReceiver.hadReceivedBroadCast1()); 889 assertEquals(broadcastReceiver.getSendingUser(), Process.myUserHandle()); 890 assertFalse(broadcastReceiver.hadReceivedBroadCast2()); 891 892 mContext.unregisterReceiver(broadcastReceiver); 893 } 894 testAccessWallpaper()895 public void testAccessWallpaper() throws IOException, InterruptedException { 896 if (!isWallpaperSupported()) return; 897 898 SystemUtil.runWithShellPermissionIdentity( 899 () -> mOriginalWallpaper = (BitmapDrawable) mContext.getWallpaper(), 900 READ_WALLPAPER_INTERNAL); 901 902 // set Wallpaper by context#setWallpaper(Bitmap) 903 Bitmap bitmap = Bitmap.createBitmap(20, 30, Bitmap.Config.RGB_565); 904 905 // grant permission READ_WALLPAPER_INTERNAL for the whole test 906 SystemUtil.runWithShellPermissionIdentity(() -> { 907 // Test getWallpaper 908 Drawable testDrawable = mContext.getWallpaper(); 909 // Test peekWallpaper 910 Drawable testDrawable2 = mContext.peekWallpaper(); 911 912 mContext.setWallpaper(bitmap); 913 mWallpaperChanged = true; 914 synchronized (this) { 915 wait(500); 916 } 917 918 assertNotSame(testDrawable, mContext.peekWallpaper()); 919 assertNotNull(mContext.getWallpaper()); 920 assertNotSame(testDrawable2, mContext.peekWallpaper()); 921 assertNotNull(mContext.peekWallpaper()); 922 923 // set Wallpaper by context#setWallpaper(InputStream) 924 mContext.clearWallpaper(); 925 926 testDrawable = mContext.getWallpaper(); 927 InputStream stream = mContext.getResources().openRawResource(R.drawable.scenery); 928 929 mContext.setWallpaper(stream); 930 synchronized (this) { 931 wait(1000); 932 } 933 934 assertNotSame(testDrawable, mContext.peekWallpaper()); 935 }, READ_WALLPAPER_INTERNAL); 936 } 937 testAccessDatabase()938 public void testAccessDatabase() { 939 String DATABASE_NAME = "databasetest"; 940 String DATABASE_NAME1 = DATABASE_NAME + "1"; 941 String DATABASE_NAME2 = DATABASE_NAME + "2"; 942 SQLiteDatabase mDatabase; 943 File mDatabaseFile; 944 945 SQLiteDatabase.CursorFactory factory = new SQLiteDatabase.CursorFactory() { 946 public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, 947 String editTable, SQLiteQuery query) { 948 return new android.database.sqlite.SQLiteCursor(db, masterQuery, editTable, query) { 949 @Override 950 public boolean requery() { 951 setSelectionArguments(new String[] { "2" }); 952 return super.requery(); 953 } 954 }; 955 } 956 }; 957 958 // FIXME: Move cleanup into tearDown() 959 for (String db : mContext.databaseList()) { 960 File f = mContext.getDatabasePath(db); 961 if (f.exists()) { 962 mContext.deleteDatabase(db); 963 } 964 } 965 966 // Test openOrCreateDatabase with null and actual factory 967 mDatabase = mContext.openOrCreateDatabase(DATABASE_NAME1, 968 Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, factory); 969 assertNotNull(mDatabase); 970 mDatabase.close(); 971 mDatabase = mContext.openOrCreateDatabase(DATABASE_NAME2, 972 Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, factory); 973 assertNotNull(mDatabase); 974 mDatabase.close(); 975 976 // Test getDatabasePath 977 File actualDBPath = mContext.getDatabasePath(DATABASE_NAME1); 978 979 // Test databaseList() 980 List<String> list = Arrays.asList(mContext.databaseList()); 981 assertTrue("1) database list: " + list, list.contains(DATABASE_NAME1)); 982 assertTrue("2) database list: " + list, list.contains(DATABASE_NAME2)); 983 984 // Test deleteDatabase() 985 for (int i = 1; i < 3; i++) { 986 mDatabaseFile = mContext.getDatabasePath(DATABASE_NAME + i); 987 assertTrue(mDatabaseFile.exists()); 988 mContext.deleteDatabase(DATABASE_NAME + i); 989 mDatabaseFile = new File(actualDBPath, DATABASE_NAME + i); 990 assertFalse(mDatabaseFile.exists()); 991 } 992 } 993 testEnforceUriPermission1()994 public void testEnforceUriPermission1() { 995 try { 996 Uri uri = Uri.parse("content://ctstest"); 997 mContext.enforceUriPermission(uri, Binder.getCallingPid(), 998 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 999 "enforceUriPermission is not working without possessing an IPC."); 1000 fail("enforceUriPermission is not working without possessing an IPC."); 1001 } catch (SecurityException e) { 1002 // If the function is OK, it should throw a SecurityException here because currently no 1003 // IPC is handled by this process. 1004 } 1005 } 1006 testEnforceUriPermission2()1007 public void testEnforceUriPermission2() { 1008 Uri uri = Uri.parse("content://ctstest"); 1009 try { 1010 mContext.enforceUriPermission(uri, NOT_GRANTED_PERMISSION, 1011 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), Binder.getCallingUid(), 1012 Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1013 "enforceUriPermission is not working without possessing an IPC."); 1014 fail("enforceUriPermission is not working without possessing an IPC."); 1015 } catch (SecurityException e) { 1016 // If the function is ok, it should throw a SecurityException here because currently no 1017 // IPC is handled by this process. 1018 } 1019 } 1020 testGetPackageResourcePath()1021 public void testGetPackageResourcePath() { 1022 assertNotNull(mContext.getPackageResourcePath()); 1023 } 1024 testStartActivityWithActivityNotFound()1025 public void testStartActivityWithActivityNotFound() { 1026 Intent intent = new Intent(mContext, ContextCtsActivity.class); 1027 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1028 try { 1029 mContext.startActivity(intent); 1030 fail("Test startActivity should throw a ActivityNotFoundException here."); 1031 } catch (ActivityNotFoundException e) { 1032 // Because ContextWrapper is a wrapper class, so no need to test 1033 // the details of the function's performance. Getting a result 1034 // from the wrapped class is enough for testing. 1035 } 1036 } 1037 testStartActivityWithNonExportedActivity()1038 public void testStartActivityWithNonExportedActivity() { 1039 Intent intent = new Intent("android.cts.action.TEST_NON_EXPORTED"); 1040 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1041 try { 1042 mContext.startActivity(intent); 1043 fail("Test startActivity should throw a ActivityNotFoundException here."); 1044 } catch (ActivityNotFoundException e) { 1045 // Because ContextWrapper is a wrapper class, so no need to test 1046 // the details of the function's performance. Getting a result 1047 // from the wrapped class is enough for testing. 1048 } 1049 } 1050 testStartActivityWithExportedActivity()1051 public void testStartActivityWithExportedActivity() { 1052 Intent intent = new Intent("android.cts.action.TEST_EXPORTED"); 1053 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1054 try { 1055 mContext.startActivity(intent); 1056 } catch (ActivityNotFoundException e) { 1057 fail("Test startActivity should not throw a ActivityNotFoundException here."); 1058 } 1059 } 1060 testStartActivities()1061 public void testStartActivities() throws Exception { 1062 final Intent[] intents = { 1063 new Intent().setComponent(new ComponentName(mContext, 1064 AvailableIntentsActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 1065 new Intent().setComponent(new ComponentName(mContext, 1066 ImageCaptureActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 1067 }; 1068 1069 final Instrumentation.ActivityMonitor firstMonitor = getInstrumentation() 1070 .addMonitor(AvailableIntentsActivity.class.getName(), null /* result */, 1071 false /* block */); 1072 final Instrumentation.ActivityMonitor secondMonitor = getInstrumentation() 1073 .addMonitor(ImageCaptureActivity.class.getName(), null /* result */, 1074 false /* block */); 1075 1076 mContext.startActivities(intents); 1077 1078 Activity firstActivity = getInstrumentation().waitForMonitorWithTimeout(firstMonitor, 5000); 1079 assertNotNull(firstActivity); 1080 1081 Activity secondActivity = getInstrumentation().waitForMonitorWithTimeout(secondMonitor, 1082 5000); 1083 assertNotNull(secondActivity); 1084 } 1085 testStartActivityAsUser()1086 public void testStartActivityAsUser() { 1087 try (ActivitySession activitySession = new ActivitySession()) { 1088 Intent intent = new Intent(mContext, AvailableIntentsActivity.class); 1089 1090 activitySession.assertActivityLaunched(intent.getComponent().getClassName(), 1091 () -> SystemUtil.runWithShellPermissionIdentity(() -> 1092 mContext.startActivityAsUser(intent, UserHandle.CURRENT))); 1093 } 1094 } 1095 testStartActivity()1096 public void testStartActivity() { 1097 try (ActivitySession activitySession = new ActivitySession()) { 1098 Intent intent = new Intent(mContext, AvailableIntentsActivity.class); 1099 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1100 1101 activitySession.assertActivityLaunched(intent.getComponent().getClassName(), 1102 () -> mContext.startActivity(intent)); 1103 } 1104 } 1105 1106 /** 1107 * Helper class to launch / close test activity. 1108 */ 1109 private class ActivitySession implements AutoCloseable { 1110 private Activity mTestActivity; 1111 private static final int ACTIVITY_LAUNCH_TIMEOUT = 5000; 1112 assertActivityLaunched(String activityClassName, Runnable activityStarter)1113 void assertActivityLaunched(String activityClassName, Runnable activityStarter) { 1114 final Instrumentation.ActivityMonitor monitor = getInstrumentation() 1115 .addMonitor(activityClassName, null /* result */, 1116 false /* block */); 1117 activityStarter.run(); 1118 // Wait for activity launch with timeout. 1119 mTestActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 1120 ACTIVITY_LAUNCH_TIMEOUT); 1121 assertNotNull(mTestActivity); 1122 } 1123 1124 @Override close()1125 public void close() { 1126 if (mTestActivity != null) { 1127 mTestActivity.finishAndRemoveTask(); 1128 } 1129 } 1130 } 1131 testCreatePackageContext()1132 public void testCreatePackageContext() throws PackageManager.NameNotFoundException { 1133 Context actualContext = mContext.createPackageContext("com.android.shell", 1134 Context.CONTEXT_IGNORE_SECURITY); 1135 1136 assertNotNull(actualContext); 1137 } 1138 testCreatePackageContextAsUser()1139 public void testCreatePackageContextAsUser() throws Exception { 1140 for (UserHandle user : new UserHandle[] { 1141 android.os.Process.myUserHandle(), 1142 UserHandle.ALL, UserHandle.CURRENT, UserHandle.SYSTEM 1143 }) { 1144 assertEquals(user, mContext 1145 .createPackageContextAsUser("com.android.shell", 0, user).getUser()); 1146 } 1147 } 1148 testCreateContextAsUser()1149 public void testCreateContextAsUser() throws Exception { 1150 for (UserHandle user : new UserHandle[] { 1151 android.os.Process.myUserHandle(), 1152 UserHandle.ALL, UserHandle.CURRENT, UserHandle.SYSTEM 1153 }) { 1154 assertEquals(user, mContext.createContextAsUser(user, 0).getUser()); 1155 } 1156 } 1157 testGetMainLooper()1158 public void testGetMainLooper() { 1159 assertNotNull(mContext.getMainLooper()); 1160 } 1161 testGetApplicationContext()1162 public void testGetApplicationContext() { 1163 assertSame(mContext.getApplicationContext(), mContext.getApplicationContext()); 1164 } 1165 testGetSharedPreferences()1166 public void testGetSharedPreferences() { 1167 SharedPreferences sp; 1168 SharedPreferences localSP; 1169 1170 sp = PreferenceManager.getDefaultSharedPreferences(mContext); 1171 String packageName = mContext.getPackageName(); 1172 localSP = mContext.getSharedPreferences(packageName + "_preferences", 1173 Context.MODE_PRIVATE); 1174 assertSame(sp, localSP); 1175 } 1176 testRevokeUriPermission()1177 public void testRevokeUriPermission() { 1178 Uri uri = Uri.parse("contents://ctstest"); 1179 mContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1180 } 1181 testAccessService()1182 public void testAccessService() throws InterruptedException { 1183 MockContextService.reset(); 1184 bindExpectResult(mContext, new Intent(mContext, MockContextService.class)); 1185 1186 // Check startService 1187 assertTrue(MockContextService.hadCalledOnStart()); 1188 // Check bindService 1189 assertTrue(MockContextService.hadCalledOnBind()); 1190 1191 assertTrue(MockContextService.hadCalledOnDestory()); 1192 // Check unbinService 1193 assertTrue(MockContextService.hadCalledOnUnbind()); 1194 } 1195 testGetPackageCodePath()1196 public void testGetPackageCodePath() { 1197 assertNotNull(mContext.getPackageCodePath()); 1198 } 1199 testGetPackageName()1200 public void testGetPackageName() { 1201 assertEquals("android.content.cts", mContext.getPackageName()); 1202 } 1203 testGetCacheDir()1204 public void testGetCacheDir() { 1205 assertNotNull(mContext.getCacheDir()); 1206 } 1207 testGetContentResolver()1208 public void testGetContentResolver() { 1209 assertSame(mContext.getContentResolver(), mContext.getContentResolver()); 1210 } 1211 testGetFileStreamPath()1212 public void testGetFileStreamPath() { 1213 String TEST_FILENAME = "TestGetFileStreamPath"; 1214 1215 // Test the path including the input filename 1216 String fileStreamPath = mContext.getFileStreamPath(TEST_FILENAME).toString(); 1217 assertTrue(fileStreamPath.indexOf(TEST_FILENAME) >= 0); 1218 } 1219 testGetClassLoader()1220 public void testGetClassLoader() { 1221 assertSame(mContext.getClassLoader(), mContext.getClassLoader()); 1222 } 1223 testGetWallpaperDesiredMinimumHeightAndWidth()1224 public void testGetWallpaperDesiredMinimumHeightAndWidth() { 1225 if (!isWallpaperSupported()) return; 1226 1227 int height = mContext.getWallpaperDesiredMinimumHeight(); 1228 int width = mContext.getWallpaperDesiredMinimumWidth(); 1229 1230 // returned value is <= 0, the caller should use the height of the 1231 // default display instead. 1232 // That is to say, the return values of desired minimumHeight and 1233 // minimunWidth are at the same side of 0-dividing line. 1234 assertTrue((height > 0 && width > 0) || (height <= 0 && width <= 0)); 1235 } 1236 testAccessStickyBroadcast()1237 public void testAccessStickyBroadcast() throws InterruptedException { 1238 ResultReceiver resultReceiver = new ResultReceiver(); 1239 1240 Intent intent = new Intent(MOCK_STICKY_ACTION); 1241 TestBroadcastReceiver stickyReceiver = new TestBroadcastReceiver(); 1242 1243 mContext.sendStickyBroadcast(intent); 1244 1245 waitForReceiveBroadCast(resultReceiver); 1246 1247 assertEquals(intent.getAction(), 1248 mContext.registerReceiver(stickyReceiver, new IntentFilter(MOCK_STICKY_ACTION), 1249 Context.RECEIVER_NOT_EXPORTED).getAction()); 1250 1251 synchronized (mLockObj) { 1252 mLockObj.wait(BROADCAST_TIMEOUT); 1253 } 1254 1255 assertTrue("Receiver didn't make any response.", stickyReceiver.hadReceivedBroadCast()); 1256 1257 mContext.unregisterReceiver(stickyReceiver); 1258 mContext.removeStickyBroadcast(intent); 1259 1260 assertNull(mContext.registerReceiver(stickyReceiver, 1261 new IntentFilter(MOCK_STICKY_ACTION), Context.RECEIVER_EXPORTED_UNAUDITED)); 1262 mContext.unregisterReceiver(stickyReceiver); 1263 } 1264 testCheckCallingOrSelfUriPermissions()1265 public void testCheckCallingOrSelfUriPermissions() { 1266 List<Uri> uris = new ArrayList<>(); 1267 Uri uri1 = Uri.parse("content://ctstest1"); 1268 uris.add(uri1); 1269 Uri uri2 = Uri.parse("content://ctstest2"); 1270 uris.add(uri2); 1271 1272 int[] retValue = mContext.checkCallingOrSelfUriPermissions(uris, 1273 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1274 assertEquals(retValue.length, 2); 1275 // This package does not have access to the given URIs 1276 assertEquals(PERMISSION_DENIED, retValue[0]); 1277 assertEquals(PERMISSION_DENIED, retValue[1]); 1278 } 1279 testCheckCallingOrSelfUriPermission()1280 public void testCheckCallingOrSelfUriPermission() { 1281 Uri uri = Uri.parse("content://ctstest"); 1282 1283 int retValue = mContext.checkCallingOrSelfUriPermission(uri, 1284 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1285 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1286 } 1287 testGrantUriPermission()1288 public void testGrantUriPermission() { 1289 mContext.grantUriPermission("com.android.mms", Uri.parse("contents://ctstest"), 1290 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1291 } 1292 testCheckPermissionGranted()1293 public void testCheckPermissionGranted() { 1294 int returnValue = mContext.checkPermission( 1295 GRANTED_PERMISSION, Process.myPid(), Process.myUid()); 1296 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1297 } 1298 testCheckPermissionNotGranted()1299 public void testCheckPermissionNotGranted() { 1300 int returnValue = mContext.checkPermission( 1301 NOT_GRANTED_PERMISSION, Process.myPid(), Process.myUid()); 1302 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1303 } 1304 testCheckPermissionRootUser()1305 public void testCheckPermissionRootUser() { 1306 // Test with root user, everything will be granted. 1307 int returnValue = mContext.checkPermission(NOT_GRANTED_PERMISSION, 1, ROOT_UID); 1308 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1309 } 1310 testCheckPermissionInvalidRequest()1311 public void testCheckPermissionInvalidRequest() { 1312 // Test with null permission. 1313 try { 1314 int returnValue = mContext.checkPermission(null, 0, ROOT_UID); 1315 fail("checkPermission should not accept null permission"); 1316 } catch (IllegalArgumentException e) { 1317 } 1318 1319 // Test with invalid uid and included granted permission. 1320 int returnValue = mContext.checkPermission(GRANTED_PERMISSION, 1, -11); 1321 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1322 } 1323 testCheckSelfPermissionGranted()1324 public void testCheckSelfPermissionGranted() { 1325 int returnValue = mContext.checkSelfPermission(GRANTED_PERMISSION); 1326 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1327 } 1328 testCheckSelfPermissionNotGranted()1329 public void testCheckSelfPermissionNotGranted() { 1330 int returnValue = mContext.checkSelfPermission(NOT_GRANTED_PERMISSION); 1331 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1332 } 1333 testEnforcePermissionGranted()1334 public void testEnforcePermissionGranted() { 1335 mContext.enforcePermission( 1336 GRANTED_PERMISSION, Process.myPid(), Process.myUid(), 1337 "permission isn't granted"); 1338 } 1339 testEnforcePermissionNotGranted()1340 public void testEnforcePermissionNotGranted() { 1341 try { 1342 mContext.enforcePermission( 1343 NOT_GRANTED_PERMISSION, Process.myPid(), Process.myUid(), 1344 "permission isn't granted"); 1345 fail("Permission shouldn't be granted."); 1346 } catch (SecurityException expected) { 1347 } 1348 } 1349 testCheckCallingOrSelfPermission_noIpc()1350 public void testCheckCallingOrSelfPermission_noIpc() { 1351 // There's no ongoing Binder call, so this package's permissions are checked. 1352 int retValue = mContext.checkCallingOrSelfPermission(GRANTED_PERMISSION); 1353 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1354 1355 retValue = mContext.checkCallingOrSelfPermission(NOT_GRANTED_PERMISSION); 1356 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1357 } 1358 testCheckCallingOrSelfPermission_ipc()1359 public void testCheckCallingOrSelfPermission_ipc() throws Exception { 1360 bindBinderPermissionTestService(); 1361 try { 1362 int retValue = mBinderPermissionTestService.doCheckCallingOrSelfPermission( 1363 GRANTED_PERMISSION); 1364 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1365 1366 retValue = mBinderPermissionTestService.doCheckCallingOrSelfPermission( 1367 NOT_GRANTED_PERMISSION); 1368 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1369 } finally { 1370 mContext.unbindService(mBinderPermissionTestConnection); 1371 } 1372 } 1373 testEnforceCallingOrSelfPermission_noIpc()1374 public void testEnforceCallingOrSelfPermission_noIpc() { 1375 // There's no ongoing Binder call, so this package's permissions are checked. 1376 mContext.enforceCallingOrSelfPermission( 1377 GRANTED_PERMISSION, "permission isn't granted"); 1378 1379 try { 1380 mContext.enforceCallingOrSelfPermission( 1381 NOT_GRANTED_PERMISSION, "permission isn't granted"); 1382 fail("Permission shouldn't be granted."); 1383 } catch (SecurityException expected) { 1384 } 1385 } 1386 testEnforceCallingOrSelfPermission_ipc()1387 public void testEnforceCallingOrSelfPermission_ipc() throws Exception { 1388 bindBinderPermissionTestService(); 1389 try { 1390 mBinderPermissionTestService.doEnforceCallingOrSelfPermission(GRANTED_PERMISSION); 1391 1392 try { 1393 mBinderPermissionTestService.doEnforceCallingOrSelfPermission( 1394 NOT_GRANTED_PERMISSION); 1395 fail("Permission shouldn't be granted."); 1396 } catch (SecurityException expected) { 1397 } 1398 } finally { 1399 mContext.unbindService(mBinderPermissionTestConnection); 1400 } 1401 } 1402 testCheckCallingPermission_noIpc()1403 public void testCheckCallingPermission_noIpc() { 1404 // Denied because no IPC is active. 1405 int retValue = mContext.checkCallingPermission(GRANTED_PERMISSION); 1406 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1407 } 1408 testEnforceCallingPermission_noIpc()1409 public void testEnforceCallingPermission_noIpc() { 1410 try { 1411 mContext.enforceCallingPermission( 1412 GRANTED_PERMISSION, 1413 "enforceCallingPermission is not working without possessing an IPC."); 1414 fail("enforceCallingPermission is not working without possessing an IPC."); 1415 } catch (SecurityException e) { 1416 // Currently no IPC is handled by this process, this exception is expected 1417 } 1418 } 1419 testEnforceCallingPermission_ipc()1420 public void testEnforceCallingPermission_ipc() throws Exception { 1421 bindBinderPermissionTestService(); 1422 try { 1423 mBinderPermissionTestService.doEnforceCallingPermission(GRANTED_PERMISSION); 1424 1425 try { 1426 mBinderPermissionTestService.doEnforceCallingPermission(NOT_GRANTED_PERMISSION); 1427 fail("Permission shouldn't be granted."); 1428 } catch (SecurityException expected) { 1429 } 1430 } finally { 1431 mContext.unbindService(mBinderPermissionTestConnection); 1432 } 1433 } 1434 testCheckCallingPermission_ipc()1435 public void testCheckCallingPermission_ipc() throws Exception { 1436 bindBinderPermissionTestService(); 1437 try { 1438 int returnValue = mBinderPermissionTestService.doCheckCallingPermission( 1439 GRANTED_PERMISSION); 1440 assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); 1441 1442 returnValue = mBinderPermissionTestService.doCheckCallingPermission( 1443 NOT_GRANTED_PERMISSION); 1444 assertEquals(PackageManager.PERMISSION_DENIED, returnValue); 1445 } finally { 1446 mContext.unbindService(mBinderPermissionTestConnection); 1447 } 1448 } 1449 bindBinderPermissionTestService()1450 private void bindBinderPermissionTestService() { 1451 Intent intent = new Intent(mContext, IBinderPermissionTestService.class); 1452 intent.setComponent(new ComponentName( 1453 "com.android.cts", "com.android.cts.BinderPermissionTestService")); 1454 1455 mBinderPermissionTestConnection = new ServiceConnection() { 1456 @Override 1457 public void onServiceConnected(ComponentName componentName, IBinder iBinder) { 1458 mBinderPermissionTestService = 1459 IBinderPermissionTestService.Stub.asInterface(iBinder); 1460 } 1461 1462 @Override 1463 public void onServiceDisconnected(ComponentName componentName) { 1464 } 1465 }; 1466 1467 assertTrue("Service not bound", mContext.bindService( 1468 intent, mBinderPermissionTestConnection, Context.BIND_AUTO_CREATE)); 1469 1470 new PollingCheck(15 * 1000) { 1471 protected boolean check() { 1472 return mBinderPermissionTestService != null; // Service was bound. 1473 } 1474 }.run(); 1475 } 1476 testCheckUriPermissions()1477 public void testCheckUriPermissions() { 1478 List<Uri> uris = new ArrayList<>(); 1479 Uri uri1 = Uri.parse("content://ctstest1"); 1480 uris.add(uri1); 1481 Uri uri2 = Uri.parse("content://ctstest2"); 1482 uris.add(uri2); 1483 1484 // Root has access to all URIs 1485 int[] retValue = mContext.checkUriPermissions(uris, Binder.getCallingPid(), 0, 1486 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1487 assertEquals(retValue.length, 2); 1488 assertEquals(PERMISSION_GRANTED, retValue[0]); 1489 assertEquals(PERMISSION_GRANTED, retValue[1]); 1490 1491 retValue = mContext.checkUriPermissions(uris, Binder.getCallingPid(), 1492 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1493 assertEquals(retValue.length, 2); 1494 // This package does not have access to the given URIs 1495 assertEquals(PERMISSION_DENIED, retValue[0]); 1496 assertEquals(PERMISSION_DENIED, retValue[1]); 1497 } 1498 testCheckUriPermission1()1499 public void testCheckUriPermission1() { 1500 Uri uri = Uri.parse("content://ctstest"); 1501 1502 int retValue = mContext.checkUriPermission(uri, Binder.getCallingPid(), 0, 1503 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1504 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1505 1506 retValue = mContext.checkUriPermission(uri, Binder.getCallingPid(), 1507 Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1508 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1509 } 1510 testCheckUriPermission2()1511 public void testCheckUriPermission2() { 1512 Uri uri = Uri.parse("content://ctstest"); 1513 1514 int retValue = mContext.checkUriPermission(uri, NOT_GRANTED_PERMISSION, 1515 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), 0, 1516 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1517 assertEquals(PackageManager.PERMISSION_GRANTED, retValue); 1518 1519 retValue = mContext.checkUriPermission(uri, NOT_GRANTED_PERMISSION, 1520 NOT_GRANTED_PERMISSION, Binder.getCallingPid(), Binder.getCallingUid(), 1521 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1522 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1523 } 1524 testCheckCallingUriPermissions()1525 public void testCheckCallingUriPermissions() { 1526 List<Uri> uris = new ArrayList<>(); 1527 Uri uri1 = Uri.parse("content://ctstest1"); 1528 uris.add(uri1); 1529 Uri uri2 = Uri.parse("content://ctstest2"); 1530 uris.add(uri2); 1531 1532 int[] retValue = mContext.checkCallingUriPermissions(uris, 1533 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1534 assertEquals(retValue.length, 2); 1535 // This package does not have access to the given URIs 1536 assertEquals(PERMISSION_DENIED, retValue[0]); 1537 assertEquals(PERMISSION_DENIED, retValue[1]); 1538 } 1539 testCheckCallingUriPermission()1540 public void testCheckCallingUriPermission() { 1541 Uri uri = Uri.parse("content://ctstest"); 1542 1543 int retValue = mContext.checkCallingUriPermission(uri, 1544 Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 1545 assertEquals(PackageManager.PERMISSION_DENIED, retValue); 1546 } 1547 testEnforceCallingUriPermission()1548 public void testEnforceCallingUriPermission() { 1549 try { 1550 Uri uri = Uri.parse("content://ctstest"); 1551 mContext.enforceCallingUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1552 "enforceCallingUriPermission is not working without possessing an IPC."); 1553 fail("enforceCallingUriPermission is not working without possessing an IPC."); 1554 } catch (SecurityException e) { 1555 // If the function is OK, it should throw a SecurityException here because currently no 1556 // IPC is handled by this process. 1557 } 1558 } 1559 testGetDir()1560 public void testGetDir() { 1561 File dir = mContext.getDir("testpath", Context.MODE_PRIVATE); 1562 assertNotNull(dir); 1563 dir.delete(); 1564 } 1565 testGetPackageManager()1566 public void testGetPackageManager() { 1567 assertSame(mContext.getPackageManager(), mContext.getPackageManager()); 1568 } 1569 testSendBroadcast1()1570 public void testSendBroadcast1() throws InterruptedException { 1571 final ResultReceiver receiver = new ResultReceiver(); 1572 1573 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1574 1575 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION) 1576 .setPackage(mContext.getPackageName())); 1577 1578 new PollingCheck(BROADCAST_TIMEOUT){ 1579 @Override 1580 protected boolean check() { 1581 return receiver.hasReceivedBroadCast(); 1582 } 1583 }.run(); 1584 } 1585 testSendBroadcast2()1586 public void testSendBroadcast2() throws InterruptedException { 1587 final ResultReceiver receiver = new ResultReceiver(); 1588 1589 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1590 1591 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION) 1592 .setPackage(mContext.getPackageName()), null); 1593 1594 new PollingCheck(BROADCAST_TIMEOUT){ 1595 @Override 1596 protected boolean check() { 1597 return receiver.hasReceivedBroadCast(); 1598 } 1599 }.run(); 1600 } 1601 testSendBroadcast_WithExportedRuntimeReceiver()1602 public void testSendBroadcast_WithExportedRuntimeReceiver() throws InterruptedException { 1603 final ResultReceiver receiver = new ResultReceiver(); 1604 1605 registerBroadcastReceiver(receiver, new IntentFilter( 1606 ResultReceiver.MOCK_ACTION), Context.RECEIVER_EXPORTED); 1607 1608 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION), null); 1609 1610 try { 1611 new PollingCheck(BROADCAST_TIMEOUT) { 1612 @Override 1613 protected boolean check() { 1614 return receiver.hasReceivedBroadCast(); 1615 } 1616 }.run(); 1617 } catch (AssertionError e) { 1618 Assert.fail(); 1619 } 1620 } 1621 testSendBroadcast_WithNonExportedRuntimeReceiver()1622 public void testSendBroadcast_WithNonExportedRuntimeReceiver() throws InterruptedException { 1623 final ResultReceiver receiver = new ResultReceiver() { 1624 @Override 1625 public void onReceive(Context context, Intent intent) { 1626 Assert.fail(); 1627 } 1628 }; 1629 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1630 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION), null); 1631 1632 try { 1633 new PollingCheck(BROADCAST_TIMEOUT) { 1634 @Override 1635 protected boolean check() { 1636 return receiver.hasReceivedBroadCast(); 1637 } 1638 }.run(); 1639 } catch (AssertionError e) { 1640 // If the check still fails after the given timeout we can assume the receiver has 1641 // never received the broadcast, so we can swallow the exception and pass the test. 1642 } 1643 } 1644 1645 /** 1646 * Verify the receiver should get the broadcast since it has all of the required permissions. 1647 */ testSendBroadcastRequireAllOfPermissions_receiverHasAllPermissions()1648 public void testSendBroadcastRequireAllOfPermissions_receiverHasAllPermissions() 1649 throws Exception { 1650 final ResultReceiver receiver = new ResultReceiver(); 1651 1652 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1653 BroadcastOptions options = BroadcastOptions.makeBasic(); 1654 options.setRequireAllOfPermissions( 1655 new String[] { // this test APK has both these permissions 1656 android.Manifest.permission.ACCESS_WIFI_STATE, 1657 android.Manifest.permission.ACCESS_NETWORK_STATE 1658 }); 1659 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION) 1660 .setPackage(mContext.getPackageName()), null, options.toBundle()); 1661 1662 new PollingCheck(BROADCAST_TIMEOUT) { 1663 @Override 1664 protected boolean check() { 1665 return receiver.hasReceivedBroadCast(); 1666 } 1667 }.run(); 1668 } 1669 1670 /** The receiver should not get the broadcast if it does not have all the permissions. */ testSendBroadcastRequireAllOfPermissions_receiverHasSomePermissions()1671 public void testSendBroadcastRequireAllOfPermissions_receiverHasSomePermissions() 1672 throws Exception { 1673 final ResultReceiver receiver = new ResultReceiver(); 1674 1675 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1676 BroadcastOptions options = BroadcastOptions.makeBasic(); 1677 options.setRequireAllOfPermissions( 1678 new String[] { // this test APK only has ACCESS_WIFI_STATE 1679 android.Manifest.permission.ACCESS_WIFI_STATE, 1680 android.Manifest.permission.NETWORK_STACK, 1681 }); 1682 1683 mContext.sendBroadcast( 1684 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 1685 null, options.toBundle()); 1686 1687 Thread.sleep(BROADCAST_TIMEOUT); 1688 assertFalse(receiver.hasReceivedBroadCast()); 1689 } 1690 1691 /** 1692 * Verify the receiver will get the broadcast since it has none of the excluded permissions. 1693 */ testSendBroadcastRequireNoneOfPermissions_receiverHasNoneOfExcludedPermissions()1694 public void testSendBroadcastRequireNoneOfPermissions_receiverHasNoneOfExcludedPermissions() 1695 throws Exception { 1696 final ResultReceiver receiver = new ResultReceiver(); 1697 1698 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1699 BroadcastOptions options = BroadcastOptions.makeBasic(); 1700 options.setRequireAllOfPermissions( 1701 new String[] { // this test APK has both these permissions 1702 android.Manifest.permission.ACCESS_WIFI_STATE, 1703 android.Manifest.permission.ACCESS_NETWORK_STATE 1704 }); 1705 options.setRequireNoneOfPermissions( 1706 new String[] { // test package does not have NETWORK_STACK 1707 android.Manifest.permission.NETWORK_STACK 1708 }); 1709 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION) 1710 .setPackage(mContext.getPackageName()), null, options.toBundle()); 1711 1712 new PollingCheck(BROADCAST_TIMEOUT) { 1713 @Override 1714 protected boolean check() { 1715 return receiver.hasReceivedBroadCast(); 1716 } 1717 }.run(); 1718 } 1719 1720 /** 1721 * Verify the receiver will not get the broadcast since it has one of the excluded permissions. 1722 */ testSendBroadcastRequireNoneOfPermissions_receiverHasExcludedPermissions()1723 public void testSendBroadcastRequireNoneOfPermissions_receiverHasExcludedPermissions() 1724 throws Exception { 1725 final ResultReceiver receiver = new ResultReceiver(); 1726 1727 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1728 BroadcastOptions options = BroadcastOptions.makeBasic(); 1729 options.setRequireAllOfPermissions( 1730 new String[] { // this test APK has ACCESS_WIFI_STATE 1731 android.Manifest.permission.ACCESS_WIFI_STATE 1732 }); 1733 options.setRequireNoneOfPermissions( 1734 new String[] { // test package has ACCESS_NETWORK_STATE 1735 android.Manifest.permission.ACCESS_NETWORK_STATE 1736 }); 1737 mContext.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION) 1738 .setPackage(mContext.getPackageName()), null, 1739 options.toBundle()); 1740 1741 Thread.sleep(BROADCAST_TIMEOUT); 1742 assertFalse(receiver.hasReceivedBroadCast()); 1743 } 1744 1745 /** The receiver should get the broadcast if it has all the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasAllPermissions()1746 public void testSendBroadcastWithMultiplePermissions_receiverHasAllPermissions() 1747 throws Exception { 1748 final ResultReceiver receiver = new ResultReceiver(); 1749 1750 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1751 1752 mContext.sendBroadcastWithMultiplePermissions( 1753 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 1754 new String[] { // this test APK has both these permissions 1755 android.Manifest.permission.ACCESS_WIFI_STATE, 1756 android.Manifest.permission.ACCESS_NETWORK_STATE, 1757 }); 1758 1759 new PollingCheck(BROADCAST_TIMEOUT) { 1760 @Override 1761 protected boolean check() { 1762 return receiver.hasReceivedBroadCast(); 1763 } 1764 }.run(); 1765 } 1766 1767 /** The receiver should not get the broadcast if it does not have all the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasSomePermissions()1768 public void testSendBroadcastWithMultiplePermissions_receiverHasSomePermissions() 1769 throws Exception { 1770 final ResultReceiver receiver = new ResultReceiver(); 1771 1772 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1773 1774 mContext.sendBroadcastWithMultiplePermissions( 1775 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 1776 new String[] { // this test APK only has ACCESS_WIFI_STATE 1777 android.Manifest.permission.ACCESS_WIFI_STATE, 1778 android.Manifest.permission.NETWORK_STACK, 1779 }); 1780 1781 Thread.sleep(BROADCAST_TIMEOUT); 1782 assertFalse(receiver.hasReceivedBroadCast()); 1783 } 1784 1785 /** The receiver should not get the broadcast if it has none of the permissions. */ testSendBroadcastWithMultiplePermissions_receiverHasNoPermissions()1786 public void testSendBroadcastWithMultiplePermissions_receiverHasNoPermissions() 1787 throws Exception { 1788 final ResultReceiver receiver = new ResultReceiver(); 1789 1790 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); 1791 1792 mContext.sendBroadcastWithMultiplePermissions( 1793 new Intent(ResultReceiver.MOCK_ACTION).setPackage(mContext.getPackageName()), 1794 new String[] { // this test APK has neither of these permissions 1795 android.Manifest.permission.NETWORK_SETTINGS, 1796 android.Manifest.permission.NETWORK_STACK, 1797 }); 1798 1799 Thread.sleep(BROADCAST_TIMEOUT); 1800 assertFalse(receiver.hasReceivedBroadCast()); 1801 } 1802 1803 /** 1804 * Starting from Android 13, a SecurityException is thrown for apps targeting this 1805 * release or later that do not specify {@link Context#RECEIVER_EXPORTED} or {@link 1806 * Context#RECEIVER_NOT_EXPORTED} when registering for non-system broadcasts. 1807 */ testRegisterReceiver_noFlags_exceptionThrown()1808 public void testRegisterReceiver_noFlags_exceptionThrown() throws Exception { 1809 try { 1810 final ResultReceiver receiver = new ResultReceiver(); 1811 1812 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION), 0); 1813 1814 fail("An app targeting Android 13 and registering a dynamic receiver for a " 1815 + "non-system broadcast must receive a SecurityException if " 1816 + "RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED is not specified"); 1817 } catch (SecurityException expected) { 1818 } 1819 } 1820 1821 /** 1822 * An app targeting Android 13 or later can register for system broadcasts without specifying 1823 * {@link Context#RECEIVER_EXPORTED} or {@link Context@RECEIVER_NOT_EXPORTED}. 1824 */ testRegisterReceiver_noFlagsProtectedBroadcast_noExceptionThrown()1825 public void testRegisterReceiver_noFlagsProtectedBroadcast_noExceptionThrown() 1826 throws Exception { 1827 final ResultReceiver receiver = new ResultReceiver(); 1828 1829 // Intent.ACTION_SCREEN_OFF is a system broadcast and thus should not require a flag 1830 // indicating whether the receiver is exported. 1831 registerBroadcastReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF), 0); 1832 } 1833 1834 /** 1835 * An app targeting Android 13 or later can request a sticky broadcast via 1836 * {@code Context#registerReceiver} without specifying {@link Context#RECEIVER_EXPORTED} or 1837 * {@link Context#RECEIVER_NOT_EXPORTED}. 1838 */ testRegisterReceiver_noFlagsStickyBroadcast_noExceptionThrown()1839 public void testRegisterReceiver_noFlagsStickyBroadcast_noExceptionThrown() throws Exception { 1840 // If a null receiver is specified to Context#registerReceiver, it indicates the caller 1841 // is requesting a sticky broadcast without actually registering a receiver; a flag 1842 // must not be required in this case. 1843 mContext.registerReceiver(null, new IntentFilter(ResultReceiver.MOCK_ACTION), 0); 1844 } 1845 1846 /** 1847 * Starting from Android 13, an app targeting this release or later must specify one of either 1848 * {@link Context#RECEIVER_EXPORTED} or {@link Context#RECEIVER_NOT_EXPORTED} when registering 1849 * a receiver for non-system broadcasts; however if both are specified then an 1850 * {@link IllegalArgumentException} should be thrown. 1851 */ testRegisterReceiver_bothFlags_exceptionThrown()1852 public void testRegisterReceiver_bothFlags_exceptionThrown() throws Exception { 1853 try { 1854 final ResultReceiver receiver = new ResultReceiver(); 1855 1856 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION), 1857 Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED); 1858 1859 fail("An app invoke invoking Context#registerReceiver with both RECEIVER_EXPORTED and" 1860 + " RECEIVER_NOT_EXPORTED set must receive an IllegalArgumentException"); 1861 } catch (IllegalArgumentException expected) { 1862 } 1863 } 1864 1865 /** 1866 * Verifies a receiver registered with {@link Context#RECEIVER_EXPORTED} can receive a 1867 * broadcast from an external app. 1868 * 1869 * <p>The broadcast is sent as a shell command since this most closely simulates sending a 1870 * broadcast from an external app; sending the broadcast via {@code 1871 * ShellIdentityUtils#invokeMethodWithShellPermissionsNoReturn} is still delivered even to 1872 * apps that use {@link Context#RECEIVER_NOT_EXPORTED}. 1873 */ testRegisterReceiver_exported_broadcastReceived()1874 public void testRegisterReceiver_exported_broadcastReceived() throws Exception { 1875 final ResultReceiver receiver = new ResultReceiver(); 1876 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION), 1877 Context.RECEIVER_EXPORTED); 1878 1879 SystemUtil.runShellCommand(EXTERNAL_APP_BROADCAST_COMMAND); 1880 1881 new PollingCheck(BROADCAST_TIMEOUT, "The broadcast to the exported receiver" 1882 + " was not received within the timeout window") { 1883 @Override 1884 protected boolean check() { 1885 return receiver.hasReceivedBroadCast(); 1886 } 1887 }.run(); 1888 } 1889 1890 /** 1891 * Verifies a receiver registered with {@link Context#RECEIVER_EXPORTED_UNAUDITED} can receive 1892 * a broadcast from an external app. 1893 * 1894 * <p>{@code Context#RECEIVER_EXPORTED_UNAUDITED} is only intended to be applied to receivers 1895 * that have not yet been audited to determine their intended exported state; this test ensures 1896 * this flag maintains the existing behavior of exporting the receiver until it can be 1897 * evaluated. 1898 */ testRegisterReceiver_exportedUnaudited_broadcastReceived()1899 public void testRegisterReceiver_exportedUnaudited_broadcastReceived() throws Exception { 1900 final ResultReceiver receiver = new ResultReceiver(); 1901 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION), 1902 Context.RECEIVER_EXPORTED_UNAUDITED); 1903 1904 SystemUtil.runShellCommand(EXTERNAL_APP_BROADCAST_COMMAND); 1905 1906 new PollingCheck(BROADCAST_TIMEOUT, "The broadcast to the exported receiver" 1907 + " was not received within the timeout window") { 1908 @Override 1909 protected boolean check() { 1910 return receiver.hasReceivedBroadCast(); 1911 } 1912 }.run(); 1913 } 1914 1915 /** 1916 * Verifies a receiver registered with {@link Context#RECEIVER_NOT_EXPORTED} does not receive 1917 * a broadcast from an external app. 1918 */ testRegisterReceiver_notExported_broadcastNotReceived()1919 public void testRegisterReceiver_notExported_broadcastNotReceived() throws Exception { 1920 final ResultReceiver receiver = new ResultReceiver(); 1921 registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION), 1922 Context.RECEIVER_NOT_EXPORTED); 1923 1924 SystemUtil.runShellCommand(EXTERNAL_APP_BROADCAST_COMMAND); 1925 1926 Thread.sleep(BROADCAST_TIMEOUT); 1927 assertFalse( 1928 "An external app must not be able to send a broadcast to a dynamic receiver " 1929 + "registered with RECEIVER_NOT_EXPORTED", 1930 receiver.hasReceivedBroadCast()); 1931 } 1932 testRegisterReceiverForSystemBroadcast_notExported_stickyBroadcastReceived()1933 public void testRegisterReceiverForSystemBroadcast_notExported_stickyBroadcastReceived() 1934 throws InterruptedException { 1935 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) { 1936 return; 1937 } 1938 final WifiManager wifiManager = mContext.getSystemService(WifiManager.class); 1939 boolean wifiInitiallyOn = wifiManager.isWifiEnabled(); 1940 // Cycle Wifi to force the WIFI_STATE_CHANGED_ACTION sticky broadcast 1941 if (wifiInitiallyOn) { 1942 SystemUtil.runShellCommand("cmd wifi set-wifi-enabled disabled"); 1943 Thread.sleep(1000); 1944 } 1945 SystemUtil.runShellCommand("cmd wifi set-wifi-enabled enabled"); 1946 Thread.sleep(1000); 1947 1948 try { 1949 TestBroadcastReceiver stickyReceiver = new TestBroadcastReceiver(); 1950 // A receiver registered for sticky broadcasts with the RECEIVER_NOT_EXPORTED flag 1951 // should still receive back a sticky broadcast sent from the system UID. 1952 assertEquals(WifiManager.WIFI_STATE_CHANGED_ACTION, 1953 mContext.registerReceiver(stickyReceiver, 1954 new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION), 1955 Context.RECEIVER_NOT_EXPORTED).getAction()); 1956 synchronized (mLockObj) { 1957 mLockObj.wait(BROADCAST_TIMEOUT); 1958 } 1959 assertTrue("Sticky broadcast not delivered to unexported receiver", 1960 stickyReceiver.hadReceivedBroadCast()); 1961 } finally { 1962 if (wifiInitiallyOn) { 1963 SystemUtil.runShellCommand("cmd wifi set-wifi-enabled enabled"); 1964 } else { 1965 SystemUtil.runShellCommand("cmd wifi set-wifi-enabled disabled"); 1966 } 1967 } 1968 } 1969 testEnforceCallingOrSelfUriPermission()1970 public void testEnforceCallingOrSelfUriPermission() { 1971 try { 1972 Uri uri = Uri.parse("content://ctstest"); 1973 mContext.enforceCallingOrSelfUriPermission(uri, 1974 Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 1975 "enforceCallingOrSelfUriPermission is not working without possessing an IPC."); 1976 fail("enforceCallingOrSelfUriPermission is not working without possessing an IPC."); 1977 } catch (SecurityException e) { 1978 // If the function is OK, it should throw a SecurityException here because currently no 1979 // IPC is handled by this process. 1980 } 1981 } 1982 testGetAssets()1983 public void testGetAssets() { 1984 assertSame(mContext.getAssets(), mContext.getAssets()); 1985 } 1986 testGetResources()1987 public void testGetResources() { 1988 assertSame(mContext.getResources(), mContext.getResources()); 1989 } 1990 testStartInstrumentation()1991 public void testStartInstrumentation() { 1992 // Use wrong name 1993 ComponentName cn = new ComponentName("com.android", 1994 "com.android.content.FalseLocalSampleInstrumentation"); 1995 assertNotNull(cn); 1996 assertNotNull(mContext); 1997 // If the target instrumentation is wrong, the function should return false. 1998 assertFalse(mContext.startInstrumentation(cn, null, null)); 1999 } 2000 bindExpectResult(Context context, Intent service)2001 private void bindExpectResult(Context context, Intent service) 2002 throws InterruptedException { 2003 if (service == null) { 2004 fail("No service created!"); 2005 } 2006 TestConnection conn = new TestConnection(true, false); 2007 2008 context.bindService(service, conn, Context.BIND_AUTO_CREATE); 2009 context.startService(service); 2010 2011 // Wait for a short time, so the service related operations could be 2012 // working. 2013 synchronized (this) { 2014 wait(2500); 2015 } 2016 // Test stop Service 2017 assertTrue(context.stopService(service)); 2018 context.unbindService(conn); 2019 2020 synchronized (this) { 2021 wait(1000); 2022 } 2023 } 2024 2025 private interface Condition { onCondition()2026 public boolean onCondition(); 2027 } 2028 waitForCondition(Condition con)2029 private synchronized void waitForCondition(Condition con) throws InterruptedException { 2030 // check the condition every 1 second until the condition is fulfilled 2031 // and wait for 3 seconds at most 2032 for (int i = 0; !con.onCondition() && i <= 3; i++) { 2033 wait(1000); 2034 } 2035 } 2036 waitForReceiveBroadCast(final ResultReceiver receiver)2037 private void waitForReceiveBroadCast(final ResultReceiver receiver) 2038 throws InterruptedException { 2039 Condition con = new Condition() { 2040 public boolean onCondition() { 2041 return receiver.hasReceivedBroadCast(); 2042 } 2043 }; 2044 waitForCondition(con); 2045 } 2046 waitForFilteredIntent(Context context, final String action)2047 private void waitForFilteredIntent(Context context, final String action) 2048 throws InterruptedException { 2049 context.sendBroadcast(new Intent(action), null); 2050 2051 synchronized (mLockObj) { 2052 mLockObj.wait(BROADCAST_TIMEOUT); 2053 } 2054 } 2055 2056 private final class TestBroadcastReceiver extends BroadcastReceiver { 2057 boolean mHadReceivedBroadCast; 2058 boolean mIsOrderedBroadcasts; 2059 2060 @Override onReceive(Context context, Intent intent)2061 public void onReceive(Context context, Intent intent) { 2062 synchronized (this) { 2063 if (mIsOrderedBroadcasts) { 2064 setResultCode(3); 2065 setResultData(ACTUAL_RESULT); 2066 } 2067 2068 Bundle map = getResultExtras(false); 2069 if (map != null) { 2070 map.remove(KEY_REMOVED); 2071 map.putString(KEY_ADDED, VALUE_ADDED); 2072 } 2073 mHadReceivedBroadCast = true; 2074 this.notifyAll(); 2075 } 2076 2077 synchronized (mLockObj) { 2078 mLockObj.notify(); 2079 } 2080 } 2081 hadReceivedBroadCast()2082 boolean hadReceivedBroadCast() { 2083 return mHadReceivedBroadCast; 2084 } 2085 reset()2086 void reset(){ 2087 mHadReceivedBroadCast = false; 2088 } 2089 } 2090 2091 private class FilteredReceiver extends BroadcastReceiver { 2092 private boolean mHadReceivedBroadCast1 = false; 2093 private boolean mHadReceivedBroadCast2 = false; 2094 onReceive(Context context, Intent intent)2095 public void onReceive(Context context, Intent intent) { 2096 String action = intent.getAction(); 2097 if (MOCK_ACTION1.equals(action)) { 2098 mHadReceivedBroadCast1 = true; 2099 } else if (MOCK_ACTION2.equals(action)) { 2100 mHadReceivedBroadCast2 = true; 2101 } 2102 2103 synchronized (mLockObj) { 2104 mLockObj.notify(); 2105 } 2106 } 2107 hadReceivedBroadCast1()2108 public boolean hadReceivedBroadCast1() { 2109 return mHadReceivedBroadCast1; 2110 } 2111 hadReceivedBroadCast2()2112 public boolean hadReceivedBroadCast2() { 2113 return mHadReceivedBroadCast2; 2114 } 2115 reset()2116 public void reset(){ 2117 mHadReceivedBroadCast1 = false; 2118 mHadReceivedBroadCast2 = false; 2119 } 2120 } 2121 2122 private class TestConnection implements ServiceConnection { TestConnection(boolean expectDisconnect, boolean setReporter)2123 public TestConnection(boolean expectDisconnect, boolean setReporter) { 2124 } 2125 setMonitor(boolean v)2126 void setMonitor(boolean v) { 2127 } 2128 onServiceConnected(ComponentName name, IBinder service)2129 public void onServiceConnected(ComponentName name, IBinder service) { 2130 } 2131 onServiceDisconnected(ComponentName name)2132 public void onServiceDisconnected(ComponentName name) { 2133 } 2134 } 2135 testOpenFileOutput_mustNotCreateWorldReadableFile()2136 public void testOpenFileOutput_mustNotCreateWorldReadableFile() throws Exception { 2137 try { 2138 mContext.openFileOutput("test.txt", Context.MODE_WORLD_READABLE); 2139 fail("Exception expected"); 2140 } catch (SecurityException expected) { 2141 } 2142 } 2143 testOpenFileOutput_mustNotCreateWorldWriteableFile()2144 public void testOpenFileOutput_mustNotCreateWorldWriteableFile() throws Exception { 2145 try { 2146 mContext.openFileOutput("test.txt", Context.MODE_WORLD_WRITEABLE); 2147 fail("Exception expected"); 2148 } catch (SecurityException expected) { 2149 } 2150 } 2151 testOpenFileOutput_mustNotWriteToParentDirectory()2152 public void testOpenFileOutput_mustNotWriteToParentDirectory() throws Exception { 2153 try { 2154 // Created files must be under the application's private directory. 2155 mContext.openFileOutput("../test.txt", Context.MODE_PRIVATE); 2156 fail("Exception expected"); 2157 } catch (IllegalArgumentException expected) { 2158 } 2159 } 2160 testOpenFileOutput_mustNotUseAbsolutePath()2161 public void testOpenFileOutput_mustNotUseAbsolutePath() throws Exception { 2162 try { 2163 // Created files must be under the application's private directory. 2164 mContext.openFileOutput("/tmp/test.txt", Context.MODE_PRIVATE); 2165 fail("Exception expected"); 2166 } catch (IllegalArgumentException expected) { 2167 } 2168 } 2169 isWallpaperSupported()2170 private boolean isWallpaperSupported() { 2171 return WallpaperManager.getInstance(mContext).isWallpaperSupported(); 2172 } 2173 } 2174