android.content.Context

Here are the examples of the java api class android.content.Context taken from open source projects.

1. DigitsClient#startPhoneNumberActivity()

Project: digits-android
Source File: DigitsClient.java
View license
private void startPhoneNumberActivity(Bundle bundle) {
    final Context appContext = digits.getContext();
    final Activity currentActivity = digits.getFabric().getCurrentActivity();
    final Context selectedContext = (currentActivity != null && !currentActivity.isFinishing()) ? currentActivity : appContext;
    final int intentFlags = (currentActivity != null && !currentActivity.isFinishing()) ? 0 : (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final Intent intent = new Intent(selectedContext, digits.getActivityClassManager().getPhoneNumberActivity());
    intent.putExtras(bundle);
    intent.setFlags(intentFlags);
    selectedContext.startActivity(intent);
}

2. DialogUtils#isDialog()

Project: robotium
Source File: DialogUtils.java
View license
/**
	 * Checks that the specified DecorView and the Activity DecorView are not equal.
	 * 
	 * @param activity the activity which DecorView is to be compared
	 * @param decorView the DecorView to compare
	 * @return true if not equal
	 */
private boolean isDialog(Activity activity, View decorView) {
    if (decorView == null || !decorView.isShown() || activity == null) {
        return false;
    }
    Context viewContext = null;
    if (decorView != null) {
        viewContext = decorView.getContext();
    }
    if (viewContext instanceof ContextThemeWrapper) {
        ContextThemeWrapper ctw = (ContextThemeWrapper) viewContext;
        viewContext = ctw.getBaseContext();
    }
    Context activityContext = activity;
    Context activityBaseContext = activity.getBaseContext();
    return (activityContext.equals(viewContext) || activityBaseContext.equals(viewContext)) && (decorView != activity.getWindow().getDecorView());
}

3. KeyguardService#onCreate()

Project: AcDisplay
Source File: KeyguardService.java
View license
@Override
public void onCreate() {
    super.onCreate();
    final Context context = getContext();
    mPackageName = PackageUtils.getName(context);
    mScreenOff = !PowerUtils.isScreenOn(context);
    // Register base receiver that is watching ACTION_SCREEN_ON,
    // ACTION_SCREEN_OFF and does completely nothing except
    // saving the screen off timestamp.
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    // highest priority
    intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
    context.registerReceiver(mScreenReceiver, intentFilter);
}

4. KeyguardService#onStart()

Project: AcDisplay
Source File: KeyguardService.java
View license
@Override
public void onStart(@Nullable Object... objects) {
    final Context context = getContext();
    // Register receiver
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    // highest priority
    intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
    context.registerReceiver(mReceiver, intentFilter);
    if (mScreenOff) {
        // Make sure the app is launched
        mLocked = mPresenter.isLocked();
        performLockWithDelay();
    }
    isActive = true;
}

5. KeyguardService#onStop()

Project: AcDisplay
Source File: KeyguardService.java
View license
@Override
public void onStop(@Nullable Object... objects) {
    final Context context = getContext();
    context.unregisterReceiver(mReceiver);
    stopMonitorThread();
    cancelLockWithDelay();
    if (mScreenOff) {
        // Make sure that the app is not
        // waiting in the shade.
        mPresenter.kill();
    }
    isActive = false;
}

6. InitialTest#startAppFromHomeScreen()

Project: android
Source File: InitialTest.java
View license
/**
     * Start owncloud app
     */
@Test
public void startAppFromHomeScreen() {
    // Perform a short press on the HOME button
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(OWNCLOUD_APP_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(OWNCLOUD_APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

7. InitialTest#startSettingsFromHomeScreen()

Project: android
Source File: InitialTest.java
View license
/**
     * Start Settings app
     *
     * @throws UiObjectNotFoundException
     */
@Test
public void startSettingsFromHomeScreen() throws UiObjectNotFoundException {
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(ANDROID_SETTINGS_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    clickByText(SETTINGS_DATA_USAGE_OPTION);
}

8. ChangeTextBehaviorTest#startMainActivityFromHomeScreen()

View license
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    // Start from the home screen
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the blueprint app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
    // Clear out any previous instances
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

9. UiAutomatorTest#startBlueprintActivityFromHomeScreen()

View license
/**
     * When using UiAutomator you can interact with ui elements outside of your own process.
     * You can start your application by pressing the home button of the device and launch the
     * target app through the android launcher.
     *
     * <p>
     * If you only want to launch and test a single {@link Activity} you can use {@link
     * Instrumentation} directly to only launch the target {@link Activity}
     * </p>
     */
@Before
public void startBlueprintActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    // Start from the home screen
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the blueprint app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
    // Clear out any previous instances
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

10. RatingDialog#rateNow()

Project: AntennaPod
Source File: RatingDialog.java
View license
public static void rateNow() {
    Context context = mContext.get();
    if (context == null) {
        return;
    }
    final String appPackage = "de.danoeh.antennapod";
    final Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    saveRated();
}

11. AbstractClickActivity#launchApp()

View license
/**
     * Launch main intent from package.
     */
public void launchApp() {
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(intent);
}

12. ApplicationServiceSupport#bind()

View license
/**
   * Create the service connection.
   */
public void bind() {
    if (serviceObject != null) {
        return;
    }
    final Context context = contextRef.get();
    if (context == null) {
        return;
    }
    // TODO make it configurable
    final Intent intent = new Intent(context, GoroService.class);
    intent.setAction(getInterfaceClass().getName());
    if (DEBUG_CALLS) {
        Log.v(TAG, "Attempt to bind to service " + this + "/" + context, new RuntimeException());
    }
    // start manually, so that it will be stopped manually
    context.startService(intent);
    final boolean bindResult = context.bindService(intent, this, 0);
    if (DEBUG) {
        Log.v(TAG, "Binded to service: " + bindResult + ", " + context + ", interface: " + getInterfaceClass());
    }
}

13. FrenchToast#unwrapActivity()

Project: frenchtoast
Source File: FrenchToast.java
View license
private static Activity unwrapActivity(Context context) {
    Context appContext = context.getApplicationContext();
    Context unwrapped = context;
    for (; ; ) {
        if (unwrapped instanceof Activity) {
            return (Activity) unwrapped;
        }
        if (unwrapped == null || unwrapped == appContext || !(unwrapped instanceof ContextWrapper)) {
            throw new IllegalArgumentException("Could not find Activity in the chain of wrapped contexts from " + context);
        }
        Context baseContext = ((ContextWrapper) unwrapped).getBaseContext();
        if (baseContext == unwrapped) {
            throw new IllegalArgumentException("Could not find Activity in the chain of wrapped contexts from " + context);
        }
        unwrapped = baseContext;
    }
}

14. UiAutomatorTest#setUp()

View license
@Before
public void setUp() {
    // Get the device instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    assertThat(mDevice, notNullValue());
    // Start from the home screen
    mDevice.pressHome();
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = new Intent().setClassName(APP_PACKAGE, APP_PACKAGE + ".MainActivity").addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
    mContext = InstrumentationRegistry.getTargetContext();
}

15. InitialTest#startAppFromHomeScreen()

View license
/**
     * Start owncloud app
     */
@Test
public void startAppFromHomeScreen() {
    // Perform a short press on the HOME button
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(OWNCLOUD_APP_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(OWNCLOUD_APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

16. InitialTest#startSettingsFromHomeScreen()

View license
/**
     * Start Settings app
     *
     * @throws UiObjectNotFoundException
     */
@Test
public void startSettingsFromHomeScreen() throws UiObjectNotFoundException {
    mDevice.pressHome();
    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(ANDROID_SETTINGS_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    clickByText(SETTINGS_DATA_USAGE_OPTION);
}

17. UiAutomatorTest#setUp()

View license
@Before
public void setUp() {
    // Get the device instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    assertThat(mDevice, notNullValue());
    // Start from the home screen
    mDevice.pressHome();
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    Intent intent = new Intent().setClassName(APP_PACKAGE, APP_PACKAGE + ".MainActivity").addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
    mContext = InstrumentationRegistry.getTargetContext();
}

18. UiAutomatorTest#setUp()

View license
@Before
public void setUp() {
    // Get the device instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    assertThat(mDevice, notNullValue());
    // Start from the home screen
    mDevice.pressHome();
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    Intent intent = new Intent().setClassName(APP_PACKAGE, APP_PACKAGE + ".MainActivity").addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
    mContext = InstrumentationRegistry.getTargetContext();
}

19. AbstractClickActivity#launchApp()

View license
/**
     * Launch main intent from package.
     */
public void launchApp() {
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(intent);
}

20. ActiveModeService#onCreate()

Project: AcDisplay
Source File: ActiveModeService.java
View license
@Override
public void onCreate() {
    Context context = getContext();
    mSensors = buildAvailableSensorsList(context);
    super.onCreate();
    IntentFilter filter = new IntentFilter();
    filter.addAction(App.ACTION_INTERNAL_PING_SENSORS);
    LocalBroadcastManager.getInstance(context).registerReceiver(mLocalReceiver, filter);
    NotificationPresenter.getInstance().registerListener(this);
}

21. ActiveModeService#onStart()

Project: AcDisplay
Source File: ActiveModeService.java
View license
@Override
public void onStart(Object... objects) {
    if (DEBUG)
        Log.d(TAG, "Starting listening to sensors.");
    Context context = getContext();
    SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    for (ActiveModeSensor sensor : mSensors) {
        sensor.registerCallback(this);
        sensor.onAttached(sensorManager, context);
    }
    mActiveChargingEnabled = Config.getInstance().isActiveModeActiveChargingEnabled();
    if (mActiveChargingEnabled) {
        mPluggedAtomic.react(PowerUtils.isPlugged(context));
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        context.registerReceiver(mReceiver, intentFilter);
    }
}

22. KeyguardSettings#onCreate()

Project: AcDisplay
Source File: KeyguardSettings.java
View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Context context = getActivity();
    // Request to grant the keyguard permissions if possible,
    // no need of permissions otherwise (since AcDisplay v3.8).
    PermissionGroup pg = App.getAccessManager().getKeyguardPermissions();
    if (pg.exists(context)) {
        requestMasterSwitch(Config.KEY_KEYGUARD, pg.permissions);
    } else
        requestMasterSwitch(Config.KEY_KEYGUARD);
    addPreferencesFromResource(R.xml.settings_keyguard_fragment);
    syncPreference(Config.KEY_KEYGUARD_RESPECT_INACTIVE_TIME);
    syncPreference(Config.KEY_KEYGUARD_WITHOUT_NOTIFICATIONS);
    syncPreference(Config.KEY_KEYGUARD_LOCK_DELAY, mDelayPreferenceSetter);
}

23. InactiveTimePreference#onDialogClosed()

View license
@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);
    if (!positiveResult) {
        return;
    }
    Context context = getContext();
    Config config = Config.getInstance();
    config.setInactiveTimeFrom(context, mFrom.hours * 60 + mFrom.minutes, null);
    config.setInactiveTimeTo(context, mTo.hours * 60 + mTo.minutes, null);
    config.setInactiveTimeEnabled(context, mEnabled.isChecked(), null);
}

24. ActionBarSherlockCompat#initializePanelMenu()

View license
private boolean initializePanelMenu() {
    //getContext();
    Context context = mActivity;
    // If we have an action bar, initialize the menu with a context themed for it.
    if (wActionBar != null) {
        TypedValue outValue = new TypedValue();
        Resources.Theme currentTheme = context.getTheme();
        currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, outValue, true);
        final int targetThemeRes = outValue.resourceId;
        if (targetThemeRes != 0) /*&& context.getThemeResId() != targetThemeRes*/
        {
            context = new ContextThemeWrapper(context, targetThemeRes);
        }
    }
    mMenu = new MenuBuilder(context);
    mMenu.setCallback(this);
    return true;
}

25. ActionBarSherlockNative#getThemedContext()

View license
@Override
protected Context getThemedContext() {
    Context context = mActivity;
    TypedValue outValue = new TypedValue();
    mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true);
    if (outValue.resourceId != 0) {
        //We are unable to test if this is the same as our current theme
        //so we just wrap it and hope that if the attribute was specified
        //then the user is intentionally specifying an alternate theme.
        context = new ContextThemeWrapper(context, outValue.resourceId);
    }
    return context;
}

26. ListNavigation#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    //Used for theme switching in samples
    setTheme(SampleList.THEME);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_navigation);
    mSelected = (TextView) findViewById(R.id.text);
    mLocations = getResources().getStringArray(R.array.locations);
    Context context = getSupportActionBar().getThemedContext();
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    getSupportActionBar().setListNavigationCallbacks(list, this);
}

27. BaseUrlSpan#onClick()

Project: actor-platform
Source File: BaseUrlSpan.java
View license
@Override
public void onClick(View v) {
    Context ctx = v.getContext();
    Intent intent = buildChromeIntent().intent;
    intent.setData(Uri.parse(getURL()));
    if (intent.resolveActivity(ctx.getPackageManager()) != null) {
        ctx.startActivity(intent);
    } else {
        intent.setData(Uri.parse("http://" + getURL()));
        if (intent.resolveActivity(ctx.getPackageManager()) != null) {
            ctx.startActivity(intent);
        } else {
            Toast.makeText(ctx, "Unknown URL type", Toast.LENGTH_SHORT).show();
        }
    }
}

28. MainActivity#purgeRules()

Project: afwall
Source File: MainActivity.java
View license
/**
	 * Purge iptables rules, showing a visual indication
	 */
private void purgeRules() {
    final Context ctx = getApplicationContext();
    Api.purgeIptables(ctx, true, new RootCommand().setSuccessToast(R.string.rules_deleted).setFailureToast(R.string.error_purge).setReopenShell(true).setCallback(new RootCommand.Callback() {

        public void cbFunc(RootCommand state) {
            // error exit -> assume the rules are still enabled
            // we shouldn't wind up in this situation, but if we do, the user's
            // best bet is to click Apply then toggle Enabled again
            boolean nowEnabled = state.exitCode != 0;
            Api.setEnabled(ctx, nowEnabled, true);
            menuSetApplyOrSave(MainActivity.this.mainMenu, nowEnabled);
        }
    }));
}

29. RepoListFragment#clickableWelcomeMessage()

Project: agit
Source File: RepoListFragment.java
View license
private SpannableStringBuilder clickableWelcomeMessage() {
    SpannableStringBuilder message = new SpannableStringBuilder(getString(welcome_message));
    applyToEntireString(message, new TextAppearanceSpan(getActivity(), R.style.WelcomeText));
    final Context applicationContext = getActivity().getApplicationContext();
    CharacterStyle linkStyle = new ForegroundColorSpan(getResources().getColor(R.color.link_text));
    ClickableText.addLinks(message, linkStyle, new ClickableText.Listener() {

        public void onClick(String command, View widget) {
            if (command.equals("clone")) {
                startActivity(new Intent(applicationContext, CloneLauncherActivity.class));
            }
        }
    });
    return message;
}

30. GetAdvertisingIdTask#doInBackground()

View license
@Override
protected Pair<String, Boolean> doInBackground(Context... contexts) {
    final Context context = contexts[0];
    try {
        Object advertisingInfo = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient").getMethod("getAdvertisingIdInfo", Context.class).invoke(null, context);
        Boolean isLimitAdTrackingEnabled = (Boolean) advertisingInfo.getClass().getMethod("isLimitAdTrackingEnabled").invoke(advertisingInfo);
        if (isLimitAdTrackingEnabled) {
            return Pair.create(null, false);
        }
        String advertisingId = (String) advertisingInfo.getClass().getMethod("getId").invoke(advertisingInfo);
        return Pair.create(advertisingId, true);
    } catch (Exception ignored) {
        return null;
    }
}

31. SegmentIntegrationTest#flushWhenDisconnectedSkipsUpload()

View license
@Test
public void flushWhenDisconnectedSkipsUpload() throws IOException {
    NetworkInfo networkInfo = mock(NetworkInfo.class);
    when(networkInfo.isConnectedOrConnecting()).thenReturn(false);
    ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo);
    Context context = mockApplication();
    when(context.getSystemService(CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);
    Client client = mock(Client.class);
    SegmentIntegration segmentIntegration = new SegmentBuilder().context(context).client(client).build();
    segmentIntegration.submitFlush();
    verify(client, never()).upload();
}

32. SegmentIntegrationTest#flushWhenQueueSizeIsLessThanOneSkipsUpload()

View license
@Test
public void flushWhenQueueSizeIsLessThanOneSkipsUpload() throws IOException {
    PayloadQueue payloadQueue = mock(PayloadQueue.class);
    when(payloadQueue.size()).thenReturn(0);
    Context context = mockApplication();
    Client client = mock(Client.class);
    SegmentIntegration segmentIntegration = //
    new SegmentBuilder().payloadQueue(payloadQueue).context(context).client(client).build();
    segmentIntegration.submitFlush();
    verifyZeroInteractions(context);
    verify(client, never()).upload();
}

33. CommentsFragment#onOptionsItemSelected()

Project: andlytics
Source File: CommentsFragment.java
View license
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Context ctx = getActivity();
    if (ctx == null) {
        return false;
    }
    switch(item.getItemId()) {
        case R.id.itemCommentsmenuRefresh:
            refreshComments();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

34. TaskRetainerFragment#setTask()

Project: android
Source File: TaskRetainerFragment.java
View license
/**
     * Sets the task to retain across configuration changes
     *
     * @param task  Task to retain
     */
public void setTask(CopyAndUploadContentUrisTask task) {
    if (mTask != null) {
        mTask.setListener(null);
    }
    mTask = task;
    Context context = getContext();
    if (mTask != null && context != null) {
        if (context instanceof ReceiveExternalFilesActivity) {
            task.setListener((CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener) context);
        } else {
            task.setListener(null);
        }
    }
}

35. AutofitHelper#setTextSize()

View license
/**
     * Set the original text size of the View.
     *
     * @see TextView#setTextSize(int, float)
     */
public void setTextSize(int unit, float size) {
    if (mIsAutofitting) {
        // since it'd get set to the autofitTextSize
        return;
    }
    Context context = mTextView.getContext();
    Resources r = Resources.getSystem();
    if (context != null) {
        r = context.getResources();
    }
    setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()));
}

36. DetailActivityTest#characterCollectionsDisplayed()

View license
@Test
public void characterCollectionsDisplayed() {
    Character mockCharacter = MockModelFabric.makeMockCharacter();
    Intent intent = DetailActivity.getStartIntent(InstrumentationRegistry.getContext(), mockCharacter);
    main.launchActivity(intent);
    Context context = InstrumentationRegistry.getTargetContext();
    String[] tabTitles = context.getResources().getStringArray(R.array.detail_fragment_titles);
    checkTextIsShownInTab(tabTitles[0], mockCharacter.films);
    checkTextIsShownInTab(tabTitles[1], mockCharacter.vehicles);
    checkTextIsShownInTab(tabTitles[2], mockCharacter.species);
    checkTextIsShownInTab(tabTitles[3], mockCharacter.starships);
}

37. MainActivityTest#loadCharactersShowsCharactersFeed()

View license
@Test
public void loadCharactersShowsCharactersFeed() {
    Context context = InstrumentationRegistry.getTargetContext();
    int[] characterIds = context.getResources().getIntArray(R.array.characters);
    List<Character> mockCharacters = MockModelFabric.makeListOfMockCharacters(characterIds.length);
    stubMockCharacters(Observable.just(mockCharacters));
    main.launchActivity(null);
    try {
        Thread.sleep(2000);
    } catch (InterruptedException error) {
        Timber.e(error, "Interrupted exception occurred");
    }
    checkCharactersDisplayOnRecyclerView(mockCharacters);
}

38. MainActivityTest#characterScreenOpensWhenClickingOnCard()

View license
@Test
public void characterScreenOpensWhenClickingOnCard() {
    Context context = InstrumentationRegistry.getTargetContext();
    int[] characterIds = context.getResources().getIntArray(R.array.characters);
    List<Character> mockCharacters = MockModelFabric.makeListOfMockCharacters(characterIds.length);
    stubMockCharacters(Observable.just(mockCharacters));
    main.launchActivity(null);
    onView(withText(mockCharacters.get(0).name)).perform(click());
    onView(withText(com.hitherejoe.androidboilerplate.R.string.text_lorem_ipsum)).check(matches(isDisplayed()));
}

39. DetailAdapter#onBindViewHolder()

View license
@Override
public void onBindViewHolder(final DetailHolder holder, final int position) {
    final Context context = holder.itemView.getContext();
    final String detail = mDetails.get(position);
    holder.detailText.setText(detail);
    holder.detailText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(detail)));
        }
    });
}

40. CostItemAdapter#onCreateViewHolder()

View license
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);
    // check if this should be an expanded card
    if (viewType == ViewType.EXPANDED_CARD.ordinal()) {
        View view = inflater.inflate(R.layout.card_expanded_daily_cost_item, parent, false);
        return new ExpandedViewHolder(view, this);
    }
    // this is a normal/contracted card
    View view = inflater.inflate(R.layout.card_daily_cost_item, parent, false);
    return new ViewHolder(view, this);
}

41. FlipView#init()

Project: android-FlipView
Source File: FlipView.java
View license
private void init() {
    final Context context = getContext();
    final ViewConfiguration configuration = ViewConfiguration.get(context);
    mScroller = new Scroller(context, flipInterpolator);
    mTouchSlop = configuration.getScaledPagingTouchSlop();
    mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
    mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
    mShadowPaint.setColor(Color.BLACK);
    mShadowPaint.setStyle(Style.FILL);
    mShadePaint.setColor(Color.BLACK);
    mShadePaint.setStyle(Style.FILL);
    mShinePaint.setColor(Color.WHITE);
    mShinePaint.setStyle(Style.FILL);
}

42. FloatingActionsMenu#createLabels()

View license
private void createLabels() {
    Context context = new ContextThemeWrapper(getContext(), mLabelsStyle);
    for (int i = 0; i < mButtonsCount; i++) {
        FloatingActionButton button = (FloatingActionButton) getChildAt(i);
        String title = button.getTitle();
        if (button == mAddButton || title == null || button.getTag(R.id.fab_label) != null)
            continue;
        TextView label = new TextView(context);
        label.setTextAppearance(getContext(), mLabelsStyle);
        label.setText(button.getTitle());
        addView(label);
        button.setTag(R.id.fab_label, label);
    }
}

43. StepperLayout#init()

View license
private void init(AttributeSet attrs, @AttrRes int defStyleAttr) {
    initDefaultValues();
    extractValuesFromAttributes(attrs, defStyleAttr);
    final Context context = getContext();
    LayoutInflater.from(context).inflate(R.layout.ms_stepper_layout, this, true);
    bindViews();
    mPager.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return true;
        }
    });
    initNavigation();
    mDottedProgressBar.setVisibility(GONE);
    mProgressBar.setVisibility(GONE);
    mTabsContainer.setVisibility(GONE);
    mStepperType = StepperTypeFactory.createType(mTypeIdentifier, this);
}

44. Focus2AndroidTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    mFocusFinder = FocusFinder.getInstance();
    // inflate the layout
    final Context context = getContext();
    final LayoutInflater inflater = LayoutInflater.from(context);
    mRoot = (ViewGroup) inflater.inflate(R.layout.focus_2, null);
    // manually measure it, and lay it out
    mRoot.measure(500, 500);
    mRoot.layout(0, 0, 500, 500);
    mLeftButton = (Button) mRoot.findViewById(R.id.leftButton);
    mCenterButton = (Button) mRoot.findViewById(R.id.centerButton);
    mRightButton = (Button) mRoot.findViewById(R.id.rightButton);
}

45. FontCache#setFont()

Project: Android-Next
Source File: FontCache.java
View license
public void setFont(TextView tv, String fontName, boolean useCache) {
    if (TextUtils.isEmpty(fontName)) {
        return;
    }
    Context context = tv.getContext();
    Typeface typeface;
    if (useCache) {
        typeface = mCache.get(fontName);
        if (typeface == null) {
            typeface = Typeface.createFromAsset(context.getAssets(), fontName);
            mCache.put(fontName, typeface);
        }
    } else {
        typeface = Typeface.createFromAsset(tv.getContext().getAssets(), fontName);
    }
    tv.setTypeface(typeface);
}

46. AboutDfuPreference#onClick()

View license
@Override
protected void onClick() {
    final Context context = getContext();
    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.sdk52.v0.9.1%2Fexamples_ble_dfu.html&cp=4_0_0_4_2"));
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // is browser installed?
    if (intent.resolveActivity(context.getPackageManager()) != null)
        context.startActivity(intent);
    else {
        Toast.makeText(getContext(), R.string.no_application, Toast.LENGTH_LONG).show();
    }
}

47. MediaStoreBucketsAsyncTask#doInBackground()

View license
@Override
protected List<MediaStoreBucket> doInBackground(Void... params) {
    ArrayList<MediaStoreBucket> result = null;
    Context context = mContext.get();
    if (null != context) {
        // Add 'All Photos' item
        result = new ArrayList<MediaStoreBucket>();
        result.add(MediaStoreBucket.getAllPhotosBucket(context));
        Cursor cursor = MediaStoreCursorHelper.openPhotosCursor(context, MediaStoreCursorHelper.MEDIA_STORE_CONTENT_URI);
        if (null != cursor) {
            MediaStoreCursorHelper.photosCursorToBucketList(cursor, result);
            cursor.close();
        }
    } else {
    }
    return result;
}

48. HQVisualizerFragment#setupViews()

View license
private void setupViews() {
    HQVisualizerStateStore state = getStateStore();
    Context context = getActivity();
    mDuringSetupViews = true;
    mToggleButtonEnableWaveform.setChecked(state.isCaptureWaveformEnabled());
    mToggleButtonEnableFft.setChecked(state.isCaptureFftEnabled());
    {
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.hq_visualizer_window_type_names, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerWindowType.setAdapter(adapter);
    }
    mSpinnerWindowType.setSelection(windowTypeToListPosition(state.getWindowType()));
    mDuringSetupViews = false;
}

49. PresetReverbFragment#setupViews()

View license
private void setupViews() {
    Context context = getActivity();
    PresetReverbStateStore state = getAppController().getPresetReverbStateStore();
    {
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.aux_preset_reverb_preset_names, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerPreset.setAdapter(adapter);
    }
    mSpinnerPreset.setSelection(state.getSettings().preset);
}

50. VisualizerFragment#setupViews()

View license
private void setupViews() {
    VisualizerStateStore state = getStateStore();
    Context context = getActivity();
    mDuringSetupViews = true;
    mToggleButtonEnableWaveform.setChecked(state.isCaptureWaveformEnabled());
    mToggleButtonEnableFft.setChecked(state.isCaptureFftEnabled());
    mToggleButtonEnablePeak.setChecked(state.isMeasurementPeakEnabled());
    mToggleButtonEnableRms.setChecked(state.isMeasurementRmsEnabled());
    {
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.visualizer_scaling_mode_names, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerScalingMode.setAdapter(adapter);
    }
    mSpinnerScalingMode.setSelection(state.getScalingMode());
    mDuringSetupViews = false;
}

51. PluginLoader#getDefaultPluginContext()

View license
/**
	 * ????class?????Context
	 * ??????1?DefaultContext,
	 * ????????class???Context
	 * 
	 * @param clazz
	 * @return
	 */
public static Context getDefaultPluginContext(@SuppressWarnings("rawtypes") Class clazz) {
    Context pluginContext = null;
    PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(clazz.getName());
    if (pluginDescriptor != null) {
        pluginContext = PluginLauncher.instance().getRunningPlugin(pluginDescriptor.getPackageName()).pluginContext;
        ;
    } else {
        LogUtil.e("PluginDescriptor Not Found for ", clazz.getName());
    }
    if (pluginContext == null) {
        LogUtil.e("Context Not Found for ", clazz.getName());
    }
    return pluginContext;
}

52. PluginTestApplication#onCreate()

View license
@Override
public void onCreate() {
    super.onCreate();
    Context ctx = getApplicationContext();
    Log.d("xx", "" + ctx);
    if (isApplicationProcess()) {
        LogUtil.d("api??????????????????");
    }
}

53. RateThisAppTest#shouldRateDialogIfNeeded_LaunchTimeIsCorrect()

View license
@Test
public void shouldRateDialogIfNeeded_LaunchTimeIsCorrect() {
    Context context = RuntimeEnvironment.application.getApplicationContext();
    RateThisApp.init(new RateThisApp.Config(1, 3));
    RateThisApp.onStart(context);
    Assert.assertFalse(RateThisApp.shouldShowRateDialog());
    RateThisApp.onStart(context);
    Assert.assertFalse(RateThisApp.shouldShowRateDialog());
    RateThisApp.onStart(context);
    Assert.assertTrue(RateThisApp.shouldShowRateDialog());
    RateThisApp.onStart(context);
    Assert.assertTrue(RateThisApp.shouldShowRateDialog());
}

54. HorizontalRTToolbar#getFontColorItems()

View license
private SpinnerItems<FontColorSpinnerItem> getFontColorItems() {
    SpinnerItems<FontColorSpinnerItem> spinnerItems = new SpinnerItems<FontColorSpinnerItem>();
    Context context = getContext();
    // empty color
    String name = context.getString(R.string.rte_toolbar_color_text);
    FontColorSpinnerItem spinnerItem = new FontColorSpinnerItem(mCustomColorFont, name, true, false);
    spinnerItems.add(spinnerItem);
    // regular colors
    for (String fontColor : getResources().getStringArray(R.array.rte_toolbar_fontcolors_values)) {
        int color = Integer.parseInt(fontColor, 16);
        spinnerItem = new FontColorSpinnerItem(color, name, false, false);
        spinnerItems.add(spinnerItem);
    }
    // custom color
    name = context.getString(R.string.rte_toolbar_color_custom);
    spinnerItem = new FontColorSpinnerItem(mCustomColorFont, name, false, true);
    spinnerItems.add(spinnerItem);
    return spinnerItems;
}

55. HorizontalRTToolbar#getBGColorItems()

View license
private SpinnerItems<BGColorSpinnerItem> getBGColorItems() {
    SpinnerItems<BGColorSpinnerItem> spinnerItems = new SpinnerItems<BGColorSpinnerItem>();
    Context context = getContext();
    // empty color
    String name = context.getString(R.string.rte_toolbar_color_text);
    BGColorSpinnerItem spinnerItem = new BGColorSpinnerItem(mCustomColorFont, name, true, false);
    spinnerItems.add(spinnerItem);
    // regular colors
    for (String fontColor : getResources().getStringArray(R.array.rte_toolbar_fontcolors_values)) {
        int color = Integer.parseInt(fontColor, 16);
        spinnerItem = new BGColorSpinnerItem(color, name, false, false);
        spinnerItems.add(spinnerItem);
    }
    // custom color
    name = context.getString(R.string.rte_toolbar_color_custom);
    spinnerItem = new BGColorSpinnerItem(mCustomColorFont, name, false, true);
    spinnerItems.add(spinnerItem);
    return spinnerItems;
}

56. SampleAdapter#onBindViewHolder()

View license
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Context context = holder.itemView.getContext();
    ScalableType scalableType = ScalableType.values()[position];
    holder.mTextView.setText(context.getString(R.string.sample_scale_title, position, scalableType.toString()));
    holder.mImageView.setImageResource(mImageResId);
    holder.mImageView.setScalableType(scalableType);
    holder.mImageView.requestLayout();
}

57. StorageTestCase#setUp()

View license
@Override
protected void setUp() throws Exception {
    Context context = getInstrumentation().getContext();
    // set a storage
    mStorage = null;
    if (SimpleStorage.isExternalStorageWritable()) {
        mStorage = SimpleStorage.getExternalStorage();
    } else {
        mStorage = SimpleStorage.getInternalStorage(context);
    }
}

58. SlidingLayer#init()

View license
private void init() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        setLayerType(LAYER_TYPE_HARDWARE, null);
    }
    setWillNotDraw(false);
    setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
    setFocusable(true);
    final Context context = getContext();
    mScroller = new Scroller(context, sMenuInterpolator);
    final ViewConfiguration configuration = ViewConfiguration.get(context);
    mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
    mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
    final float density = context.getResources().getDisplayMetrics().density;
    mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
    mRandom = new Random();
}

59. SSLTestActivity#testHttpsUrlPinned()

View license
private InputStream testHttpsUrlPinned() throws IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, KeyStoreException {
    URL url = new URL("https://10.0.2.2");
    Context context = this.getApplicationContext();
    AssetManager assetManager = context.getAssets();
    InputStream keyStoreInputStream = assetManager.open("tentwo.store");
    KeyStore trustStore = KeyStore.getInstance("BKS");
    trustStore.load(keyStoreInputStream, "password".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);
    //HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    //for now for testing
    HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    Log.i(TAG, "hostnameverifier is: " + urlConnection.getHostnameVerifier().getClass().getName());
    return urlConnection.getInputStream();
}

60. MyPreferenceFragment#testDynamicPrefs()

View license
private void testDynamicPrefs() {
    // this is the material styled context
    final Context ctx = getPreferenceManager().getContext();
    final PreferenceCategory dynamicCategory = (PreferenceCategory) findPreference("pref_categ");
    Preference prefAdd = findPreference("pref_add");
    prefAdd.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        private int n = 0;

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference newPreference = new Preference(ctx);
            newPreference.setTitle("New preference " + n++);
            newPreference.setSummary(Long.toString(System.currentTimeMillis()));
            dynamicCategory.addPreference(newPreference);
            return true;
        }
    });
}

61. SelectItemQuizView#createQuizContentView()

View license
@Override
protected View createQuizContentView() {
    Context context = getContext();
    mListView = new ListView(context);
    mListView.setDivider(null);
    mListView.setSelector(R.drawable.selector_button);
    mListView.setAdapter(new OptionsQuizAdapter(getQuiz().getOptions(), R.layout.item_answer_start, context, true));
    mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            allowAnswer();
            toggleAnswerFor(position);
        }
    });
    return mListView;
}

62. GooglyEyesActivity#createCameraSource()

View license
//==============================================================================================
// Camera Source
//==============================================================================================
/**
     * Creates the face detector and the camera.
     */
private void createCameraSource() {
    Context context = getApplicationContext();
    FaceDetector detector = createFaceDetector(context);
    int facing = CameraSource.CAMERA_FACING_FRONT;
    if (!mIsFrontFacing) {
        facing = CameraSource.CAMERA_FACING_BACK;
    }
    // The camera source is initialized to use either the front or rear facing camera.  We use a
    // relatively low resolution for the camera preview, since this is sufficient for this app
    // and the face detector will run faster at lower camera resolutions.
    //
    // However, note that there is a speed/accuracy trade-off with respect to choosing the
    // camera resolution.  The face detector will run faster with lower camera resolutions,
    // but may miss smaller faces, landmarks, or may not correctly detect eyes open/closed in
    // comparison to using higher camera resolutions.  If you have any of these issues, you may
    // want to increase the resolution.
    mCameraSource = new CameraSource.Builder(context, detector).setFacing(facing).setRequestedPreviewSize(320, 240).setRequestedFps(60.0f).setAutoFocusEnabled(true).build();
}

63. AboutFragment#onCreateView()

Project: androidclient
Source File: AboutFragment.java
View license
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.about_about, container, false);
    Context parent = getActivity();
    if (parent != null) {
        TextView txtVersion = (TextView) view.findViewById(R.id.version);
        txtVersion.setText(SystemUtils.getVersionFullName(parent));
    }
    view.findViewById(R.id.button_twitter).setOnClickListener(this);
    view.findViewById(R.id.button_googleplus).setOnClickListener(this);
    view.findViewById(R.id.button_facebook).setOnClickListener(this);
    view.findViewById(R.id.button_identica).setOnClickListener(this);
    return view;
}

64. ConversationListFragment#startQuery()

View license
public void startQuery() {
    Cursor c = null;
    Context ctx = getActivity();
    if (ctx != null) {
        try {
            c = Conversation.startQuery(ctx);
        } catch (SQLiteException e) {
            Log.e(TAG, "query error", e);
        }
    }
    mQueryHandler.onQueryComplete(THREAD_LIST_QUERY_TOKEN, null, c);
}

65. VCardContentView#bind()

Project: androidclient
Source File: VCardContentView.java
View license
@Override
public void bind(long id, VCardComponent component, Pattern highlight) {
    mComponent = component;
    Context context = getContext();
    String size = Preferences.getFontSize(context);
    int sizeId;
    if (size.equals("small"))
        sizeId = android.R.style.TextAppearance_Small;
    else if (size.equals("large"))
        sizeId = android.R.style.TextAppearance_Large;
    else
        sizeId = android.R.style.TextAppearance;
    setTextAppearance(context, sizeId);
    String text = CompositeMessage.getSampleTextContent(component.getMime());
    setText(text);
}

66. system#isDebuggable()

Project: AndroidQuickUtils
Source File: system.java
View license
/**
     * Is this APK signed or is it a Debug build?
     *
     * @return true if it is not signed
     */
public static boolean isDebuggable() {
    boolean debuggable = false;
    Context ctx = QuickUtils.getContext();
    try {
        PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
        Signature signatures[] = pinfo.signatures;
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        for (int i = 0; i < signatures.length; i++) {
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable)
                break;
        }
    } catch (NameNotFoundExceptionCertificateException |  ignored) {
    }
    return debuggable;
}

67. CardPresenter#onCreateViewHolder()

View license
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
    Context context = parent.getContext();
    mDefaultBackgroundColor = ContextCompat.getColor(context, R.color.primary);
    mSelectedBackgroundColor = ContextCompat.getColor(context, R.color.primary_dark);
    mDefaultCardImage = ContextCompat.getDrawable(context, R.drawable.card_default);
    ImageCardView cardView = new ImageCardView(parent.getContext()) {

        @Override
        public void setSelected(boolean selected) {
            updateCardBackgroundColor(this, selected);
            super.setSelected(selected);
        }
    };
    cardView.setFocusable(true);
    cardView.setFocusableInTouchMode(true);
    updateCardBackgroundColor(cardView, false);
    return new ViewHolder(cardView);
}

68. AnnotationActivityManagerTest#testExecute()

View license
@Test
public void testExecute() throws Exception {
    // Given
    TestObject testObject = new TestObject();
    Context context = new Application();
    manager.activityField = testObject.getClass().getDeclaredField("activity");
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.activity).isNotNull();
    assertThat(testObject.activity.created).isTrue();
    verify(androidUnitTest).setActivityController(any(ActivityController.class));
}

69. AnnotationActivityManagerTest#testExecuteState()

View license
@Test
public void testExecuteState() throws Exception {
    // Given
    TestObjectState testObject = new TestObjectState();
    Context context = new Application();
    manager.activityField = testObject.getClass().getDeclaredField("activity");
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.activity).isNotNull();
    assertThat(testObject.activity.created).isTrue();
    assertThat(testObject.activity.started).isTrue();
    assertThat(testObject.activity.resumed).isTrue();
    verify(androidUnitTest).setActivityController(any(ActivityController.class));
}

70. AnnotationFragmentManagerTest#testExecute()

View license
@Test
public void testExecute() throws Exception {
    // Given
    TestObject testObject = new TestObject();
    Context context = new Application();
    manager.fragmentFields.add(testObject.getClass().getDeclaredField("fragment1"));
    manager.fragmentFields.add(testObject.getClass().getDeclaredField("fragment2"));
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.fragment1).isNotNull();
    assertThat(testObject.fragment2).isNotNull();
}

71. AnnotationViewManagerTest#testExecute()

View license
@Test
public void testExecute() throws Exception {
    // Given
    TestObject testObject = new TestObject();
    Context context = new Application();
    manager.fields.add(testObject.getClass().getDeclaredField("view1"));
    manager.fields.add(testObject.getClass().getDeclaredField("view2"));
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.view1).isNotNull();
    assertThat(testObject.view2).isNotNull();
}

72. AppLinkData#fetchDeferredAppLinkData()

Project: ANE-Facebook
Source File: AppLinkData.java
View license
/**
     * Asynchronously fetches app link information that might have been stored for use
     * after installation of the app
     * @param context The context
     * @param applicationId Facebook application Id. If null, it is taken from the manifest
     * @param completionHandler CompletionHandler to be notified with the AppLinkData object or null if none is
     *                          available.  Must not be null.
     */
public static void fetchDeferredAppLinkData(Context context, String applicationId, final CompletionHandler completionHandler) {
    Validate.notNull(context, "context");
    Validate.notNull(completionHandler, "completionHandler");
    if (applicationId == null) {
        applicationId = Utility.getMetadataApplicationId(context);
    }
    Validate.notNull(applicationId, "applicationId");
    final Context applicationContext = context.getApplicationContext();
    final String applicationIdCopy = applicationId;
    Settings.getExecutor().execute(new Runnable() {

        @Override
        public void run() {
            fetchDeferredAppLinkFromServer(applicationContext, applicationIdCopy, completionHandler);
        }
    });
}

73. Settings#publishInstallAsync()

Project: ANE-Facebook
Source File: Settings.java
View license
static void publishInstallAsync(final Context context, final String applicationId, final Request.Callback callback) {
    // grab the application context ahead of time, since we will return to the caller immediately.
    final Context applicationContext = context.getApplicationContext();
    Settings.getExecutor().execute(new Runnable() {

        @Override
        public void run() {
            final Response response = Settings.publishInstallAndWaitForResponse(applicationContext, applicationId, false);
            if (callback != null) {
                // invoke the callback on the main thread.
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onCompleted(response);
                    }
                });
            }
        }
    });
}

74. Sound#configureVideo()

Project: Anki-Android
Source File: Sound.java
View license
private static void configureVideo(VideoView videoView, int videoWidth, int videoHeight) {
    // get the display
    Context context = AnkiDroidApp.getInstance().getApplicationContext();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    // adjust the size of the video so it fits on the screen
    float videoProportion = (float) videoWidth / (float) videoHeight;
    int screenWidth = display.getWidth();
    int screenHeight = display.getHeight();
    float screenProportion = (float) screenWidth / (float) screenHeight;
    android.view.ViewGroup.LayoutParams lp = videoView.getLayoutParams();
    if (videoProportion > screenProportion) {
        lp.width = screenWidth;
        lp.height = (int) ((float) screenWidth / videoProportion);
    } else {
        lp.width = (int) (videoProportion * (float) screenHeight);
        lp.height = screenHeight;
    }
    videoView.setLayoutParams(lp);
}

75. VersionUtils#getAppName()

Project: Anki-Android
Source File: VersionUtils.java
View license
/**
     * Get package name as defined in the manifest.
     */
public static String getAppName() {
    String pkgName = AnkiDroidApp.TAG;
    Context context = AnkiDroidApp.getInstance();
    try {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        pkgName = context.getString(pInfo.applicationInfo.labelRes);
    } catch (PackageManager.NameNotFoundException e) {
        Timber.e(e, "Couldn't find package named %s", context.getPackageName());
    }
    return pkgName;
}

76. VersionUtils#getPkgVersionName()

Project: Anki-Android
Source File: VersionUtils.java
View license
/**
     * Get the package versionName as defined in the manifest.
     */
public static String getPkgVersionName() {
    String pkgVersion = "?";
    Context context = AnkiDroidApp.getInstance();
    if (context != null) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            pkgVersion = pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Timber.e(e, "Couldn't find package named %s", context.getPackageName());
        }
    }
    return pkgVersion;
}

77. FeedHandlerTest#setUp()

Project: AntennaPod
Source File: FeedHandlerTest.java
View license
protected void setUp() throws Exception {
    super.setUp();
    Context context = getInstrumentation().getContext();
    File destDir = context.getExternalFilesDir(FEEDS_DIR);
    assertNotNull(destDir);
    file = new File(destDir, "feed.xml");
    file.delete();
    assertNotNull(file);
    assertFalse(file.exists());
    outputStream = new FileOutputStream(file);
}

78. PlaybackServiceMediaPlayerTest#writeTestPlayable()

View license
private Playable writeTestPlayable(String downloadUrl, String fileUrl) {
    final Context c = getInstrumentation().getTargetContext();
    Feed f = new Feed(0, null, "f", "l", "d", null, null, null, null, "i", null, null, "l", false);
    FeedPreferences prefs = new FeedPreferences(f.getId(), false, FeedPreferences.AutoDeleteAction.NO, null, null);
    f.setPreferences(prefs);
    f.setItems(new ArrayList<>());
    FeedItem i = new FeedItem(0, "t", "i", "l", new Date(), FeedItem.UNPLAYED, f);
    f.getItems().add(i);
    FeedMedia media = new FeedMedia(0, i, 0, 0, 0, "audio/wav", fileUrl, downloadUrl, fileUrl != null, null, 0, 0);
    i.setMedia(media);
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(f);
    assertTrue(media.getId() != 0);
    adapter.close();
    return media;
}

79. PlaybackServiceTaskManagerTest#writeTestQueue()

View license
private List<FeedItem> writeTestQueue(String pref) {
    final Context c = getInstrumentation().getTargetContext();
    final int NUM_ITEMS = 10;
    Feed f = new Feed(0, null, "title", "link", "d", null, null, null, null, "id", null, "null", "url", false);
    f.setItems(new ArrayList<>());
    for (int i = 0; i < NUM_ITEMS; i++) {
        f.getItems().add(new FeedItem(0, pref + i, pref + i, "link", new Date(), FeedItem.PLAYED, f));
    }
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(f);
    adapter.setQueue(f.getItems());
    adapter.close();
    for (FeedItem item : f.getItems()) {
        assertTrue(item.getId() != 0);
    }
    return f.getItems();
}

80. PlaybackServiceTaskManagerTest#testGetQueueWriteBeforeCreation()

View license
public void testGetQueueWriteBeforeCreation() throws InterruptedException {
    final Context c = getInstrumentation().getTargetContext();
    List<FeedItem> queue = writeTestQueue("a");
    assertNotNull(queue);
    PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM);
    List<FeedItem> testQueue = pstm.getQueue();
    assertNotNull(testQueue);
    assertTrue(queue.size() == testQueue.size());
    for (int i = 0; i < queue.size(); i++) {
        assertTrue(queue.get(i).getId() == testQueue.get(i).getId());
    }
    pstm.shutdown();
}

81. PlaybackServiceTaskManagerTest#testCancelAllTasksAllTasksStarted()

View license
public void testCancelAllTasksAllTasksStarted() {
    final Context c = getInstrumentation().getTargetContext();
    PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM);
    pstm.startWidgetUpdater();
    pstm.startPositionSaver();
    pstm.setSleepTimer(100000, false, false);
    pstm.cancelAllTasks();
    assertFalse(pstm.isPositionSaverActive());
    assertFalse(pstm.isWidgetUpdaterActive());
    assertFalse(pstm.isSleepTimerActive());
    pstm.shutdown();
}

82. DBReaderTest#testLoadFeedDataOfFeedItemlist()

Project: AntennaPod
Source File: DBReaderTest.java
View license
public void testLoadFeedDataOfFeedItemlist() {
    final Context context = getInstrumentation().getTargetContext();
    final int numFeeds = 10;
    final int numItems = 1;
    List<Feed> feeds = saveFeedlist(numFeeds, numItems, false);
    List<FeedItem> items = new ArrayList<>();
    for (Feed f : feeds) {
        for (FeedItem item : f.getItems()) {
            item.setFeed(null);
            item.setFeedId(f.getId());
            items.add(item);
        }
    }
    DBReader.loadAdditionalFeedItemListData(items);
    for (int i = 0; i < numFeeds; i++) {
        for (int j = 0; j < numItems; j++) {
            FeedItem item = feeds.get(i).getItems().get(j);
            assertNotNull(item.getFeed());
            assertTrue(item.getFeed().getId() == feeds.get(i).getId());
            assertTrue(item.getFeedId() == item.getFeed().getId());
        }
    }
}

83. DBWriterTest#tearDown()

Project: AntennaPod
Source File: DBWriterTest.java
View license
@Override
protected void tearDown() throws Exception {
    super.tearDown();
    assertTrue(PodDBAdapter.deleteDatabase());
    final Context context = getInstrumentation().getTargetContext();
    File testDir = context.getExternalFilesDir(TEST_FOLDER);
    assertNotNull(testDir);
    for (File f : testDir.listFiles()) {
        f.delete();
    }
}

84. DBWriterTest#playbackHistorySetup()

Project: AntennaPod
Source File: DBWriterTest.java
View license
private FeedMedia playbackHistorySetup(Date playbackCompletionDate) {
    final Context context = getInstrumentation().getTargetContext();
    Feed feed = new Feed("url", null, "title");
    feed.setItems(new ArrayList<FeedItem>());
    FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed);
    FeedMedia media = new FeedMedia(0, item, 10, 0, 1, "mime", null, "url", false, playbackCompletionDate, 0, 0);
    feed.getItems().add(item);
    item.setMedia(media);
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(feed);
    adapter.close();
    assertTrue(media.getId() != 0);
    return media;
}

85. DBWriterTest#testAddQueueItemSingleItem()

Project: AntennaPod
Source File: DBWriterTest.java
View license
public void testAddQueueItemSingleItem() throws InterruptedException, ExecutionException, TimeoutException {
    final Context context = getInstrumentation().getTargetContext();
    Feed feed = new Feed("url", null, "title");
    feed.setItems(new ArrayList<>());
    FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed);
    feed.getItems().add(item);
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(feed);
    adapter.close();
    assertTrue(item.getId() != 0);
    DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS);
    adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor cursor = adapter.getQueueIDCursor();
    assertTrue(cursor.moveToFirst());
    assertTrue(cursor.getLong(0) == item.getId());
    cursor.close();
    adapter.close();
}

86. DBWriterTest#testAddQueueItemMultipleItems()

Project: AntennaPod
Source File: DBWriterTest.java
View license
public void testAddQueueItemMultipleItems() throws InterruptedException, ExecutionException, TimeoutException {
    final Context context = getInstrumentation().getTargetContext();
    final int NUM_ITEMS = 10;
    Feed feed = queueTestSetupMultipleItems(NUM_ITEMS);
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor cursor = adapter.getQueueIDCursor();
    assertTrue(cursor.moveToFirst());
    assertTrue(cursor.getCount() == NUM_ITEMS);
    for (int i = 0; i < NUM_ITEMS; i++) {
        assertTrue(cursor.moveToPosition(i));
        assertTrue(cursor.getLong(0) == feed.getItems().get(i).getId());
    }
    cursor.close();
    adapter.close();
}

87. MainActivityTest#setUp()

Project: AntennaPod
Source File: MainActivityTest.java
View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    Context context = getInstrumentation().getTargetContext();
    uiTestUtils = new UITestUtils(context);
    uiTestUtils.setup();
    // create new database
    PodDBAdapter.init(context);
    PodDBAdapter.deleteDatabase();
    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.close();
    // override first launch preference
    // do this BEFORE calling getActivity()!
    prefs = getInstrumentation().getTargetContext().getSharedPreferences(MainActivity.PREF_NAME, Context.MODE_PRIVATE);
    prefs.edit().putBoolean(MainActivity.PREF_IS_FIRST_LAUNCH, false).commit();
    solo = new Solo(getInstrumentation(), getActivity());
}

88. RatingDialog#createDialog()

Project: AntennaPod
Source File: RatingDialog.java
View license
@Nullable
private static MaterialDialog createDialog() {
    Context context = mContext.get();
    if (context == null) {
        return null;
    }
    return new MaterialDialog.Builder(context).title(R.string.rating_title).content(R.string.rating_message).positiveText(R.string.rating_now_label).negativeText(R.string.rating_never_label).neutralText(R.string.rating_later_label).onPositive(( dialog,  which) -> rateNow()).onNegative(( dialog,  which) -> saveRated()).onNeutral(( dialog,  which) -> resetStartDate()).cancelListener( dialog1 -> resetStartDate()).build();
}

89. PreferenceController#setUpdateIntervalText()

View license
private void setUpdateIntervalText() {
    Context context = ui.getActivity().getApplicationContext();
    String val;
    long interval = UserPreferences.getUpdateInterval();
    if (interval > 0) {
        int hours = (int) TimeUnit.MILLISECONDS.toHours(interval);
        String hoursStr = context.getResources().getQuantityString(R.plurals.time_hours_quantified, hours, hours);
        val = String.format(context.getString(R.string.pref_autoUpdateIntervallOrTime_every), hoursStr);
    } else {
        int[] timeOfDay = UserPreferences.getUpdateTimeOfDay();
        if (timeOfDay.length == 2) {
            Calendar cal = new GregorianCalendar();
            cal.set(Calendar.HOUR_OF_DAY, timeOfDay[0]);
            cal.set(Calendar.MINUTE, timeOfDay[1]);
            String timeOfDayStr = DateFormat.getTimeFormat(context).format(cal.getTime());
            val = String.format(context.getString(R.string.pref_autoUpdateIntervallOrTime_at), timeOfDayStr);
        } else {
            val = context.getString(R.string.pref_smart_mark_as_played_disabled);
        }
    }
    String summary = context.getString(R.string.pref_autoUpdateIntervallOrTime_sum) + "\n" + String.format(context.getString(R.string.pref_current_value), val);
    ui.findPreference(UserPreferences.PREF_UPDATE_INTERVAL).setSummary(summary);
}

90. SPAUtil#sendSPAppsQueryFeedsIntent()

Project: AntennaPod
Source File: SPAUtil.java
View license
/**
     * Sends an ACTION_SP_APPS_QUERY_FEEDS intent to all AntennaPod Single Purpose apps.
     * The receiving single purpose apps will then send their feeds back to AntennaPod via an
     * ACTION_SP_APPS_QUERY_FEEDS_RESPONSE intent.
     * This intent will only be sent once.
     *
     * @return True if an intent was sent, false otherwise (for example if the intent has already been
     * sent before.
     */
public static synchronized boolean sendSPAppsQueryFeedsIntent(Context context) {
    if (context == null)
        throw new IllegalArgumentException("context = null");
    final Context appContext = context.getApplicationContext();
    if (appContext == null) {
        Log.wtf(TAG, "Unable to get application context");
        return false;
    }
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
    if (!prefs.getBoolean(PREF_HAS_QUERIED_SP_APPS, false)) {
        appContext.sendBroadcast(new Intent(SPAReceiver.ACTION_SP_APPS_QUERY_FEEDS));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Sending SP_APPS_QUERY_FEEDS intent");
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(PREF_HAS_QUERIED_SP_APPS, true);
        editor.commit();
        return true;
    } else {
        return false;
    }
}

91. InstallerUtils#isEnableAutoInstall()

View license
public static boolean isEnableAutoInstall() {
    Context mContext = AutoInstallerContext.getContext();
    SimpleStringSplitter simpleStringSplitter = new SimpleStringSplitter(':');
    if (!SettingsUtil.isAccessibiltiyEnable(mContext)) {
        return false;
    }
    String string = Secure.getString(mContext.getContentResolver(), "enabled_accessibility_services");
    if (string == null) {
        return false;
    }
    simpleStringSplitter.setString(string);
    while (simpleStringSplitter.hasNext()) {
        if (simpleStringSplitter.next().equalsIgnoreCase(AutoInstallerContext.getTargetService())) {
            return true;
        }
    }
    return false;
}

92. FloatingActionMenu#createLabels()

View license
private void createLabels() {
    Context context = new ContextThemeWrapper(getContext(), mLabelsStyle);
    for (int i = 0; i < mButtonsCount; i++) {
        FloatingActionButton button = (FloatingActionButton) getChildAt(i);
        CharSequence title = button.getContentDescription();
        if (button == mMainButton || title == null || button.getTag(R.id.fab_label) != null)
            continue;
        TextView label = new TextView(context);
        label.setTextAppearance(getContext(), mLabelsStyle);
        label.setText(title);
        addView(label);
        button.setTag(R.id.fab_label, label);
    }
}

93. Persistence#nextHighPrioFile()

View license
private File nextHighPrioFile() {
    Context context = getContext();
    if (context != null) {
        String path = context.getFilesDir() + AI_SDK_DIRECTORY + HIGH_PRIO_DIRECTORY;
        File directory = new File(path);
        InternalLogging.info(TAG, "Returning High Prio File: ", path);
        return this.nextAvailableFileInDirectory(directory);
    }
    InternalLogging.warn(TAG, "Couldn't provide next file, the context for persistence is null");
    return null;
}

94. Persistence#nextRegularPrioFile()

View license
private File nextRegularPrioFile() {
    Context context = getContext();
    if (context != null) {
        String path = context.getFilesDir() + AI_SDK_DIRECTORY + REGULAR_PRIO_DIRECTORY;
        File directory = new File(path);
        InternalLogging.info(TAG, "Returning Regular Prio File: " + path);
        return this.nextAvailableFileInDirectory(directory);
    }
    InternalLogging.warn(TAG, "Couldn't provide next file, the context for persistence is null");
    return null;
}

95. RepositoryAdapter#onBindViewHolder()

Project: archi
Source File: RepositoryAdapter.java
View license
@Override
public void onBindViewHolder(RepositoryViewHolder holder, int position) {
    Repository repository = repositories.get(position);
    Context context = holder.titleTextView.getContext();
    holder.repository = repository;
    holder.titleTextView.setText(repository.name);
    holder.descriptionTextView.setText(repository.description);
    holder.watchersTextView.setText(context.getResources().getString(R.string.text_watchers, repository.watchers));
    holder.starsTextView.setText(context.getResources().getString(R.string.text_stars, repository.stars));
    holder.forksTextView.setText(context.getResources().getString(R.string.text_forks, repository.forks));
}

96. RepositoryAdapter#onBindViewHolder()

Project: archi
Source File: RepositoryAdapter.java
View license
@Override
public void onBindViewHolder(RepositoryViewHolder holder, int position) {
    Repository repository = repositories.get(position);
    Context context = holder.titleTextView.getContext();
    holder.repository = repository;
    holder.titleTextView.setText(repository.name);
    holder.descriptionTextView.setText(repository.description);
    holder.watchersTextView.setText(context.getResources().getString(R.string.text_watchers, repository.watchers));
    holder.starsTextView.setText(context.getResources().getString(R.string.text_stars, repository.stars));
    holder.forksTextView.setText(context.getResources().getString(R.string.text_forks, repository.forks));
}

97. ActionBarSherlockCompat#initializePanelMenu()

Project: astrid
Source File: ActionBarSherlockCompat.java
View license
private boolean initializePanelMenu() {
    //getContext();
    Context context = mActivity;
    // If we have an action bar, initialize the menu with a context themed for it.
    if (wActionBar != null) {
        TypedValue outValue = new TypedValue();
        Resources.Theme currentTheme = context.getTheme();
        currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, outValue, true);
        final int targetThemeRes = outValue.resourceId;
        if (targetThemeRes != 0) /*&& context.getThemeResId() != targetThemeRes*/
        {
            context = new ContextThemeWrapper(context, targetThemeRes);
        }
    }
    mMenu = new MenuBuilder(context);
    mMenu.setCallback(this);
    return true;
}

98. ActionBarSherlockNative#getThemedContext()

Project: astrid
Source File: ActionBarSherlockNative.java
View license
@Override
protected Context getThemedContext() {
    Context context = mActivity;
    TypedValue outValue = new TypedValue();
    mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true);
    if (outValue.resourceId != 0) {
        //We are unable to test if this is the same as our current theme
        //so we just wrap it and hope that if the attribute was specified
        //then the user is intentionally specifying an alternate theme.
        context = new ContextThemeWrapper(context, outValue.resourceId);
    }
    return context;
}

99. ListNavigation#onCreate()

Project: astrid
Source File: ListNavigation.java
View license
@Override
public void onCreate(Bundle savedInstanceState) {
    //Used for theme switching in samples
    setTheme(SampleList.THEME);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_navigation);
    mSelected = (TextView) findViewById(R.id.text);
    mLocations = getResources().getStringArray(R.array.locations);
    Context context = getSupportActionBar().getThemedContext();
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    getSupportActionBar().setListNavigationCallbacks(list, this);
}

100. Preferences#getIntegerFromString()

Project: astrid
Source File: Preferences.java
View license
/** Gets an integer value from a string preference. Returns null
     * if the value is not set or not an integer.
     *
     * @param keyResource resource from string.xml
     * @return integer value, or null on error
     */
public static int getIntegerFromString(int keyResource, int defaultValue) {
    Context context = ContextManager.getContext();
    Resources r = context.getResources();
    String value = getPrefs(context).getString(r.getString(keyResource), null);
    if (value == null)
        return defaultValue;
    try {
        return Integer.parseInt(value);
    } catch (Exception e) {
        return defaultValue;
    }
}