android.content.Context Java Examples

The following examples show how to use android.content.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: SendBird-Android   Author: sendbird   File: GroupChatAdapter.java    License: MIT License 8 votes vote down vote up
void bind(Context context, final FileMessage message, GroupChannel channel, boolean isNewDay, final OnItemClickListener listener) {
    bind(message, isNewDay);

    fileNameText.setText(message.getName());
    timeText.setText(DateUtils.formatTime(message.getCreatedAt()));

    if (listener != null) {
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onFileMessageItemClick(message);
            }
        });
    }

    messageStatusView.drawMessageStatus(channel, message);
}
 
Example #2
Source Project: exodus-android-app   Author: Exodus-Privacy   File: TrackerFragment.java    License: GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onUpdateComplete() {
    Context context = trackerBinding.getRoot().getContext();
    Tracker tracker = DatabaseManager.getInstance(context).getTracker(trackerId);
    trackerBinding.name.setText(tracker.name);
    trackerBinding.codeDetection.setText(tracker.codeSignature);
    trackerBinding.networkDetection.setText(tracker.networkSignature);
    trackerBinding.description.setText(Html.fromHtml(Utils.markdownToHtml(tracker.description)));
    trackerBinding.description.setMovementMethod(LinkMovementMethod.getInstance());
    trackerBinding.description.setClickable(true);
    trackerBinding.trackerUrl.setOnClickListener(v -> {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(tracker.website));
        startActivity(intent);
    });
    displayAppListAsync();
}
 
Example #3
Source Project: tinkerpatch-sdk   Author: TinkerPatch   File: DefaultPatchRequestCallback.java    License: MIT License 6 votes vote down vote up
@Override
public void onPatchDownloadFail(Exception e, Integer newVersion, Integer currentVersion) {
    TinkerLog.w(TAG, "onPatchDownloadFail e:" + e);
    //check network
    TinkerServerClient client = TinkerServerClient.get();
    //due to network, just return
    if (!NetStatusUtil.isConnected(client.getContext())) {
        TinkerLog.e(TAG, "onPatchDownloadFail, not connect to internet just return");
        return;
    }
    Context context = client.getContext();
    if (increaseDownloadError(context)) {
        client.reportPatchFail(newVersion, ERROR_DOWNLOAD_FAIL);
    }

}
 
Example #4
Source Project: iMoney   Author: xinpengfei520   File: TagAliasOperatorHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置手机号码回调
 *
 * @param context
 * @param jPushMessage
 */
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
    int sequence = jPushMessage.getSequence();
    LogUtil.i(TAG, "action - onMobileNumberOperatorResult, sequence:" + sequence + ",mobileNumber:" + jPushMessage.getMobileNumber());
    init(context);
    if (jPushMessage.getErrorCode() == 0) {
        LogUtil.i(TAG, "action - set mobile number Success,sequence:" + sequence);
        setActionCache.remove(sequence);
    } else {
        String logs = "Failed to set mobile number, errorCode:" + jPushMessage.getErrorCode();
        LogUtil.e(TAG, logs);
        if (!RetrySetMobileNumberActionIfNeeded(jPushMessage.getErrorCode(), jPushMessage.getMobileNumber())) {
            ExampleUtil.showToast(logs, context);
        }
    }
}
 
Example #5
Source Project: Equate   Author: EvanRespaut   File: AnimatedHoldButton.java    License: GNU General Public License v3.0 6 votes vote down vote up
public AnimatedHoldButton(Context context, AttributeSet attrs) {
	super(context, attrs);

	CLICK_HOLD_TIME = ViewUtils.getLongClickTimeout(context);

	mPrimaryText = "";

	mNormalDrawable = getBackground();

	TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AnimatedHoldButton, 0, 0);
	try {
		mPrimaryText = ta.getString(R.styleable.AnimatedHoldButton_primary_text);
		mPressedColor = ta.getColor(R.styleable.AnimatedHoldButton_pressed_color,
				  ContextCompat.getColor(context, R.color.op_button_pressed));
	} finally {
		ta.recycle();
	}

	//this is needed for so paint knows what to measure in layoutText
	setText(mPrimaryText);
}
 
Example #6
Source Project: meiShi   Author: sungerk   File: VideoControllerView.java    License: Apache License 2.0 6 votes vote down vote up
private void initView(Context context) {
    this.context = context;
    View v = LayoutInflater.from(context).inflate(R.layout.view_video_controller, null);
    addView(v);
    mVideoView = findView(R.id.videoView);

    mVideoView.setOnTouchListener(this);
    mVideoView.setOnPreparedListener(this);
    mVideoView.setOnBufferingUpdateListener(this);
    mVideoView.setOnCompletionListener(this);
    mProgressWheel = findView(R.id.progressWheel);
    mProgressWheel.startSpinning();
    viewPlay = findView(R.id.button_play);
    slider = findView(R.id.slider);
    slider.setOnValueChangedListener(this);
    slider.setOnNumberIndicatorConvert(new Slider.OnNumberIndicatorConvert() {
        @Override
        public String covert(long val) {
            return MediaPlayerUtils.getVideoDisplayTime(val);
        }
    });
    setVideoPlayButton();
}
 
Example #7
Source Project: BaldPhone   Author: UriahShaulMandel   File: BaldFrameLayoutButton.java    License: Apache License 2.0 6 votes vote down vote up
public BaldFrameLayoutButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.sharedPreferences = context.getSharedPreferences(D.BALD_PREFS, Context.MODE_PRIVATE);
    this.longPresses = sharedPreferences.getBoolean(BPrefs.LONG_PRESSES_KEY, BPrefs.LONG_PRESSES_DEFAULT_VALUE);
    this.longPressesShorter = sharedPreferences.getBoolean(BPrefs.LONG_PRESSES_SHORTER_KEY, BPrefs.LONG_PRESSES_SHORTER_DEFAULT_VALUE);
    this.vibrationFeedback = sharedPreferences.getBoolean(BPrefs.VIBRATION_FEEDBACK_KEY, BPrefs.VIBRATION_FEEDBACK_DEFAULT_VALUE);
    this.vibrator = this.vibrationFeedback ? (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE) : null;
    longer = longPresses ? BaldToast.from(context).setText(context.getText(R.string.press_longer)).setType(BaldToast.TYPE_DEFAULT).setLength(0).build() : null;
    if (longPresses)
        if (longPressesShorter) {
            baldButtonTouchListener = new BaldButtonTouchListener(this);
            super.setOnTouchListener(baldButtonTouchListener);
            super.setOnClickListener(D.EMPTY_CLICK_LISTENER);
        } else {
            super.setOnLongClickListener(this);
            super.setOnClickListener(this);
        }
    else
        super.setOnClickListener(this);
}
 
Example #8
Source Project: focus-android   Author: mozilla-mobile   File: Locales.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get a Resources instance with the currently selected locale applied.
 */
public static Resources getLocalizedResources(Context context) {
    final Resources currentResources = context.getResources();

    final Locale currentLocale = LocaleManager.getInstance().getCurrentLocale(context);
    @SuppressWarnings("deprecation") final Locale viewLocale = currentResources.getConfiguration().locale;

    if (currentLocale == null || viewLocale == null) {
        return currentResources;
    }

    if (currentLocale.toLanguageTag().equals(viewLocale.toLanguageTag())) {
        return currentResources;
    }

    final Configuration configuration = new Configuration(currentResources.getConfiguration());
    configuration.setLocale(currentLocale);

    return context.createConfigurationContext(configuration).getResources();
}
 
Example #9
Source Project: alynx-live-wallpaper   Author: AlynxZhou   File: LWApplication.java    License: Apache License 2.0 6 votes vote down vote up
private static void saveWallpaperCardPreference(@NonNull final Context context, final WallpaperCard wallpaperCard) {
    final SharedPreferences pref = context.getSharedPreferences(CURRENT_CARD_PREF, MODE_PRIVATE);
    // Save to preference.
    final SharedPreferences.Editor prefEditor = pref.edit();
    prefEditor.putString("name", wallpaperCard.getName());
    prefEditor.putString("path", wallpaperCard.getPath());
    switch (wallpaperCard.getType()) {
    case INTERNAL:
        prefEditor.putString("type",  "INTERNAL");
        break;
    case EXTERNAL:
        prefEditor.putString("type", "EXTERNAL");
        break;
    }
    prefEditor.apply();
}
 
Example #10
Source Project: sana.mobile   Author: SanaMobile   File: MDSInterface2.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static URI getURI(Context c, String path, String query) throws URISyntaxException {
    SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(c);

    String scheme = getScheme(preferences);
    String host = preferences.getString(Constants.PREFERENCE_MDS_URL,
            c.getString(R.string.host_mds));
    int port = getPort(c);
    String root = c.getString(R.string.path_root);
    Log.i(TAG, " path:" + root + path);
    URI uri = new URI(scheme, null, host, port, root + path, query, null);
    Log.i(TAG, "uri: " + uri.toString() + ", path:" + path);
    return uri;
}
 
Example #11
Source Project: LibreNews-Android   Author: milesmcc   File: SyncManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).getBoolean("wifi_sync_only", false)) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        int networkType = connManager.getActiveNetworkInfo().getType();
        if(networkType != ConnectivityManager.TYPE_WIFI){
            sendDebugNotification("Not on WiFi, not syncing...", context);
            return;
        }
    }
    sendDebugNotification("Syncing with server...", context);
    FlashManager flashManager = new FlashManager(context);
    flashManager.refresh();
    sendDebugNotification("Sync completed!", context);
}
 
Example #12
Source Project: OPFPush   Author: onepf   File: RetryBroadcastReceiver.java    License: Apache License 2.0 5 votes vote down vote up
private void checkRegistering(@NonNull final Context context,
                              @NonNull final OPFPushHelper helper,
                              @NonNull final String providerName) {
    OPFLog.logMethod(context, helper, providerName);
    if (helper.isRegistering()) {
        Settings.getInstance(context).saveState(State.UNREGISTERED);
        helper.registerNextAvailableProvider(providerName);
    }
}
 
Example #13
Source Project: easydeviceinfo   Author: nisrulz   File: EasyNetworkMod.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets SSID of Connected WiFi
 *
 * You need to declare the below permission in the manifest file to use this properly
 *
 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 *
 * @return Returns the service set identifier (SSID) of the current 802.11 network
 */
@RequiresPermission(allOf = {
    Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE
})
public final String getWifiSSID() {
  String result = null;
  if (PermissionUtil.hasPermission(context, Manifest.permission.ACCESS_WIFI_STATE)) {
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
      NetworkInfo networkInfo = cm.getActiveNetworkInfo();
      if (networkInfo == null) {
        result = null;
      }

      if (networkInfo != null && networkInfo.isConnected()) {
        final WifiManager wifiManager =
            (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
          final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
          if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
            result = connectionInfo.getSSID();
          }
        }
      }
    }
  }
  return CheckValidityUtil.checkValidData(result);
}
 
Example #14
Source Project: Slide   Author: ccrama   File: PopulateNewsViewHolder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void doText(NewsViewHolder holder, Submission submission, Context mContext,
        String baseSub) {
    SpannableStringBuilder t = SubmissionCache.getTitleLine(submission, mContext);
    SpannableStringBuilder l = SubmissionCache.getInfoLine(submission, mContext, baseSub);

    int[] textSizeAttr = new int[]{R.attr.font_cardtitle, R.attr.font_cardinfo};
    TypedArray a = mContext.obtainStyledAttributes(textSizeAttr);
    int textSizeT = a.getDimensionPixelSize(0, 18);
    int textSizeI = a.getDimensionPixelSize(1, 14);

    a.recycle();

    t.setSpan(new AbsoluteSizeSpan(textSizeT), 0, t.length(), 0);
    l.setSpan(new AbsoluteSizeSpan(textSizeI), 0, l.length(), 0);

    SpannableStringBuilder s = new SpannableStringBuilder();
    if (SettingValues.titleTop) {
        s.append(t);
        s.append("\n");
        s.append(l);
    } else {
        s.append(l);
        s.append("\n");
        s.append(t);
    }

    holder.title.setText(s);

}
 
Example #15
Source Project: here-android-sdk-examples   Author: heremaps   File: BasicVenueActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Only when the app's target SDK is 23 or higher, it requests each dangerous permissions it
 * needs when the app is running.
 */
private static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}
 
Example #16
Source Project: HaoReader   Author: Invinciblelee   File: ScrimInsetsRelativeLayout.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void init(Context context, AttributeSet attrs, int defStyle) {
    final TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.ScrimInsetsRelativeLayout, defStyle, 0);
    mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsRelativeLayout_appInsetForeground);
    mConsumeInsets = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_appConsumeInsets, true);
    mFitTop = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitTop, true);
    mFitBottom = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitBottom, false);
    mFitLeft = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitLeft, false);
    mFitRight = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitRight, false);
    a.recycle();

    setWillNotDraw(true);
    ViewCompat.setOnApplyWindowInsetsListener(this, (v, insets) -> {
        if (!mConsumeInsets) {
            if (mOnInsetsCallback != null) {
                mOnInsetsCallback.onInsetsChanged(new Rect(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()));
            }
            return insets.consumeSystemWindowInsets();
        }

        if (null == ScrimInsetsRelativeLayout.this.mInsets) {
            ScrimInsetsRelativeLayout.this.mInsets = new Rect();
        }

        ScrimInsetsRelativeLayout.this.mInsets.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
        ScrimInsetsRelativeLayout.this.onInsetsChanged(ScrimInsetsRelativeLayout.this.mInsets);
        ScrimInsetsRelativeLayout.this.setWillNotDraw(!insets.hasSystemWindowInsets() || ScrimInsetsRelativeLayout.this.mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(ScrimInsetsRelativeLayout.this);
        return insets.consumeSystemWindowInsets();
    });
}
 
Example #17
Source Project: springreplugin   Author: wangyupeng1-iri   File: PackageFilesUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 检查 files 目录下个某个文件是否已经为最新(比 assets 目录下的新)
 *
 * @param c
 * @param filename
 * @return 如果文件比 assets 下的同名文件的时间戳旧,或者文件不存在,则返回 false.
 */
public static boolean isFileUpdated(Context c, String filename) {
    File file = c.getFileStreamPath(filename);
    if (file == null) {
        return false;
    }
    if (!file.exists()) {
        return false;
    }

    long timestampOfFile = getFileTimestamp(c, filename);
    long timestampOfAsset = getBundleTimestamp(c, filename);

    return (timestampOfAsset <= timestampOfFile);
}
 
Example #18
Source Project: delion   Author: derry   File: PrivacyPreferencesManager.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean isMobileNetworkCapable() {
    ConnectivityManager connectivityManager =
            (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    // Android telephony team said it is OK to continue using getNetworkInfo() for our purposes.
    // We cannot use ConnectivityManager#getAllNetworks() because that one only reports enabled
    // networks. See crbug.com/532455.
    @SuppressWarnings("deprecation")
    NetworkInfo networkInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    return networkInfo != null;
}
 
Example #19
Source Project: glide-support   Author: TWiStErRob   File: GlideModule.java    License: The Unlicense 5 votes vote down vote up
@Override public void registerComponents(Context context, Glide glide) {
	// just to see the headers actually went through, Stetho or proxy can also be used for this
	glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient.Builder()
			.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
			.build()));
	// override default loader with one that attaches headers
	glide.register(String.class, InputStream.class, new HeaderedLoader.Factory());
}
 
Example #20
Source Project: Android-Universal-Image-Loader-Modify   Author: jiangqqlmj   File: UILWidgetProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
	UILApplication.initImageLoader(context);

	final int widgetCount = appWidgetIds.length;
	for (int i = 0; i < widgetCount; i++) {
		int appWidgetId = appWidgetIds[i];
		updateAppWidget(context, appWidgetManager, appWidgetId);
	}
}
 
Example #21
Source Project: XPrivacy   Author: M66B   File: PrivacyManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static TreeMap<String, String> getRestrictions(Context context) {
	Collator collator = Collator.getInstance(Locale.getDefault());
	TreeMap<String, String> tmRestriction = new TreeMap<String, String>(collator);
	for (String restrictionName : getRestrictions()) {
		int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string",
				context.getPackageName());
		tmRestriction.put(stringId == 0 ? restrictionName : context.getString(stringId), restrictionName);
	}
	return tmRestriction;
}
 
Example #22
Source Project: letv   Author: JackChan1999   File: LetvVideoViewBuilder4D.java    License: Apache License 2.0 5 votes vote down vote up
public LetvMediaPlayerControl4D build(Context context, Type type) {
    LogTag.i("Create player, type=" + (type != null ? type.toString() : "null") + ", version=" + 1.4f);
    switch ($SWITCH_TABLE$com$letv$component$player$fourd$LetvVideoViewBuilder4D$Type()[type.ordinal()]) {
        case 1:
            return new VideoViewH264mp4_4D(context);
        case 2:
            return new VideoViewH264m3u8_4D(context);
        case 3:
            return new VideoViewH264m3u8Hw_4D(context);
        case 4:
            return new VideoViewH264LeMobile_4D(context);
        default:
            return null;
    }
}
 
Example #23
Source Project: giraff-android   Author: asm-products   File: CardContainer.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public CardContainer(Context context) {
    super(context);

    setOrientation(Orientation.Disordered);
    setGravity(Gravity.CENTER);
    init();

}
 
Example #24
Source Project: aosp_screen_stabilization   Author: ryanchyshyn   File: StabilizationService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
	unregisterAccListener();
	setSurfaceFlingerTranslate(0, 0);
	Log.d(TAG, "Screen is off");
}
 
Example #25
Source Project: ForceTouch   Author: michelelacorte   File: ForceTouchListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Public constructor with only Context, millisToVibrate and pressureLimit is setted by default
 * @param context Context
 * @param forceTouchExecution Callback
 * @param isProgressive boolean
 */
public ForceTouchListener(Context context, boolean isProgressive, boolean isVibrate, Callback forceTouchExecution){
    this.context = context;
    this.millisToVibrate = DEFAULT_MILLIS_TO_VIBRATE;
    this.pressureLimit = DEFAULT_PRESSURE_LIMIT;
    this.forceTouchExecution = forceTouchExecution;
    this.isProgressive = isProgressive;
    this.isVibrate = isVibrate;
}
 
Example #26
Source Project: VideoCompressor   Author: fishwjy   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static void writeFile(Context context){
    try {
        OutputStream os = getLogStream(context);
        os.write(getInformation(context).getBytes("utf-8"));
        os.flush();
        os.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
 
Example #27
Source Project: letv   Author: JackChan1999   File: SplashActivity.java    License: Apache License 2.0 5 votes vote down vote up
public static void initLesoApplication() {
    AMapLocationTool.getInstance().location();
    if (!isFirstInitLeso) {
        Class clazz_lesoinit = JarLoader.loadClass(LetvApplication.getInstance().getApplicationContext(), "LetvLeso.apk", JarConstant.LETV_LESO_PACKAGENAME, "utils.LesoInitData");
        if (clazz_lesoinit != null && clazz_lesoinit != null) {
            JarLoader.invokeStaticMethod(clazz_lesoinit, "initData", new Class[]{Context.class}, new Object[]{LetvApplication.getInstance().getApplicationContext()});
            isFirstInitLeso = true;
        }
    }
}
 
Example #28
Source Project: EventApp   Author: mhidaka   File: AssetsLoader.java    License: Apache License 2.0 5 votes vote down vote up
public static String load(Context context, String fileName) {
    try {
        return IOUtils.toString(context.getResources().getAssets().open(fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #29
Source Project: Slide   Author: ccrama   File: Submit.java    License: GNU General Public License v3.0 5 votes vote down vote up
public File createFile(Uri uri, @NonNull Context context) {
    InputStream in;
    ContentResolver resolver = context.getContentResolver();
    String type = resolver.getType(uri);
    String extension;

    if ("image/png".equals(type)) {
        extension = ".gif";
    } else if ("image/png".equals(type)) {
        extension = ".png";
    } else {
        extension = ".jpg";
    }

    try {
        in = resolver.openInputStream(uri);
    } catch (FileNotFoundException e) {
        return null;
    }

    // Create files from a uri in our cache directory so they eventually get deleted
    String timeStamp = String.valueOf(System.currentTimeMillis());
    File cacheDir = ((Reddit) context.getApplicationContext()).getImageLoader()
            .getDiskCache()
            .getDirectory();
    File tempFile = new File(cacheDir, timeStamp + extension);

    if (writeInputStreamToFile(in, tempFile)) {
        return tempFile;
    } else {
        // If writeInputStreamToFile fails, delete the excess file
        tempFile.delete();
    }

    return null;
}
 
Example #30
Source Project: Mizuu   Author: MizzleDK   File: IdentifyTvShowEpisodeFragment.java    License: Apache License 2.0 5 votes vote down vote up
public TvShowSearch(Context context, String query) {
    mContext = context;
    mQueryText = query;

    // Execute the AsyncTask
    execute();
}