Java Code Examples for android.content.Context

The following examples show how to use android.content.Context. These examples are extracted from open source projects.
Example 1
Project: tinkerpatch-sdk   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 2
Project: SendBird-Android   File: GroupChatAdapter.java    License: MIT License 6 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 3
Project: exodus-android-app   File: TrackerFragment.java    License: GNU General Public License v3.0 6 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 4
Project: iMoney   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
Project: Equate   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
Project: meiShi   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
Project: BaldPhone   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
Project: focus-android   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
Project: alynx-live-wallpaper   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
Project: sana.mobile   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
Project: LibreNews-Android   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
Project: OPFPush   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
Project: easydeviceinfo   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
Project: Slide   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
Project: here-android-sdk-examples   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
Project: HaoReader   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
Project: springreplugin   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
Project: delion   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
Project: glide-support   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
Project: Android-Universal-Image-Loader-Modify   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
Project: XPrivacy   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
Project: letv   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
Project: giraff-android   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
Project: aosp_screen_stabilization   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
Project: ForceTouch   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
Project: VideoCompressor   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
Project: letv   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
Project: EventApp   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
Project: Slide   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
Project: Mizuu   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();
}
 
Example 31
Project: CryptoBuddy   File: DatabaseHelperSingleton.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static synchronized DatabaseHelperSingleton getInstance(Context context) {

        if (sInstance == null) {
            sInstance = new DatabaseHelperSingleton(context.getApplicationContext());
        }
        return sInstance;
    }
 
Example 32
Project: QuranAndroid   File: AudioManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean isConnectedToInternet(Context context) {
    try {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
        return false;
    } catch (Exception e) {
        Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
        return false;
    }
}
 
Example 33
Project: BtPlayer   File: XLTaskHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static XLTaskHelper instance(Context context) {
    if (instance == null) {
        synchronized (XLTaskHelper.class) {
            if (instance == null) {
                instance = new XLTaskHelper(context.getApplicationContext());
            }
        }

    }
    return instance;
}
 
Example 34
Project: Social   File: CircleImageView.java    License: Apache License 2.0 5 votes vote down vote up
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);

    mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
    mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);
    mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_civ_border_overlay, DEFAULT_BORDER_OVERLAY);
    mFillColor = a.getColor(R.styleable.CircleImageView_civ_fill_color, DEFAULT_FILL_COLOR);

    a.recycle();

    init();
}
 
Example 35
Project: kcanotify   File: KcaItemAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
public KcaItemAdapter(Context context, int layout, List<String> data) {
    this.context = context;
    this.layout = layout;
    this.item = data;
    inf = (LayoutInflater) context.getSystemService
            (Context.LAYOUT_INFLATER_SERVICE);
}
 
Example 36
Project: RecycleClick   File: ExampleInstrumentedTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void useAppContext() throws Exception {
    // Context of the app under test.
    Context appContext = InstrumentationRegistry.getTargetContext();

    assertEquals("com.chootdev.recycleviewclick", appContext.getPackageName());
}
 
Example 37
Project: android_9.0.0_r45   File: ImmersiveModeConfirmation.java    License: Apache License 2.0 5 votes vote down vote up
public ImmersiveModeConfirmation(Context context) {
    mContext = ActivityThread.currentActivityThread().getSystemUiContext();
    mHandler = new H();
    mShowDelayMs = getNavBarExitDuration() * 3;
    mPanicThresholdMs = context.getResources()
            .getInteger(R.integer.config_immersive_mode_confirmation_panic);
    mWindowManager = (WindowManager)
            mContext.getSystemService(Context.WINDOW_SERVICE);
}
 
Example 38
Project: carstream-android-auto   File: PlayerAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
        if (isPlaying()) {
            pause();
        }
    }
}
 
Example 39
Project: VideoRecord   File: ExampleInstrumentedTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void useAppContext() throws Exception {
    // Context of the app under test.
    Context appContext = InstrumentationRegistry.getTargetContext();

    assertEquals("com.example.administrator.videorecorddemo", appContext.getPackageName());
}
 
Example 40
Project: CPOrm   File: UriMatcherHelper.java    License: MIT License 5 votes vote down vote up
public static Uri.Builder generateItemUri(Context context, TableDetails tableDetails){

        String authority = tableDetails.getAuthority();
        return new Uri.Builder()
                .scheme("content")
                .authority(authority)
                .appendEncodedPath(tableDetails.getTableName());
    }