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   Source File: SharedPreferencesUtil.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * 从文件中读取数据
 *
 * @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   Source File: AllegroUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 通过上下问获取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   Source File: LayoutInflaterFactory2.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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
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   Source File: ContextUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 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
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   Source File: GsmDataDisabler.java    License: Apache License 2.0 6 votes vote down vote up
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
@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   Source File: KcaUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
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   Source File: KcaUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
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   Source File: Toolbar.java    License: Apache License 2.0 6 votes vote down vote up
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   Source File: PluginLoadedApk.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 反射获取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   Source File: ActivityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取 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   Source File: Visual.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
@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
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   Source File: LocaleUtils.java    License: Apache License 2.0 6 votes vote down vote up
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   Source File: NucleusLayout.java    License: MIT License 5 votes vote down vote up
/**
 * 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   Source File: Application.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
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   Source File: SharedPreferencesMyUtil.java    License: Apache License 2.0 5 votes vote down vote up
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   Source File: PluginInjector.java    License: MIT License 5 votes vote down vote up
static void replaceReceiverContext(Context baseContext, Context newBase) {

		if (HackContextImpl.instanceOf(baseContext)) {
			ContextWrapper receiverRestrictedContext = new HackContextImpl(baseContext).getReceiverRestrictedContext();
			new HackContextWrapper(receiverRestrictedContext).setBase(newBase);
		}
	}
 
Example 23
@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
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   Source File: SharedPreferencesMyUtil.java    License: Apache License 2.0 5 votes vote down vote up
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   Source File: SharedPreferencesMyUtil.java    License: Apache License 2.0 5 votes vote down vote up
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   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
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   Source File: SceneNavigator.java    License: Apache License 2.0 5 votes vote down vote up
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
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   Source File: ContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
static ContextImpl getImpl(Context context) {
    Context nextContext;
    while ((context instanceof ContextWrapper) &&
            (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
        context = nextContext;
    }
    return (ContextImpl)context;
}