Java Code Examples for android.content.ContextWrapper
The following examples show how to use
android.content.ContextWrapper.
These examples are extracted from open source projects.
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: DragerViewLayout Author: loonggg File: SharedPreferencesUtil.java License: Apache License 2.0 | 7 votes |
/** * 从文件中读取数据 * * @param context * @param key * @param defValue * @return */ public static Object getData(Context context, String key, Object defValue) { try { //利用java反射机制将XML文件自定义存储 Field field; // 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象 field = ContextWrapper.class.getDeclaredField("mBase"); field.setAccessible(true); // 获取mBase变量 Object obj = field.get(context); // 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径 field = obj.getClass().getDeclaredField("mPreferencesDir"); field.setAccessible(true); // 创建自定义路径 File file = new File(FILE_PATH); // 修改mPreferencesDir变量的值 field.set(obj, file); String type = defValue.getClass().getSimpleName(); SharedPreferences sharedPreferences = context.getSharedPreferences (FILE_NAME, Context.MODE_PRIVATE); //defValue为为默认值,如果当前获取不到数据就返回它 if ("Integer".equals(type)) { return sharedPreferences.getInt(key, (Integer) defValue); } else if ("Boolean".equals(type)) { return sharedPreferences.getBoolean(key, (Boolean) defValue); } else if ("String".equals(type)) { return sharedPreferences.getString(key, (String) defValue); } else if ("Float".equals(type)) { return sharedPreferences.getFloat(key, (Float) defValue); } else if ("Long".equals(type)) { return sharedPreferences.getLong(key, (Long) defValue); } return null; } catch (Exception e) { return defValue; } }
Example #2
Source Project: ans-android-sdk Author: analysys File: AllegroUtils.java License: GNU General Public License v3.0 | 6 votes |
/** * 通过上下问获取activity */ private static Activity getActivityFromContext(Context context) { if (context != null) { if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (context instanceof Activity) { return (Activity) context; } } } return getCurAc(); }
Example #3
Source Project: ThemeDemo Author: zzz40500 File: LayoutInflaterFactory2.java License: Apache License 2.0 | 6 votes |
/** * android:onClick doesn't handle views with a ContextWrapper context. This method * backports new framework functionality to traverse the Context wrappers to find a * suitable target. */ private void checkOnClickListener(View view, AttributeSet attrs) { final Context context = view.getContext(); if (!(context instanceof ContextWrapper) || (Build.VERSION.SDK_INT >= 15 && !ViewCompat.hasOnClickListeners(view))) { // Skip our compat functionality if: the Context isn't a ContextWrapper, or // the view doesn't have an OnClickListener (we can only rely on this on API 15+ so // always use our compat code on older devices) return; } final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs); final String handlerName = a.getString(0); if (handlerName != null) { view.setOnClickListener(new DeclaredOnClickListener(view, handlerName)); } a.recycle(); }
Example #4
Source Project: OpenMapKitAndroid Author: posm File: OfflineMapDownloader.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
private OfflineMapDownloader(Context context) { super(); this.context = context; listeners = new ArrayList<OfflineMapDownloaderListener>(); mutableOfflineMapDatabases = new ArrayList<OfflineMapDatabase>(); // Load OfflineMapDatabases from File System ContextWrapper cw = new ContextWrapper(context); for (String s : cw.databaseList()) { if (!s.toLowerCase().contains("partial") && !s.toLowerCase().contains("journal")) { // Setup Database Handler OfflineDatabaseManager.getOfflineDatabaseManager(context).getOfflineDatabaseHandlerForMapId(s, true); // Create the Database Object OfflineMapDatabase omd = new OfflineMapDatabase(context, s); omd.initializeDatabase(); mutableOfflineMapDatabases.add(omd); } } this.state = MBXOfflineMapDownloaderState.MBXOfflineMapDownloaderStateAvailable; }
Example #5
Source Project: react-native-GPay Author: hellochirag File: ContextUtils.java License: MIT License | 6 votes |
/** * Returns the nearest context in the chain (as defined by ContextWrapper.getBaseContext()) which * is an instance of the specified type, or null if one could not be found * * @param context Initial context * @param clazz Class instance to look for * @param <T> * @return the first context which is an instance of the specified class, or null if none exists */ public static @Nullable <T> T findContextOfType( @Nullable Context context, Class<? extends T> clazz) { while (!(clazz.isInstance(context))) { if (context instanceof ContextWrapper) { Context baseContext = ((ContextWrapper) context).getBaseContext(); if (context == baseContext) { return null; } else { context = baseContext; } } else { return null; } } return (T) context; }
Example #6
Source Project: container Author: codehz File: NotificationCompatCompatV14.java License: GNU General Public License v3.0 | 6 votes |
Context getAppContext(final String packageName) { final Resources resources = getResources(packageName); Context context = null; try { context = getHostContext().createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE); } catch (PackageManager.NameNotFoundException e) { context = getHostContext(); } return new ContextWrapper(context) { @Override public Resources getResources() { return resources; } @Override public String getPackageName() { return packageName; } }; }
Example #7
Source Project: test-butler Author: linkedin File: GsmDataDisabler.java License: Apache License 2.0 | 6 votes |
boolean setGsmState(boolean enabled) throws RemoteException { Object manager; Method method; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { throw ExceptionCreator.createRemoteException(TAG, "Api before " + Build.VERSION_CODES.KITKAT + " not supported because of WTF", null); } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { manager = serviceManager.getIService(Context.CONNECTIVITY_SERVICE, "android.net.IConnectivityManager"); method = getMethod(ConnectivityManager.class, "setMobileDataEnabled", boolean.class); method.setAccessible(true); invoke(method, manager, enabled); method.setAccessible(false); } else { manager = serviceManager.getIService(ContextWrapper.TELEPHONY_SERVICE, "com.android.internal.telephony.ITelephony"); if (enabled) { invoke(getMethod(manager.getClass(), "enableDataConnectivity"), manager); } else { invoke(getMethod(manager.getClass(), "disableDataConnectivity"), manager); } } return true; }
Example #8
Source Project: MiPushFramework Author: MiPushFramework File: CondomKitTest.java License: GNU General Public License v3.0 | 6 votes |
@Test @SuppressLint("HardwareIds") public void testNullDeviceIdKit() { final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "NullDeviceId", new CondomOptions().addKit(new NullDeviceIdKit())); final TelephonyManager tm = (TelephonyManager) condom.getSystemService(Context.TELEPHONY_SERVICE); assertTrue(condom.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE).getClass().getName().startsWith(NullDeviceIdKit.class.getName())); assertPermission(condom, READ_PHONE_STATE, true); assertNull(tm.getDeviceId()); if (SDK_INT >= M) assertNull(tm.getDeviceId(0)); assertNull(tm.getImei()); assertNull(tm.getImei(0)); if (SDK_INT >= O) assertNull(tm.getMeid()); if (SDK_INT >= O) assertNull(tm.getMeid(0)); assertNull(tm.getSimSerialNumber()); assertNull(tm.getLine1Number()); assertNull(tm.getSubscriberId()); }
Example #9
Source Project: kcanotify Author: antest1 File: KcaUtils.java License: GNU General Public License v3.0 | 6 votes |
public static JsonArray getJsonArrayFromStorage(Context context, String name, KcaDBHelper helper) { if (getBooleanPreferences(context, PREF_RES_USELOCAL)) { return getJsonArrayFromAsset(context, name, helper); } else { ContextWrapper cw = new ContextWrapper(context); File directory = cw.getDir("data", Context.MODE_PRIVATE); File jsonFile = new File(directory, name); JsonArray data = new JsonArray(); try { Reader reader = new FileReader(jsonFile); data = new JsonParser().parse(reader).getAsJsonArray(); reader.close(); } catch (IOException | IllegalStateException | JsonSyntaxException e ) { e.printStackTrace(); setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true); if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "0", getStringFromException(e)); data = getJsonArrayFromAsset(context, name, helper); } return data; } }
Example #10
Source Project: kcanotify_h5-master Author: qly5213 File: KcaUtils.java License: GNU General Public License v3.0 | 6 votes |
public static boolean validateResourceFiles(Context context, KcaDBHelper helper) { int count = 0; ContextWrapper cw = new ContextWrapper(context); File directory = cw.getDir("data", Context.MODE_PRIVATE); for (final File entry : directory.listFiles()) { try { Reader reader = new FileReader(entry); new JsonParser().parse(reader); count += 1; } catch (FileNotFoundException | IllegalStateException | JsonSyntaxException e ) { e.printStackTrace(); if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, entry.getName(), "validateResourceFiles", "2", getStringFromException(e)); setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true); return false; } } return count > 0; }
Example #11
Source Project: Carbon Author: ZieIony File: Toolbar.java License: Apache License 2.0 | 6 votes |
private void initLayout() { inflate(getContext(), R.layout.carbon_toolbar, this); super.setNavigationIcon(null); super.setTitle(null); content = findViewById(R.id.carbon_toolbarContent); title = findViewById(R.id.carbon_toolbarTitle); icon = findViewById(R.id.carbon_toolbarIcon); toolStrip = findViewById(R.id.carbon_toolbarMenu); icon.setOnClickListener(view -> { if (getContext() == null) return; Context context = getContext(); while (!(context instanceof Activity)) context = ((ContextWrapper) context).getBaseContext(); if (context instanceof UpAwareActivity) { ((UpAwareActivity) context).onUpPressed(); } else { ((Activity) context).onBackPressed(); } }); }
Example #12
Source Project: Neptune Author: iqiyi File: PluginLoadedApk.java License: Apache License 2.0 | 6 votes |
/** * 反射获取ActivityThread中的Instrumentation对象 * 从而拦截Activity跳转 */ @Deprecated private void hookInstrumentation() { try { Context contextImpl = ((ContextWrapper) mHostContext).getBaseContext(); Object activityThread = ReflectionUtils.getFieldValue(contextImpl, "mMainThread"); Field instrumentationF = activityThread.getClass().getDeclaredField("mInstrumentation"); instrumentationF.setAccessible(true); Instrumentation hostInstr = (Instrumentation) instrumentationF.get(activityThread); mPluginInstrument = new PluginInstrument(hostInstr, mPluginPackageName); } catch (Exception e) { ErrorUtil.throwErrorIfNeed(e); PluginManager.deliver(mHostContext, false, mPluginPackageName, ErrorType.ERROR_PLUGIN_HOOK_INSTRUMENTATION, "hookInstrumentation failed"); } }
Example #13
Source Project: DevUtils Author: afkT File: ActivityUtils.java License: Apache License 2.0 | 6 votes |
/** * 获取 View context 所属的 Activity * @param view {@link View} * @return {@link Activity} */ public static Activity getActivity(final View view) { if (view != null) { try { Context context = view.getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getActivity"); } } return null; }
Example #14
Source Project: ssj Author: hcmlab File: Visual.java License: GNU General Public License v3.0 | 6 votes |
private Activity getActivity(View view) { Context context = view.getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity)context; } context = ((ContextWrapper)context).getBaseContext(); } //alternative method View content = view.findViewById(android.R.id.content); if(content != null) return (Activity) content.getContext(); else return null; }
Example #15
Source Project: firebase-android-sdk Author: firebase File: CrashlyticsControllerTest.java License: Apache License 2.0 | 6 votes |
@Override public Context getContext() { // Return a context wrapper that will allow us to override the behavior of registering // the receiver for battery changed events. return new ContextWrapper(super.getContext()) { @Override public Context getApplicationContext() { return this; } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { // For the BatteryIntent, use test values to avoid breaking from emulator changes. if (filter.hasAction(Intent.ACTION_BATTERY_CHANGED)) { // If we ever call this with a receiver, it will be broken. assertNull(receiver); return BatteryIntentProvider.getBatteryIntent(); } return getBaseContext().registerReceiver(receiver, filter); } }; }
Example #16
Source Project: MTweaks-KernelAdiutorMOD Author: morogoku File: BaseActivity.java License: GNU General Public License v3.0 | 6 votes |
public static ContextWrapper wrap(Context context, Locale newLocale) { Resources res = context.getResources(); Configuration configuration = res.getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { configuration.setLocale(newLocale); LocaleList localeList = new LocaleList(newLocale); LocaleList.setDefault(localeList); configuration.setLocales(localeList); context = context.createConfigurationContext(configuration); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(newLocale); context = context.createConfigurationContext(configuration); } else { configuration.locale = newLocale; res.updateConfiguration(configuration, res.getDisplayMetrics()); } return new ContextWrapper(context); }
Example #17
Source Project: prayer-times-android Author: metinkale38 File: LocaleUtils.java License: Apache License 2.0 | 6 votes |
public static Context wrapContext(Context context) { Resources res = context.getResources(); Configuration configuration = res.getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { configuration.setLocale(getLocale()); LocaleList localeList = getLocales(); LocaleList.setDefault(localeList); configuration.setLocales(localeList); context = context.createConfigurationContext(configuration); } else { configuration.setLocale(getLocale()); context = context.createConfigurationContext(configuration); } return new ContextWrapper(context); }
Example #18
Source Project: nucleus Author: konmik File: NucleusLayout.java License: MIT License | 5 votes |
/** * Returns the unwrapped activity of the view or throws an exception. * * @return an unwrapped activity */ public Activity getActivity() { Context context = getContext(); while (!(context instanceof Activity) && context instanceof ContextWrapper) context = ((ContextWrapper) context).getBaseContext(); if (!(context instanceof Activity)) throw new IllegalStateException("Expected an activity context, got " + context.getClass().getSimpleName()); return (Activity) context; }
Example #19
Source Project: Augendiagnose Author: jeisfeld File: Application.java License: GNU General Public License v2.0 | 5 votes |
/** * Create a ContextWrapper, wrappint the context with a specific locale. * * @param context The original context. * @return The context wrapper. */ public static ContextWrapper createContextWrapperForLocale(final Context context) { Resources res = context.getResources(); Configuration configuration = res.getConfiguration(); Locale newLocale = getApplicationLocale(); Context newContext = context; if (VERSION.SDK_INT >= VERSION_CODES.N) { configuration.setLocale(newLocale); LocaleList localeList = new LocaleList(newLocale); LocaleList.setDefault(localeList); configuration.setLocales(localeList); newContext = context.createConfigurationContext(configuration); } else if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(newLocale); newContext = context.createConfigurationContext(configuration); } else { configuration.locale = newLocale; res.updateConfiguration(configuration, res.getDisplayMetrics()); } return new ContextWrapper(newContext); }
Example #20
Source Project: revolution-irc Author: MCMrARM File: LiveThemeComponent.java License: GNU General Public License v3.0 | 5 votes |
private static Resources.Theme getThemeForContext(Context context) { WeakReference<Resources.Theme> retWeak = sThemeCache.get(context); Resources.Theme ret = null; if (retWeak != null) ret = retWeak.get(); if (ret != null) return ret; if (context instanceof ContextWrapper) { Resources.Theme baseTheme = getThemeForContext(((ContextWrapper) context).getBaseContext()); ret = baseTheme; int childResId = 0; if (context instanceof androidx.appcompat.view.ContextThemeWrapper) { childResId = ((androidx.appcompat.view.ContextThemeWrapper) context) .getThemeResId(); } else if (context instanceof android.view.ContextThemeWrapper) { childResId = LiveThemeUtils.getContextThemeWrapperResId( (android.view.ContextThemeWrapper) context); } ThemeManager.ThemeResInfo t = ThemeManager.getInstance(context).getCurrentTheme(); if (childResId == t.getThemeResId() || childResId == t.getThemeNoActionBarResId()) childResId = R.style.LiveThemeHelperTheme; if (childResId != 0) { Resources.Theme newTheme = context.getResources().newTheme(); newTheme.setTo(baseTheme); newTheme.applyStyle(childResId, true); ret = newTheme; } } else { ret = context.getResources().newTheme(); } sThemeCache.put(context, new WeakReference<>(ret)); return ret; }
Example #21
Source Project: star-zone-android Author: bootsrc File: SharedPreferencesMyUtil.java License: Apache License 2.0 | 5 votes |
public static void storeHeadVersion(ContextWrapper contextWrapper, long headVersion) { if (contextWrapper == null) { return; } SharedPreferences sp = contextWrapper.getSharedPreferences(StorageConstant.SHARED_PREFERENCES_NAME_FILE_STORAGE , 0); SharedPreferences.Editor editor = sp.edit(); editor.putLong("headVersion", headVersion); editor.commit(); }
Example #22
Source Project: Android-Plugin-Framework Author: limpoxe File: PluginInjector.java License: MIT License | 5 votes |
static void replaceReceiverContext(Context baseContext, Context newBase) { if (HackContextImpl.instanceOf(baseContext)) { ContextWrapper receiverRestrictedContext = new HackContextImpl(baseContext).getReceiverRestrictedContext(); new HackContextWrapper(receiverRestrictedContext).setBase(newBase); } }
Example #23
Source Project: material-components-android Author: material-components File: ContextUtilsTest.java License: Apache License 2.0 | 5 votes |
@Test public void testWithContextWrapper() { ApplicationProvider.getApplicationContext().setTheme(R.style.Theme_AppCompat); AppCompatActivity appCompatActivity = Robolectric.setupActivity(AppCompatActivity.class); ContextWrapper contextWrapper = new ContextWrapper(appCompatActivity); Activity activity = ContextUtils.getActivity(contextWrapper); Assert.assertNotNull(activity); }
Example #24
Source Project: prayer-times-android Author: metinkale38 File: CalendarIntegrationPreference.java License: Apache License 2.0 | 5 votes |
private Activity getActivity() { Context c = getContext(); while ((c instanceof ContextWrapper) && !(c instanceof Activity)) { c = ((ContextWrapper) c).getBaseContext(); } if (c instanceof Activity) { return (Activity) c; } return null; }
Example #25
Source Project: star-zone-android Author: bootsrc File: SharedPreferencesMyUtil.java License: Apache License 2.0 | 5 votes |
public static void storeMiRegid(ContextWrapper contextWrapper, String regid) { if (contextWrapper == null) { return; } SharedPreferences sp = contextWrapper.getSharedPreferences(StorageConstant.SHARED_PREFERENCES_NAME_MIPUSH , 0); SharedPreferences.Editor editor = sp.edit(); editor.putString("regid", regid); editor.commit(); }
Example #26
Source Project: star-zone-android Author: bootsrc File: SharedPreferencesMyUtil.java License: Apache License 2.0 | 5 votes |
public static String queryMiRegid(ContextWrapper contextWrapper) { if (contextWrapper == null) { return null; } SharedPreferences sp = contextWrapper.getSharedPreferences(StorageConstant.SHARED_PREFERENCES_NAME_MIPUSH , 0); String regid = sp.getString("regid", ""); return regid; }
Example #27
Source Project: AndroidSlideBack Author: qinci File: Utils.java License: Apache License 2.0 | 5 votes |
static Activity getActivityContext(Context context) { if (context == null) return null; else if (context instanceof Activity) return (Activity) context; else if (context instanceof ContextWrapper) return getActivityContext(((ContextWrapper) context).getBaseContext()); return null; }
Example #28
Source Project: scene Author: bytedance File: SceneNavigator.java License: Apache License 2.0 | 5 votes |
public SceneNavigator(@NonNull Context context, @StyleRes int themeResId, @Nullable List<SceneNavigationContainer> containerList) { mContext = context; mThemeResId = themeResId; while (context instanceof ContextWrapper) { if (context instanceof Activity) { mHostActivity = (Activity) context; break; } context = ((ContextWrapper) context).getBaseContext(); } this.mContainerList = containerList; }
Example #29
Source Project: Applozic-Android-SDK Author: AppLozic File: ApplozicComponents.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
public Activity getActivity() { Context context = getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } return null; }
Example #30
Source Project: AndroidComponentPlugin Author: androidmalin File: ContextImpl.java License: Apache License 2.0 | 5 votes |
static ContextImpl getImpl(Context context) { Context nextContext; while ((context instanceof ContextWrapper) && (nextContext=((ContextWrapper)context).getBaseContext()) != null) { context = nextContext; } return (ContextImpl)context; }