@SuppressWarnings("deprecation") public static ContextWrapper wrap(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String lang = prefs.getString(Constants.PREF_APP_LANGUAGE, ""); Locale locale = StringUtils.getLocale(lang); locale = (locale == null) ? Locale.getDefault() : locale; Configuration configuration = context.getResources().getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { LocaleList localeList = new LocaleList(locale); LocaleList.setDefault(localeList); Locale.setDefault(locale); configuration.setLocale(locale); configuration.setLocales(localeList); context = context.createConfigurationContext(configuration); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(locale); context = context.createConfigurationContext(configuration); } else { configuration.locale = locale; context.getResources().updateConfiguration(configuration, null); } return new InventumContextWrapper(context); }
@NonNull private void resolveMethod(@Nullable Context context, @NonNull String name) { while (context != null) { try { if (!context.isRestricted()) { Method method = context.getClass().getMethod(this.mMethodName, new Class[]{View.class}); if (method != null) { this.mResolvedMethod = method; this.mResolvedContext = context; return; } } } catch (NoSuchMethodException e) { } if (context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } else { context = null; } } int id = this.mHostView.getId(); throw new IllegalStateException("Could not find method " + this.mMethodName + "(View) in a parent or ancestor Context for android:onClick " + "attribute defined on view " + this.mHostView.getClass() + (id == -1 ? "" : " with id '" + this.mHostView.getContext().getResources().getResourceEntryName(id) + "'")); }
/** * 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(); }
/** * Get the Activity of a context. This is typically used to determine the hosting activity of a * {@link View} * * @param context The context * @return The Activity or throws an Exception if Activity couldnt be determined */ @NonNull public static Activity getActivity(@NonNull Context context) { if (context == null) { throw new NullPointerException("context == null"); } if (context instanceof Activity) { return (Activity) context; } while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } throw new IllegalStateException("Could not find the surrounding Activity"); }
@SuppressWarnings("deprecation") public static ContextWrapper wrap(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String lang = prefs.getString(Constants.PREF_APP_LANGUAGE, ""); Locale locale = StringUtils.getLocale(lang); locale = (locale == null) ? Locale.getDefault() : locale; Configuration configuration = context.getResources().getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { LocaleList localeList = new LocaleList(locale); LocaleList.setDefault(localeList); Locale.setDefault(locale); configuration.setLocale(locale); configuration.setLocales(localeList); context = context.createConfigurationContext(configuration); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(locale); context = context.createConfigurationContext(configuration); } else { configuration.locale = locale; context.getResources().updateConfiguration(configuration, null); } return new ShowChatContextWrapper(context); }
@SuppressWarnings("deprecation") public static ContextWrapper wrap(Context context, String language) { Configuration config = context.getResources().getConfiguration(); Locale sysLocale = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { sysLocale = getSystemLocale(config); } else { sysLocale = getSystemLocaleLegacy(config); } if (!language.equals("") && !sysLocale.getLanguage().equals(language)) { Locale locale = new Locale(language); Locale.setDefault(locale); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { setSystemLocale(config, locale); } else { setSystemLocaleLegacy(config, locale); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { context = context.createConfigurationContext(config); } else { context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); } } return new MyContextWrapper(context); }
/** * @param token The {@link ServiceToken} to unbind from */ 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; } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_whitelist); if (getSupportActionBar() != null) { getSupportActionBar().setElevation(0.0f); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } new Prefs.Builder() .setContext(this) .setMode(ContextWrapper.MODE_PRIVATE) .setPrefsName(getPackageName()) .setUseDefaultSharedPreference(true) .build(); whitelistArray = Prefs.getOrderedStringSet("whitelistArray", new LinkedHashSet<String>()); listView = (RecyclerView) findViewById(R.id.listView1); RecyclerView.LayoutManager manager = new LinearLayoutManager(this); listView.setLayoutManager(manager); listView.setHasFixedSize(true); listView.setAdapter(new RecyclerAdapter(whitelistArray.toArray(new String[whitelistArray.size()]))); }
@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); }
private Activity extractActivity(Context context) { while (true) { if (context instanceof Application) { return null; } else if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { Context baseContext = ((ContextWrapper) context).getBaseContext(); // Prevent Stack Overflow. if (baseContext == context) { return null; } context = baseContext; } else { return null; } } }
@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()); }
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; } }; }
@SmallTest @Feature({"Cronet"}) public void testInitDifferentEngines() throws Exception { // Test that concurrently instantiating Cronet context's upon various // different versions of the same Android Context does not cause crashes // like crbug.com/453845 mTestFramework = startCronetTestFramework(); CronetEngine firstEngine = new CronetUrlRequestContext(mTestFramework.createCronetEngineBuilder(getContext())); CronetEngine secondEngine = new CronetUrlRequestContext( mTestFramework.createCronetEngineBuilder(getContext().getApplicationContext())); CronetEngine thirdEngine = new CronetUrlRequestContext( mTestFramework.createCronetEngineBuilder(new ContextWrapper(getContext()))); firstEngine.shutdown(); secondEngine.shutdown(); thirdEngine.shutdown(); }
public void popFromActivityStack(Activity activity) { if(sReminderDialog!=null && (sReminderDialog.getContext()==activity || (sReminderDialog.getContext() instanceof ContextWrapper && ((ContextWrapper)sReminderDialog.getContext()).getBaseContext()==activity))){ try{ sReminderDialog.dismiss(); }catch (Throwable e){}finally { sReminderDialog = null; } } for(int x=0; x<activityList.size(); x++){ WeakReference<Activity> ref = activityList.get(x); if(ref!=null && ref.get()!=null && ref.get()==activity){ activityList.remove(ref); } } }
@Override public void callActivityOnCreate(Activity activity, Bundle icicle) { final Intent intent = activity.getIntent(); if (PluginUtil.isIntentFromPlugin(intent)) { Context base = activity.getBaseContext(); try { LoadedPlugin plugin = this.mPluginManager.getLoadedPlugin(intent); ReflectUtil.setField(base.getClass(), base, "mResources", plugin.getResources()); ReflectUtil.setField(ContextWrapper.class, activity, "mBase", plugin.getPluginContext()); ReflectUtil.setField(Activity.class, activity, "mApplication", plugin.getApplication()); ReflectUtil.setFieldNoException(ContextThemeWrapper.class, activity, "mBase", plugin.getPluginContext()); // set screenOrientation ActivityInfo activityInfo = plugin.getActivityInfo(PluginUtil.getComponent(intent)); if (activityInfo.screenOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) { activity.setRequestedOrientation(activityInfo.screenOrientation); } } catch (Exception e) { e.printStackTrace(); } } mBase.callActivityOnCreate(activity, icicle); }
@Test @SuppressLint("HardwareIds") public void testNullDeviceIdKit() throws NameNotFoundException { final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "NullDeviceId", new CondomOptions().addKit(new NullDeviceIdKit())); final TelephonyManager tm = (TelephonyManager) condom.getSystemService(Context.TELEPHONY_SERVICE); assertNotNull(tm); assertTrue(tm.getClass().getName().startsWith(NullDeviceIdKit.class.getName())); final TelephonyManager app_tm = (TelephonyManager) condom.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); assertNotNull(app_tm); assertTrue(app_tm.getClass().getName().startsWith(NullDeviceIdKit.class.getName())); assertPermission(condom, READ_PHONE_STATE, true); assertNull(tm.getDeviceId()); if (SDK_INT >= LOLLIPOP) { 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()); }
private void copyDataBase(String finalDbName) { Context applicationContext = InstrumentationRegistry.getTargetContext(); ContextWrapper cw = new ContextWrapper(applicationContext); File dbDir = new File(getDBDirectory()); if(!dbDir.exists()) { dbDir.mkdir(); } Logger.d("Database", "New database is being copied to device!"); byte[] buffer = new byte[1024]; int length; try { InputStream myInput = applicationContext.getResources().openRawResource(this.dbRawResourceId); File file = new File(dbDir , finalDbName); OutputStream myOutput = new FileOutputStream(file); while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.close(); myOutput.flush(); myInput.close(); Logger.d("Database", "New database has been copied to device!"); } catch (IOException e) { Logger.e("Database", e.getMessage(), e); } }
/** * Attempt to find the Activity in the Context through the chain of its base contexts. * * @throws IllegalArgumentException if context is null * @throws IllegalStateException if the context's base context hierarchy doesn't contain an Activity * * @param context the context * @param <T> the type of the Activity * @return the Activity */ @NonNull public static <T extends Activity> T findActivity(@NonNull Context context) { if(context == null) { throw new IllegalArgumentException("Context cannot be null!"); } if(context instanceof Activity) { // noinspection unchecked return (T) context; } else { ContextWrapper contextWrapper = (ContextWrapper) context; Context baseContext = contextWrapper.getBaseContext(); if(baseContext == null) { throw new IllegalStateException("Activity was not found as base context of view!"); } return findActivity(baseContext); } }
public static Activity scanForActivity(Context cont) { if (cont == null) return null; else if (cont instanceof Activity) return (Activity) cont; else if (cont instanceof ContextWrapper) return scanForActivity(((ContextWrapper) cont).getBaseContext()); return null; }
public static boolean isActivityContext(Context context) { if (context instanceof Activity) return true; if (context instanceof ContextWrapper) { return isActivityContext(((ContextWrapper) context).getBaseContext()); } return false; }
private boolean isActivityContext(Context context) { if (context == null) return false; if (context instanceof Activity) { return !((Activity) context).isFinishing(); } if (context instanceof ContextWrapper) { return isActivityContext(((ContextWrapper) context).getBaseContext()); } return false; }
/*** * 得到活动对象 * * @param context 上下文 * @return Activity activity */ 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; }
public RequestManager get(Context context) { if (context == null) { throw new IllegalArgumentException("You cannot start a load on a null Context"); } else if (Util.isOnMainThread() && !(context instanceof Application)) { if (context instanceof FragmentActivity) { return get((FragmentActivity) context); } else if (context instanceof Activity) { return get((Activity) context); } else if (context instanceof ContextWrapper) { return get(((ContextWrapper) context).getBaseContext()); } } return getApplicationManager(context); }
private Activity findActivity(Context context) { if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return findActivity(((ContextWrapper) context).getBaseContext()); } else { return null; } }
@Test public void testHandlesContextWrappersForActivities() { RetrieverHarness harness = new DefaultRetrieverHarness(); RequestManager requestManager = harness.doGet(); ContextWrapper contextWrapper = new ContextWrapper(harness.getController().get()); assertEquals(requestManager, retriever.get(contextWrapper)); }
/** * Resolves bug #161. Necessary when {@code theme} attribute is used in the layout. * Used by {@code FlexibleAdapter.getStickyHeaderContainer()} method. */ //TODO: review comment public static Activity scanForActivity(Context context) { if (context instanceof Activity) return (Activity) context; else if (context instanceof ContextWrapper) return scanForActivity(((ContextWrapper) context).getBaseContext()); return null; }
/** * 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; }
@Test public void testHandlesContextWrappersForApplication() { ContextWrapper contextWrapper = new ContextWrapper(RuntimeEnvironment.application); RequestManager requestManager = retriever.get(RuntimeEnvironment.application); assertEquals(requestManager, retriever.get(contextWrapper)); }
public 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; }
/** * If given context is an instance of ListenableActivity then creates new instance of * WeakReferenceActivityListenerAdapter and adds it to activity's listeners */ public static void register( ActivityListener activityListener, Context context) { if (!(context instanceof ListenableActivity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (context instanceof ListenableActivity) { ListenableActivity listenableActivity = (ListenableActivity) context; Listener listener = new Listener(activityListener); listenableActivity.addActivityListener(listener); } }