android.content.Context

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

1. 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());
}

2. 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);
}

3. 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();
}

4. 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();
}

5. 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);
}

6. 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;
}

7. 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;
}

8. 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);
}

9. 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);
}

10. 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());
    }
}

11. 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;
    }
}

12. 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();
}

13. 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);
}

14. 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);
}

15. 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);
}

16. 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();
}

17. 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);
}

18. 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);
}

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. SubtitleDownloader#onSubtitleDownloadSuccess()

View license
/**
     * Invoked when subtitle download finished successfully.
     */
private void onSubtitleDownloadSuccess() {
    if (contextReference.get() == null)
        return;
    if (listenerReference.get() == null)
        return;
    Context context = contextReference.get();
    ISubtitleDownloaderListener listener = listenerReference.get();
    try {
        File subtitleFile = getDownloadedSubtitleFile(context, media, subtitleLanguage);
        SubtitleParseTask task = new SubtitleParseTask(subtitleLanguage, listener);
        task.execute(subtitleFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        listener.onSubtitleDownloadCompleted(false, null);
    }
}

21. SignInScene#onSignInEnd()

Project: EhViewer
Source File: SignInScene.java
View license
public void onSignInEnd() {
    Context context = getContext2();
    if (null == context) {
        return;
    }
    if (EhApplication.getEhCookieStore(context).hasSignedIn()) {
        getProfile();
    } else {
        mSigningIn = false;
        hideProgress();
        whetherToSkip();
    }
}

22. MovieListAdapter#onCreateViewHolder()

View license
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_content, parent, false);
    final Context context = view.getContext();
    int gridColsNumber = context.getResources().getInteger(R.integer.grid_number_cols);
    view.getLayoutParams().height = (int) (parent.getWidth() / gridColsNumber * Movie.POSTER_ASPECT_RATIO);
    return new ViewHolder(view);
}

23. Alarm#schedule()

View license
public long schedule() {
    Context context = AlarmApplication.getAppContext();
    if (isEnabled() && !isNew()) {
        AlarmScheduler.cancelAlarm(context, this);
    } else {
        setIsEnabled(true);
    }
    // If someone edits alarm settings while in a snooze period we reset the snooze
    setSnoozed(false);
    setNew(false);
    AlarmList.get(context).updateAlarm(this);
    return AlarmScheduler.scheduleAlarm(context, this);
}

24. Alarm#snooze()

View license
public void snooze() {
    Context context = AlarmApplication.getAppContext();
    // Schedule the snooze and update the alarm data with the details
    long snoozeTime = AlarmScheduler.snoozeAlarm(context, this, getAlarmSnoozeDuration());
    Calendar snoozeCalendar = Calendar.getInstance();
    snoozeCalendar.setTimeInMillis(snoozeTime);
    setSnoozeHour(snoozeCalendar.get(Calendar.HOUR_OF_DAY));
    setSnoozeMinute(snoozeCalendar.get(Calendar.MINUTE));
    setSnoozeSeconds(snoozeCalendar.get(Calendar.SECOND));
    setSnoozed(true);
    setIsEnabled(true);
    AlarmList.get(context).updateAlarm(this);
}

25. Alarm#onDismiss()

View license
public void onDismiss() {
    Context context = AlarmApplication.getAppContext();
    boolean updateAlarm = false;
    if (isOneShot()) {
        // We disable a oneshot alarm after it has been dismissed
        setIsEnabled(false);
        updateAlarm = true;
    } else {
        // Schedule the next repeating alarm if necessary
        AlarmScheduler.scheduleAlarm(context, this);
    }
    if (isSnoozed()) {
        setSnoozed(false);
        updateAlarm = true;
    }
    if (updateAlarm) {
        AlarmList.get(context).updateAlarm(this);
    }
}

26. GeneralUtilities#getDurationSetting()

View license
public static int getDurationSetting(int settingKeyResId, int defaultSettingStringResId, int defaultDuration) {
    Context context = AlarmApplication.getAppContext();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String durationPreference = preferences.getString(context.getResources().getString(settingKeyResId), context.getResources().getString(defaultSettingStringResId));
    int duration = defaultDuration;
    try {
        duration = Integer.parseInt(durationPreference);
    } catch (NumberFormatException e) {
        Logger.trackException(e);
    }
    return duration;
}

27. FileUtils#getAvailableFileSystems()

Project: Projeto_PG
Source File: FileUtils.java
View license
protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();
    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }
    return availableFileSystems;
}

28. FileUtils#requestAllPaths()

Project: Projeto_PG
Source File: FileUtils.java
View license
private JSONObject requestAllPaths() throws JSONException {
    Context context = cordova.getActivity();
    JSONObject ret = new JSONObject();
    ret.put("applicationDirectory", "file:///android_asset/");
    ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
    ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
    ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
            ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
            ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
            ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
        }
    }
    return ret;
}

29. FileUtils#getAvailableFileSystems()

Project: Projeto_PG
Source File: FileUtils.java
View license
protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();
    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }
    return availableFileSystems;
}

30. FileUtils#requestAllPaths()

Project: Projeto_PG
Source File: FileUtils.java
View license
private JSONObject requestAllPaths() throws JSONException {
    Context context = cordova.getActivity();
    JSONObject ret = new JSONObject();
    ret.put("applicationDirectory", "file:///android_asset/");
    ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
    ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
    ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
            ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
            ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
            ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
        }
    }
    return ret;
}

31. Load#color()

Project: Pugnotification
Source File: Load.java
View license
public Load color(@ColorRes int color) {
    if (color <= 0) {
        throw new IllegalArgumentException("Resource ID Should Not Be Less Than Or Equal To Zero!");
    }
    Context context = PugNotification.mSingleton.mContext;
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.builder.setColor(context.getColor(color));
    } else {
        this.builder.setColor(context.getResources().getColor(color));
    }
    return this;
}

32. PureeConfigurationTest#checkDefaultValue()

View license
@Test
public void checkDefaultValue() {
    Context context = InstrumentationRegistry.getContext();
    PureeConfiguration conf = new PureeConfiguration.Builder(context).build();
    assertThat(conf.getContext(), notNullValue());
    assertThat(conf.getGson(), notNullValue());
    Map<?, ?> sourceOutputMap = conf.getSourceOutputMap();
    assertThat(sourceOutputMap.size(), is(0));
}

33. PureeConfigurationTest#build()

View license
@Test
public void build() {
    Context context = InstrumentationRegistry.getContext();
    PureeConfiguration conf = new PureeConfiguration.Builder(context).source(FooLog.class).to(new OutFoo()).source(FooLog.class).filters(new FooFilter()).to(new OutFoo()).source(FooLog.class).filter(new FooFilter()).filter(new BarFilter()).to(new OutBar()).source(BarLog.class).filter(new FooFilter()).to(new OutFoo()).build();
    {
        List<PureeOutput> outputs = conf.getRegisteredOutputPlugins(FooLog.class);
        assertThat(outputs, is(not(nullValue())));
        assertThat(outputs.size(), is(3));
    }
    {
        List<PureeOutput> outputs = conf.getRegisteredOutputPlugins(BarLog.class);
        assertThat(outputs.size(), is(1));
        assertThat(outputs.get(0).getClass().getName(), is(OutFoo.class.getName()));
        List<PureeFilter> filters = outputs.get(0).getFilters();
        assertThat(filters.size(), is(1));
        assertThat(filters.get(0).getClass().getName(), is(FooFilter.class.getName()));
    }
}

34. PureeConfigurationTest#build2()

View license
@Test
public void build2() {
    Context context = InstrumentationRegistry.getContext();
    PureeConfiguration conf = new PureeConfiguration.Builder(context).register(FooLog.class, new OutFoo()).register(FooLog.class, new OutFoo().withFilters(new FooFilter())).register(FooLog.class, new OutBar().withFilters(new FooFilter(), new BarFilter())).register(BarLog.class, new OutFoo().withFilters(new FooFilter())).build();
    {
        List<PureeOutput> outputs = conf.getRegisteredOutputPlugins(FooLog.class);
        assertThat(outputs.size(), is(3));
    }
    {
        List<PureeOutput> outputs = conf.getRegisteredOutputPlugins(BarLog.class);
        assertThat(outputs.size(), is(1));
        assertThat(outputs.get(0).getClass().getName(), is(OutFoo.class.getName()));
        List<PureeFilter> filters = outputs.get(0).getFilters();
        assertThat(filters.size(), is(1));
        assertThat(filters.get(0).getClass().getName(), is(FooFilter.class.getName()));
    }
}

35. AppLinkData#fetchDeferredAppLinkData()

Project: q-municate-android
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);
        }
    });
}

36. Settings#publishInstallAsync()

Project: q-municate-android
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);
                    }
                });
            }
        }
    });
}

37. RecipientIdCache#canonicalTableDump()

Project: qksms
Source File: RecipientIdCache.java
View license
public static void canonicalTableDump() {
    Log.d(TAG, "**** Dump of canoncial_addresses table ****");
    Context context = sInstance.mContext;
    Cursor c = SqliteWrapper.query(context, context.getContentResolver(), sAllCanonical, null, null, null, null);
    if (c == null) {
        Log.w(TAG, "null Cursor in content://mms-sms/canonical-addresses");
    }
    try {
        while (c.moveToNext()) {
            // TODO: don't hardcode the column indices
            long id = c.getLong(0);
            String number = c.getString(1);
            Log.d(TAG, "id: " + id + " number: " + number);
        }
    } finally {
        c.close();
    }
}

38. DeviceUtils#getDeviceUid()

View license
public static String getDeviceUid() {
    Context context = CoreApp.getInstance();
    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String uniqueDeviceId = telephonyManager.getDeviceId();
    if (TextUtils.isEmpty(uniqueDeviceId)) {
        // for tablets
        ContentResolver cr = context.getContentResolver();
        uniqueDeviceId = Settings.Secure.getString(cr, Settings.Secure.ANDROID_ID);
    }
    return uniqueDeviceId;
}

39. FadeInNetworkImageView#setImageBitmap()

View license
@SuppressWarnings("deprecation")
@Override
public void setImageBitmap(Bitmap bm) {
    Context context = getContext();
    if (context != null) {
        Resources resources = context.getResources();
        TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(resources.getColor(android.R.color.transparent)), new BitmapDrawable(context.getResources(), bm) });
        setImageDrawable(td);
        td.startTransition(FADE_IN_TIME_MS);
    }
}

40. FacebookAdapter#setUpUserImage()

Project: QuickReturn
Source File: FacebookAdapter.java
View license
// region Helper Methods
private void setUpUserImage(ImageView iv, FacebookPost post) {
    Context context = iv.getContext();
    String avatarUrl = post.getAvatarUrl();
    if (!TextUtils.isEmpty(avatarUrl)) {
        Picasso.with(context).load(avatarUrl).centerCrop().resize(QuickReturnUtils.dp2px(context, 34), QuickReturnUtils.dp2px(context, 34)).error(//                    .placeholder(R.drawable.ic_facebook)
        android.R.drawable.stat_notify_error).into(iv);
    }
}

41. FacebookAdapter#setUpPostImage()

Project: QuickReturn
Source File: FacebookAdapter.java
View license
private void setUpPostImage(ImageView iv, FacebookPost post) {
    Context context = iv.getContext();
    String postImageUrl = post.getPostImageUrl();
    if (!TextUtils.isEmpty(postImageUrl)) {
        Picasso.with(context).load(postImageUrl).centerCrop().resize(QuickReturnUtils.dp2px(context, 346), QuickReturnUtils.dp2px(context, 320)).error(android.R.drawable.stat_notify_error).into(iv);
    }
}

42. TwitterAdapter#setUpUserImage()

Project: QuickReturn
Source File: TwitterAdapter.java
View license
private void setUpUserImage(ImageView iv, Tweet tweet) {
    Context context = iv.getContext();
    String avatarUrl = tweet.getAvatarUrl();
    if (!TextUtils.isEmpty(avatarUrl)) {
        Picasso.with(context).load(avatarUrl).centerCrop().resize(QuickReturnUtils.dp2px(context, 50), QuickReturnUtils.dp2px(context, 50)).error(//                    .placeholder(R.drawable.ic_facebook)
        android.R.drawable.stat_notify_error).into(iv);
    }
}

43. StatusBarModule#getConstants()

Project: react-native
Source File: StatusBarModule.java
View license
@Override
@Nullable
public Map<String, Object> getConstants() {
    final Context context = getReactApplicationContext();
    final int heightResId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
    final float height = heightResId > 0 ? PixelUtil.toDIPFromPixel(context.getResources().getDimensionPixelSize(heightResId)) : 0;
    return MapBuilder.<String, Object>of(HEIGHT_KEY, height);
}

44. ModalHostShadowNode#addChildAt()

View license
/**
   * We need to set the styleWidth and styleHeight of the one child (represented by the <View/>
   * within the <RCTModalHostView/> in Modal.js.  This needs to fill the entire window.
   */
@Override
@TargetApi(16)
public void addChildAt(CSSNode child, int i) {
    super.addChildAt(child, i);
    Context context = getThemedContext();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    // getCurrentSizeRange will return the min and max width and height that the window can be
    display.getCurrentSizeRange(mMinPoint, mMaxPoint);
    int width, height;
    int rotation = display.getRotation();
    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
        // If we are vertical the width value comes from min width and height comes from max height
        width = mMinPoint.x;
        height = mMaxPoint.y;
    } else {
        // If we are horizontal the width value comes from max width and height comes from min height
        width = mMaxPoint.x;
        height = mMinPoint.y;
    }
    child.setStyleWidth(width);
    child.setStyleHeight(height);
}

45. AppAvailability#appInstalled()

Project: reacteu-app
Source File: AppAvailability.java
View license
// Thanks to http://floresosvaldo.com/android-cordova-plugin-checking-if-an-app-exists
public boolean appInstalled(String uri) {
    Context ctx = this.cordova.getActivity().getApplicationContext();
    final PackageManager pm = ctx.getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

46. FileUtils#getAvailableFileSystems()

Project: reacteu-app
Source File: FileUtils.java
View license
protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();
    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }
    return availableFileSystems;
}

47. FileUtils#requestAllPaths()

Project: reacteu-app
Source File: FileUtils.java
View license
private JSONObject requestAllPaths() throws JSONException {
    Context context = cordova.getActivity();
    JSONObject ret = new JSONObject();
    ret.put("applicationDirectory", "file:///android_asset/");
    ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
    ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
    ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
            ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
            ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
            ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
        }
    }
    return ret;
}

48. RealmConfigurationTests#deleteRealmIfMigrationNeeded_failsWhenAssetFileProvided()

View license
@Test
public void deleteRealmIfMigrationNeeded_failsWhenAssetFileProvided() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    // have a builder instance to isolate codepath
    RealmConfiguration.Builder builder = new RealmConfiguration.Builder(context);
    try {
        builder.assetFile(context, "asset_file.realm").deleteRealmIfMigrationNeeded();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("Realm cannot clear its schema when previously configured to use an asset file by calling assetFile().", expected.getMessage());
    }
}

49. RealmConfigurationTests#initialDataTransactionAssetFile()

View license
@Test
public void initialDataTransactionAssetFile() throws IOException {
    // Remove default instance
    Realm.deleteRealm(defaultConfig);
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    configFactory.copyRealmFromAssets(context, "asset_file.realm", Realm.DEFAULT_REALM_NAME);
    assertTrue(new File(configFactory.getRoot(), Realm.DEFAULT_REALM_NAME).exists());
    Realm.Transaction transaction = mock(Realm.Transaction.class);
    RealmConfiguration configuration = configFactory.createConfigurationBuilder().modules(new AssetFileModule()).initialData(transaction).build();
    realm = Realm.getInstance(configuration);
    realm.close();
    verify(transaction, never()).execute(realm);
}

50. RealmConfigurationTests#assetFileNullAndEmptyFileName()

View license
@Test
public void assetFileNullAndEmptyFileName() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    try {
        new RealmConfiguration.Builder(context).assetFile(context, null).build();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
    try {
        new RealmConfiguration.Builder(context).assetFile(context, "").build();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
}

51. RealmConfigurationTests#assetFileWithInMemoryConfig()

View license
@Test
public void assetFileWithInMemoryConfig() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    // Ensure that there is no data
    Realm.deleteRealm(new RealmConfiguration.Builder(context).build());
    try {
        new RealmConfiguration.Builder(context).assetFile(context, "asset_file.realm").inMemory().build();
        fail();
    } catch (RealmException ignored) {
    }
}

52. RealmConfigurationTests#assetFileFakeFile()

View license
@Test
public void assetFileFakeFile() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    // Ensure that there is no data
    Realm.deleteRealm(new RealmConfiguration.Builder(context).build());
    RealmConfiguration configuration = new RealmConfiguration.Builder(context).assetFile(context, "no_file").build();
    try {
        Realm.getInstance(configuration);
        fail();
    } catch (RealmIOException ignored) {
    }
}

53. RealmConfigurationTests#assetFile_failsWhenDeleteRealmIfMigrationNeededConfigured()

View license
@Test
public void assetFile_failsWhenDeleteRealmIfMigrationNeededConfigured() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    // have a builder instance to isolate codepath
    RealmConfiguration.Builder builder = new RealmConfiguration.Builder(context);
    try {
        builder.deleteRealmIfMigrationNeeded().assetFile(context, "asset_file.realm");
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("Realm cannot use an asset file when previously configured to clear its schema in migration by calling deleteRealmIfMigrationNeeded().", expected.getMessage());
    }
}

54. WeChatFragment#refreshLayout()

View license
void refreshLayout() {
    if (mServiceStateTv == null)
        return;
    Context context = getActivity();
    if (context == null)
        return;
    boolean isRunning = AccessibilityServiceHelper.isAccessibilitySettingsOn(context);
    mServiceStateTv.setText(isRunning ? getString(R.string.ui_wechat_tv_service_on) : getString(R.string.ui_wechat_tv_service_off));
    mServiceStateTv.setTextColor(isRunning ? Color.BLUE : Color.RED);
    mOneKeyCleanTv.setText(isRunning ? getString(R.string.ui_wechat_btn_service_on_text) : getString(R.string.ui_wechat_btn_service_off_text));
    mOneKeyCleanTv.setTextColor(isRunning ? Color.RED : Color.WHITE);
    if (PackageUtils.isAppInstalled(getActivity(), WECHAT_PACKAGENAME)) {
        mOpenWechatTv.setVisibility(View.VISIBLE);
    } else {
        mOpenWechatTv.setVisibility(View.GONE);
    }
}

55. RedditCommentListItem#onCreateViewHolder()

View license
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup viewGroup) {
    final Context context = viewGroup.getContext();
    final View view;
    if (isComment()) {
        view = new RedditCommentView(context, new RRThemeAttributes(context), mFragment);
    } else if (isLoadMore()) {
        view = new LoadMoreCommentsView(context, mCommentListingUrl);
    } else {
        throw new RuntimeException("Unknown item type");
    }
    return new RecyclerView.ViewHolder(view) {
    };
}

56. RefreshActionItem#onLongClick()

View license
@Override
public boolean onLongClick(View v) {
    if (mMenuItem == null || TextUtils.isEmpty(mMenuItem.getTitle())) {
        return true;
    }
    final int[] screenPos = new int[2];
    final Rect displayFrame = new Rect();
    getLocationOnScreen(screenPos);
    getWindowVisibleDisplayFrame(displayFrame);
    final Context context = getContext();
    final int width = getWidth();
    final int height = getHeight();
    final int midy = screenPos[1] + height / 2;
    final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
    Toast cheatSheet = Toast.makeText(context, mMenuItem.getTitle(), Toast.LENGTH_SHORT);
    if (midy < displayFrame.height()) {
        cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, screenWidth - screenPos[0] - width / 2, height);
    } else {
        cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
    }
    cheatSheet.show();
    return true;
}

57. ApkLibraryInstallerTest#installsCorrectly()

View license
@Test
public void installsCorrectly() throws IOException {
    final Context context = mock(Context.class);
    final ApplicationInfo appInfo = mock(ApplicationInfo.class);
    final ReLinkerInstance instance = mock(ReLinkerInstance.class);
    final ApkLibraryInstaller installer = new ApkLibraryInstaller();
    final File destination = tempFolder.newFile("test");
    final String[] abis = new String[] { "x86" };
    when(context.getApplicationInfo()).thenReturn(appInfo);
    appInfo.sourceDir = getClass().getResource("/fake.apk").getFile();
    installer.installLibrary(context, abis, "libtest.so", destination, instance);
    verify(context).getApplicationInfo();
    assertThat(fileToString(destination), is("works!"));
}

58. RhythmFrameLayout#onRhythmGroupSet()

Project: Rhythm
Source File: RhythmFrameLayout.java
View license
/**
     * Retrieves proper drawable from current group and links it to this view
     */
private void onRhythmGroupSet() {
    // Request rhythm group from application context
    Context context = getContext().getApplicationContext();
    if (context instanceof RhythmControl.Host) {
        // This may fail with index out of bounds exception if incorrect group index is provided
        // But, IMHO, it is better to throw the exception than suppress it and leave the developer clueless
        final RhythmDrawable drawable = ((RhythmControl.Host) context).getRhythmControl().getGroup(mRhythmGroupIndex).makeDrawable();
        doSetRhythmDrawable(drawable);
    } else {
        // Uh-oh
        throw new ClassCastException(this + " cannot connect to RhythmControl. " + "Check if your Application implements RhythmControl.Host");
    }
}

59. ProgressDialogTest#show_shouldCreateAProgressDialog()

Project: robolectric
Source File: ProgressDialogTest.java
View license
@Test
public void show_shouldCreateAProgressDialog() {
    Context context = new Activity();
    TestOnCancelListener cancelListener = new TestOnCancelListener();
    ProgressDialog progressDialog = ProgressDialog.show(context, "Title", "Message", true, true, cancelListener);
    ShadowProgressDialog shadowProgressDialog = shadowOf(progressDialog);
    assertThat(shadowProgressDialog.getContext(), is(context));
    assertThat(shadowProgressDialog.getMessage(), equalTo("Message"));
    assertTrue(shadowProgressDialog.isIndeterminate());
    assertTrue(shadowProgressDialog.isCancelable());
    progressDialog.cancel();
    assertThat(cancelListener.onCancelDialogInterface, is((DialogInterface) progressDialog));
}

60. SpiceManager#tryToStartService()

Project: robospice
Source File: SpiceManager.java
View license
private boolean tryToStartService() {
    boolean success = false;
    // start the service it is not started yet.
    Context context = getContextReference();
    if (context != null) {
        checkServiceIsProperlyDeclaredInAndroidManifest(context);
        final Intent intent = new Intent(context, spiceServiceClass);
        context.startService(intent);
        success = true;
    }
    return success;
}

61. Getter#getView()

Project: robotium
Source File: Getter.java
View license
/**
	 * Returns a {@code View} with a given id.
	 * 
	 * @param id the id of the {@link View} to return
	 * @param index the index of the {@link View}. {@code 0} if only one is available
	 * @return a {@code View} with a given id
	 */
public View getView(String id, int index) {
    View viewToReturn = null;
    Context targetContext = instrumentation.getTargetContext();
    String packageName = targetContext.getPackageName();
    int viewId = targetContext.getResources().getIdentifier(id, "id", packageName);
    if (viewId != 0) {
        viewToReturn = getView(viewId, index, TIMEOUT);
    }
    if (viewToReturn == null) {
        int androidViewId = targetContext.getResources().getIdentifier(id, "id", "android");
        if (androidViewId != 0) {
            viewToReturn = getView(androidViewId, index, TIMEOUT);
        }
    }
    if (viewToReturn != null) {
        return viewToReturn;
    }
    return getView(viewId, index);
}

62. RecyclerAdapter#onCreateViewHolder()

View license
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    if (viewType == TYPE_ITEM) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_recycler, parent, false);
        return RecylerItemViewHolder.newInstance(view);
    } else if (viewType == TYPE_HEADER) {
        View header = LayoutInflater.from(context).inflate(R.layout.item_header, parent, false);
        return new RecylerHeaderViewHolder(header);
    }
    throw new RuntimeException("There is no type that match the type " + viewType + "...");
}

63. StandOutWindow#getHiddenNotification()

Project: Roundr
Source File: StandOutWindow.java
View license
/**
	 * Return a hidden {@link Notification} for the corresponding id. The system
	 * will request a notification for every id that is hidden.
	 * 
	 * <p>
	 * If null is returned, StandOut will assume you do not wish to support
	 * hiding this window, and will {@link #close(int)} it for you.
	 * 
	 * <p>
	 * See the StandOutExample project for an implementation of
	 * {@link #getHiddenNotification(int)} that for every hidden window keeps a
	 * notification which restores that window upon user's click.
	 * 
	 * @param id
	 *            The id of the window.
	 * @return The {@link Notification} corresponding to the id or null.
	 */
public Notification getHiddenNotification(int id) {
    // same basics as getPersistentNotification()
    int icon = getHiddenIcon();
    long when = System.currentTimeMillis();
    Context c = getApplicationContext();
    String contentTitle = getHiddenNotificationTitle(id);
    String contentText = getHiddenNotificationMessage(id);
    String tickerText = String.format("%s: %s", contentTitle, contentText);
    // the difference here is we are providing the same id
    Intent notificationIntent = getHiddenNotificationIntent(id);
    PendingIntent contentIntent = null;
    if (notificationIntent != null) {
        contentIntent = PendingIntent.getService(this, 0, notificationIntent, // flag updates existing persistent notification
        PendingIntent.FLAG_UPDATE_CURRENT);
    }
    Notification notification = new Notification(icon, tickerText, when);
    notification.setLatestEventInfo(c, contentTitle, contentText, contentIntent);
    return notification;
}

64. FriendAdapter#onBindViewHolder()

Project: rox-android
Source File: FriendAdapter.java
View license
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    Context context = holder.itemView.getContext();
    holder.itemView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (listener != null)
                listener.onClick(position);
        }
    });
    String userFullName = friends[position].getLastName() == null || friends[position].getLastName().trim().isEmpty() ? friends[position].getName() : friends[position].getName() + " " + friends[position].getLastName();
    holder.userNameTextView.setText(userFullName);
    Picasso.with(context).load(friends[position].getPhotoUrl()).placeholder(R.drawable.ic_contact_picture).into(holder.profileImageView);
}

65. LikeDeletableAdapter#onBindViewHolder()

View license
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    Context context = holder.itemView.getContext();
    holder.likeNameTextView.setText(categories.get(position).getName());
    Picasso.with(context).load(categories.get(position).getIconUrl()).transform(new ColorTransformation(context.getResources().getColor(R.color.secondary_text))).placeholder(R.drawable.ic_generic_category).into(holder.likeImageView);
    holder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
    holder.swipeLayout.setDragEdge(SwipeLayout.DragEdge.Right);
    holder.deleteButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            mItemManger.removeShownLayouts(holder.swipeLayout);
            Category removedCategory = categories.remove(position);
            notifyDataSetChanged();
            mItemManger.closeAllItems();
            if (removeLikeListener != null)
                removeLikeListener.onRemove(removedCategory);
        }
    });
}

66. PastimeRecyclerAdapter#onBindViewHolder()

View license
@Override
public void onBindViewHolder(PastimeViewHolder holder, int position) {
    PastimeCard card = (PastimeCard) holder.itemView;
    if (isInSingleSelectionMode()) {
        ensureOnlyOneItemSelected(card, position);
    }
    card.setOnClickListener( v1 -> {
        toggleCardsBasedOnSelectability(v1, holder.getLayoutPosition());
        notifyPastimeSelectionListeners(mPastimes.get(holder.getLayoutPosition()));
    });
    Pastime pastime = mPastimes.get(position);
    holder.mPastimeNameTextView.setText(pastime.getName());
    Context c = holder.mPastimeIconImageView.getContext();
    Drawable pastimeIcon = pastime.getIcon(c);
    holder.mPastimeIconImageView.setImageDrawable(pastimeIcon);
}

67. AboutPreference#init()

Project: runnerup
Source File: AboutPreference.java
View license
void init() {
    setNegativeButtonText(null);
    Context ctx = getContext();
    Resources res = ctx.getResources();
    try {
        PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
        this.setDialogTitle("RunnerUp v" + pInfo.versionName);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
}

68. AboutPreference#init()

Project: runnerup
Source File: AboutPreference.java
View license
void init() {
    setNegativeButtonText(null);
    Context ctx = getContext();
    Resources res = ctx.getResources();
    try {
        PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
        this.setDialogTitle("RunnerUp v" + pInfo.versionName);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    String str = res.getString(R.string.Google_Play_Services_Legal_Notices);
    if (str.contentEquals(this.getTitle())) {
        CharSequence msg = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(this.getContext());
        if (msg != null) {
            this.setDialogMessage(msg);
        }
    }
}

69. Tracker#doBind()

Project: runnerup
Source File: Tracker.java
View license
private void doBind() {
    /**
         * Let components populate bindValues
         */
    HashMap<String, Object> bindValues = new HashMap<String, Object>();
    Context ctx = getApplicationContext();
    bindValues.put(TrackerComponent.KEY_CONTEXT, ctx);
    bindValues.put(Workout.KEY_FORMATTER, new Formatter(ctx));
    bindValues.put(Workout.KEY_HRZONES, new HRZones(ctx));
    bindValues.put(Workout.KEY_MUTE, Boolean.valueOf(workout.getMute()));
    components.onBind(bindValues);
    /**
         * and then give them to workout
         */
    workout.onBind(workout, bindValues);
}

70. StartActivity#prepareWorkout()

Project: runnerup
Source File: StartActivity.java
View license
Workout prepareWorkout() {
    Context ctx = getApplicationContext();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences audioPref = null;
    Workout w = null;
    if (tabHost.getCurrentTabTag().contentEquals(TAB_BASIC)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_basic_audio));
        Dimension target = Dimension.valueOf(simpleTargetType.getValueInt());
        w = WorkoutBuilder.createDefaultWorkout(getResources(), pref, target);
    } else if (tabHost.getCurrentTabTag().contentEquals(TAB_INTERVAL)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_interval_audio));
        w = WorkoutBuilder.createDefaultIntervalWorkout(getResources(), pref);
    } else if (tabHost.getCurrentTabTag().contentEquals(TAB_ADVANCED)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_advanced_audio));
        w = advancedWorkout;
    }
    WorkoutBuilder.prepareWorkout(getResources(), pref, w, TAB_BASIC.contentEquals(tabHost.getCurrentTabTag()));
    WorkoutBuilder.addAudioCuesToWorkout(getResources(), w, audioPref);
    return w;
}

71. RxBindingTestRunner#onStart()

Project: RxBinding
Source File: RxBindingTestRunner.java
View license
@Override
public void onStart() {
    Context app = getTargetContext().getApplicationContext();
    String name = RxBindingTestRunner.class.getSimpleName();
    // Unlock the device so that the tests can input keystrokes.
    KeyguardManager keyguard = (KeyguardManager) app.getSystemService(KEYGUARD_SERVICE);
    keyguard.newKeyguardLock(name).disableKeyguard();
    // Wake up the screen.
    PowerManager power = (PowerManager) app.getSystemService(POWER_SERVICE);
    wakeLock = power.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, name);
    wakeLock.acquire();
    super.onStart();
}

72. PushService#runIntentInService()

View license
/**
     * This method is called from the broadcast receiver, when a push notification
     * is received, or when we receive a callback from the GCM service. Processing
     * of the message occurs here, and the acquired wake lock is released post processing.
     *
     * @param intent Intent.
     */
static void runIntentInService(Intent intent) {
    final Context context = SalesforceSDKManager.getInstance().getAppContext();
    if (WAKE_LOCK == null) {
        final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        WAKE_LOCK = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    }
    WAKE_LOCK.acquire();
    intent.setClassName(context, PushService.class.getName());
    final ComponentName name = context.startService(intent);
    if (name == null) {
        Log.w(TAG, "Could not start GCM service.");
    }
}

73. PasscodeManager#storeMobilePolicyForOrg()

View license
/**
     * Stores the mobile policy for the specified account.
     *
     * @param account UserAccount instance.
     * @param timeout Timeout value, in ms.
     * @param passLen Minimum passcode length.
     */
public void storeMobilePolicyForOrg(UserAccount account, int timeout, int passLen) {
    if (account == null) {
        return;
    }
    final Context context = SalesforceSDKManager.getInstance().getAppContext();
    final SharedPreferences sp = context.getSharedPreferences(MOBILE_POLICY_PREF + account.getOrgLevelFilenameSuffix(), Context.MODE_PRIVATE);
    final Editor e = sp.edit();
    e.putInt(KEY_TIMEOUT, timeout);
    e.putInt(KEY_PASSCODE_LENGTH, passLen);
    e.commit();
}

74. U2020TestRunner#onStart()

Project: sbt-android
Source File: U2020TestRunner.java
View license
@Override
public void onStart() {
    // Inform the app we are an instrumentation test before the object graph is initialized.
    DebugU2020Module.instrumentationTest = true;
    Context app = getTargetContext().getApplicationContext();
    String name = U2020TestRunner.class.getSimpleName();
    // Unlock the device so that the tests can input keystrokes.
    KeyguardManager keyguard = (KeyguardManager) app.getSystemService(KEYGUARD_SERVICE);
    keyguard.newKeyguardLock(name).disableKeyguard();
    // Wake up the screen.
    PowerManager power = (PowerManager) app.getSystemService(POWER_SERVICE);
    wakeLock = power.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, name);
    wakeLock.acquire();
    super.onStart();
}

75. SoundcloudLauncherTest#testSoundcloudInstalled()

Project: scdl
Source File: SoundcloudLauncherTest.java
View license
@Test
public void testSoundcloudInstalled() {
    final PackageManager packageManager = mock(PackageManager.class);
    final Context context = mock(Context.class);
    final Intent launchIntent = new Intent();
    when(packageManager.getLaunchIntentForPackage("com.soundcloud.android")).thenReturn(launchIntent);
    SoundcloudLauncher launcher = new SoundcloudLauncher(context, packageManager, new SoundcloudInstallAsker(context));
    assertThat(launcher.isInstalled(), is(true));
}

76. SoundcloudLauncherTest#testSoundcloudNotInstalled()

Project: scdl
Source File: SoundcloudLauncherTest.java
View license
@Test
public void testSoundcloudNotInstalled() {
    final PackageManager packageManager = mock(PackageManager.class);
    final Context context = mock(Context.class);
    // !
    final Intent launchIntent = null;
    when(packageManager.getLaunchIntentForPackage("com.soundcloud.android")).thenReturn(launchIntent);
    SoundcloudLauncher launcher = new SoundcloudLauncher(context, packageManager, new SoundcloudInstallAsker(context));
    assertThat(launcher.isInstalled(), is(false));
}

77. SoundcloudLauncherTest#testSoundcloudActivityRegression()

Project: scdl
Source File: SoundcloudLauncherTest.java
View license
@Test
public void testSoundcloudActivityRegression() {
    final PackageManager packageManager = mock(PackageManager.class);
    final Context context = mock(Context.class);
    final Intent launchIntent = new Intent("com.example.doesnotexist");
    final SoundcloudInstallAsker asker = mock(SoundcloudInstallAsker.class);
    // Very much mockery going in here. Idea is:
    // - package manager returns a valid launchIntent
    // - startActivity for some reason throws ActivityNotFoundException
    // - then treat it as not installed (instead of crashing)
    when(packageManager.getLaunchIntentForPackage("com.soundcloud.android")).thenReturn(launchIntent);
    Mockito.doNothing().when(asker).ask();
    Mockito.doThrow(ActivityNotFoundException.class).when(context).startActivity(launchIntent);
    final SoundcloudLauncher launcher = new SoundcloudLauncher(context, packageManager, asker);
    launcher.launch();
    verify(asker).ask();
}

78. DemosController#openNotification()

Project: scoop
Source File: DemosController.java
View license
@OnClick(R.id.notification_button)
public void openNotification() {
    Context context = getView().getContext();
    Intent serviceIntent = new Intent(context, SampleIntentService.class);
    PendingIntent contentIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
    Notification notification = new Notification.Builder(context).setContentTitle("This is a push notification.").setContentText("Scoop!").setSmallIcon(R.drawable.ic_launcher).setContentIntent(contentIntent).build();
    notificationManager.notify(100, notification);
}

79. ScoopsActivityTestRule#beforeActivityLaunched()

Project: Scoops
Source File: ScoopsActivityTestRule.java
View license
@Override
protected void beforeActivityLaunched() {
    Context ctx = InstrumentationRegistry.getInstrumentation().getTargetContext();
    mSharedPrefs = ctx.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
    // Initialize Scoop
    Scoop.waffleCone().addFlavor("Default", R.style.Theme_Scoop, true).addFlavor("Light", R.style.Theme_Scoop_Light).addDayNightFlavor("DayNight", R.style.Theme_Scoop_DayNight).addFlavor("Alternate 1", R.style.Theme_Scoop_Alt1).addFlavor("Alternate 2", R.style.Theme_Scoop_Alt2).setSharedPreferences(mSharedPrefs).initialize();
    // Make sure we are set to the default flavor each time
    Scoop.getInstance().choose(Scoop.getInstance().getFlavors().get(0));
}

80. SeriesGuideProvider#onCreate()

View license
@Override
public boolean onCreate() {
    Context context = getContext();
    sUriMatcher = buildUriMatcher();
    mDbHelper = new SeriesGuideDatabase(context);
    PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(mImportListener);
    return true;
}

81. BaseActivity#updateShowDelayed()

Project: SeriesGuide
Source File: BaseActivity.java
View license
/**
     * Schedule an update for the given show. Might not run if this show was just updated. Execution
     * is also delayed so it won't reduce UI setup performance (= you can run this in {@link
     * #onCreate(android.os.Bundle)}).
     *
     * <p> See {@link com.battlelancer.seriesguide.sync.SgSyncAdapter#requestSyncIfTime(android.content.Context,
     * int)}.
     */
protected void updateShowDelayed(final int showTvdbId) {
    if (mHandler == null) {
        mHandler = new Handler();
    }
    // delay sync request to avoid slowing down UI
    final Context context = getApplicationContext();
    mUpdateShowRunnable = new Runnable() {

        @Override
        public void run() {
            SgSyncAdapter.requestSyncIfTime(context, showTvdbId);
        }
    };
    mHandler.postDelayed(mUpdateShowRunnable, DateUtils.SECOND_IN_MILLIS);
}

82. Utils#setCompoundDrawablesRelativeWithIntrinsicBounds()

Project: SeriesGuide
Source File: Utils.java
View license
/**
     * Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the
     * text.  Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their
     * intrinsic bounds.
     */
public static void setCompoundDrawablesRelativeWithIntrinsicBounds(Button button, @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        button.setCompoundDrawablesRelativeWithIntrinsicBounds(left, top, right, bottom);
        return;
    }
    Context context = button.getContext();
    setCompoundDrawablesRelativeWithIntrinsicBounds(button, left != 0 ? ContextCompat.getDrawable(context, left) : null, top != 0 ? ContextCompat.getDrawable(context, top) : null, right != 0 ? ContextCompat.getDrawable(context, right) : null, bottom != 0 ? ContextCompat.getDrawable(context, bottom) : null);
}

83. Utils#tryStartActivityForResult()

Project: SeriesGuide
Source File: Utils.java
View license
/**
     * Similar to {@link #tryStartActivity(Context, Intent, boolean)}, but starting an activity for
     * a result.
     */
public static boolean tryStartActivityForResult(Fragment fragment, Intent intent, int requestCode) {
    Context context = fragment.getContext();
    // check if the intent can be handled
    boolean handled = false;
    if (intent.resolveActivity(context.getPackageManager()) != null) {
        try {
            fragment.startActivityForResult(intent, requestCode);
            handled = true;
        } catch (ActivityNotFoundException ignored) {
        }
    }
    if (!handled) {
        Toast.makeText(context, R.string.app_not_available, Toast.LENGTH_LONG).show();
    }
    return handled;
}

84. 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);
}

85. 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);
}

86. 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();
    }
}

87. 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;
}

88. 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;
}

89. 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;
}

90. 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);
}

91. 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;
}

92. 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;
}

93. 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));
}

94. 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));
}

95. 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;
}

96. 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;
}

97. 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);
    }
}

98. 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();
}

99. 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();
}

100. 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());
}