android.content.ContextWrapper Java Examples
The following examples show how to use
android.content.ContextWrapper.
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 File: SharedPreferencesUtil.java From DragerViewLayout with 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 File: OfflineMapDownloader.java From OpenMapKitAndroid with 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 #3
Source File: BaseActivity.java From MTweaks-KernelAdiutorMOD with 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 #4
Source File: LocaleUtils.java From prayer-times-android with 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 #5
Source File: CrashlyticsControllerTest.java From firebase-android-sdk with 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 #6
Source File: Visual.java From ssj with 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 #7
Source File: AllegroUtils.java From ans-android-sdk with 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 #8
Source File: LayoutInflaterFactory2.java From ThemeDemo with 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 #9
Source File: ActivityUtils.java From DevUtils with 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 #10
Source File: PluginLoadedApk.java From Neptune with 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 #11
Source File: Toolbar.java From Carbon with 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 File: ContextUtils.java From react-native-GPay with 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 #13
Source File: KcaUtils.java From kcanotify_h5-master with 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 #14
Source File: NotificationCompatCompatV14.java From container with 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 #15
Source File: KcaUtils.java From kcanotify with 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 #16
Source File: CondomKitTest.java From MiPushFramework with 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 #17
Source File: GsmDataDisabler.java From test-butler with 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 #18
Source File: Restarter.java From sbt-android-protify with Apache License 2.0 | 5 votes |
static void showToast(@NonNull final Activity activity, @NonNull final String text) { if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) { Log.v(LOG_TAG, "About to show toast for activity " + activity + ": " + text); } activity.runOnUiThread(new Runnable() { @Override public void run() { try { Context context = activity.getApplicationContext(); if (context instanceof ContextWrapper) { Context base = ((ContextWrapper) context).getBaseContext(); if (base == null) { if (Log.isLoggable(LOG_TAG, Log.WARN)) { Log.w(LOG_TAG, "Couldn't show toast: no base context"); } return; } } // For longer messages, leave the message up longer int duration = Toast.LENGTH_SHORT; if (text.length() >= 60 || text.indexOf('\n') != -1) { duration = Toast.LENGTH_LONG; } // Avoid crashing when not available, e.g. // java.lang.RuntimeException: Can't create handler inside thread that has // not called Looper.prepare() Toast.makeText(activity, text, duration).show(); } catch (Throwable e) { if (Log.isLoggable(LOG_TAG, Log.WARN)) { Log.w(LOG_TAG, "Couldn't show toast", e); } } } }); }
Example #19
Source File: ThemedImageView.java From PowerFileExplorer with GNU General Public License v3.0 | 5 votes |
private Activity getActivity() { Context context = getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity)context; } context = ((ContextWrapper)context).getBaseContext(); } return null; }
Example #20
Source File: WindowAndroid.java From 365browser with Apache License 2.0 | 5 votes |
/** * Extract the activity if the given Context either is or wraps one. * Only retrieve the base context if the supplied context is a {@link ContextWrapper} but not * an Activity, given that Activity is already a subclass of ContextWrapper. * @param context The context to check. * @return The {@link Activity} that is extracted through the given Context. */ public static Activity activityFromContext(Context context) { if (context instanceof Activity) { return ((Activity) context); } else if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); return activityFromContext(context); } else { return null; } }
Example #21
Source File: Camera2BasicFragment.java From opencv-documentscanner-android with Apache License 2.0 | 5 votes |
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ContextWrapper cw = new ContextWrapper(getActivity().getApplicationContext()); File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); mFile = new File(directory, System.currentTimeMillis() + ".png"); }
Example #22
Source File: PluginManagerImpl.java From koala--Android-Plugin-Runtime- with Apache License 2.0 | 5 votes |
/** * 初始化 * * @param context * 上下文 * @param dop * 插件dex的存放目录 */ void init(ContextWrapper context, String dop, String pluginRootDir) { mContext = context.getBaseContext(); mDexoutputPath = dop; if (!TextUtils.isEmpty(pluginRootDir)) { mPluginRootDir = new File(pluginRootDir); if (!mPluginRootDir.exists()) { mPluginRootDir.mkdirs(); } } mHandler = new Handler(Looper.getMainLooper()); Log.d(TAG, "start init environment"); initEnvironment(); Log.d(TAG, "after init environment"); }
Example #23
Source File: MusicPlayer.java From Muzesto with GNU General Public License v3.0 | 5 votes |
public static void unbindFromService(final ServiceToken token) { if (token == null) { return; } final ContextWrapper mContextWrapper = token.mWrappedContext; final ServiceBinder mBinder = mConnectionMap.remove(mContextWrapper); if (mBinder == null) { return; } mContextWrapper.unbindService(mBinder); if (mConnectionMap.isEmpty()) { mService = null; } }
Example #24
Source File: Restarter.java From android-advanced-decode with MIT License | 5 votes |
static void showToast(final Activity activity, final String text) { if (Log.isLoggable("InstantRun", 2)) { Log.v("InstantRun", "About to show toast for activity " + activity + ": " + text); } activity.runOnUiThread(new Runnable() { public void run() { try { Context context = activity.getApplicationContext(); if ((context instanceof ContextWrapper)) { Context base = ((ContextWrapper) context) .getBaseContext(); if (base == null) { if (Log.isLoggable("InstantRun", 5)) { Log.w("InstantRun", "Couldn't show toast: no base context"); } return; } } int duration = 0; if ((text.length() >= 60) || (text.indexOf('\n') != -1)) { duration = 1; } Toast.makeText(activity, text, duration).show(); } catch (Throwable e) { if (Log.isLoggable("InstantRun", 5)) { Log.w("InstantRun", "Couldn't show toast", e); } } } }); }
Example #25
Source File: ActivityUtils.java From v9porn with MIT License | 5 votes |
private static Activity scanForActivity(Context context) { if (context == null) { return null; } if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return scanForActivity(((ContextWrapper) context).getBaseContext()); } return null; }
Example #26
Source File: MaterialSpinner.java From MaterialSpinner with Apache License 2.0 | 5 votes |
private Activity getActivity() { Context context = getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } return null; }
Example #27
Source File: ContextUtils.java From SimpleSearchView with Apache License 2.0 | 5 votes |
@Nullable public static Activity scanForActivity(@NonNull Context context) { if (context instanceof Activity) return (Activity) context; else if (context instanceof ContextWrapper) return scanForActivity(((ContextWrapper) context).getBaseContext()); return null; }
Example #28
Source File: ComponentsPoolsTest.java From litho with Apache License 2.0 | 5 votes |
@Before public void setup() { mContext1 = getApplicationContext(); mContext2 = new ContextWrapper(getApplicationContext()); mActivityController = Robolectric.buildActivity(Activity.class).create(); mActivity = mActivityController.get(); mMountContent = new ColorDrawable(Color.RED); mNewMountContent = new View(mContext1); }
Example #29
Source File: MxUtils.java From MxVideoPlayer with Apache License 2.0 | 5 votes |
static Activity scanForActivity(Context context) { if (context == null) { return null; } if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return scanForActivity(((ContextWrapper) context).getBaseContext()); } return null; }
Example #30
Source File: SkinAppCompatViewInflater.java From ReadMark with Apache License 2.0 | 5 votes |
@NonNull private void resolveMethod(@Nullable Context context, @NonNull String name) { while (context != null) { try { if (!context.isRestricted()) { final Method method = context.getClass().getMethod(mMethodName, View.class); if (method != null) { mResolvedMethod = method; mResolvedContext = context; return; } } } catch (NoSuchMethodException e) { // Failed to find method, keep searching up the hierarchy. } if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { // Can't search up the hierarchy, null out and fail. context = null; } } final int id = mHostView.getId(); final String idText = id == View.NO_ID ? "" : " with id '" + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; throw new IllegalStateException("Could not find method " + mMethodName + "(View) in a parent or ancestor Context for android:onClick " + "attribute defined on view " + mHostView.getClass() + idText); }