类android.content.ContextWrapper源码实例Demo

下面列出了怎么用android.content.ContextWrapper的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: ans-android-sdk   文件: AllegroUtils.java
/**
 * 通过上下问获取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();
}
 
源代码2 项目: ThemeDemo   文件: LayoutInflaterFactory2.java
/**
 * 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();
}
 
源代码3 项目: OpenMapKitAndroid   文件: OfflineMapDownloader.java
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;
}
 
源代码4 项目: react-native-GPay   文件: ContextUtils.java
/**
 * 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;
}
 
源代码5 项目: container   文件: NotificationCompatCompatV14.java
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;
		}
	};
}
 
源代码6 项目: test-butler   文件: GsmDataDisabler.java
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;
}
 
源代码7 项目: MiPushFramework   文件: CondomKitTest.java
@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());
}
 
源代码8 项目: kcanotify   文件: KcaUtils.java
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;
        }
    }
 
源代码9 项目: kcanotify_h5-master   文件: KcaUtils.java
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;
}
 
源代码10 项目: Carbon   文件: Toolbar.java
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();
        }
    });
}
 
源代码11 项目: Neptune   文件: PluginLoadedApk.java
/**
 * 反射获取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");
    }
}
 
源代码12 项目: DevUtils   文件: ActivityUtils.java
/**
 * 获取 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;
}
 
源代码13 项目: ssj   文件: Visual.java
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;
}
 
@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);
    }
  };
}
 
源代码15 项目: MTweaks-KernelAdiutorMOD   文件: BaseActivity.java
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);
    }
 
源代码16 项目: prayer-times-android   文件: LocaleUtils.java
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);
}
 
源代码17 项目: nucleus   文件: NucleusLayout.java
/**
 * 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;
}
 
源代码18 项目: Augendiagnose   文件: Application.java
/**
 * 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);
}
 
源代码19 项目: revolution-irc   文件: LiveThemeComponent.java
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;
}
 
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();
}
 
源代码21 项目: Android-Plugin-Framework   文件: PluginInjector.java
static void replaceReceiverContext(Context baseContext, Context newBase) {

		if (HackContextImpl.instanceOf(baseContext)) {
			ContextWrapper receiverRestrictedContext = new HackContextImpl(baseContext).getReceiverRestrictedContext();
			new HackContextWrapper(receiverRestrictedContext).setBase(newBase);
		}
	}
 
@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);
}
 
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;
}
 
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();
}
 
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;
}
 
源代码26 项目: AndroidSlideBack   文件: Utils.java
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;
}
 
源代码27 项目: scene   文件: SceneNavigator.java
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;
}
 
源代码28 项目: Applozic-Android-SDK   文件: ApplozicComponents.java
public Activity getActivity() {
    Context context = getContext();
    while (context instanceof ContextWrapper) {
        if (context instanceof Activity) {
            return (Activity) context;
        }
        context = ((ContextWrapper) context).getBaseContext();
    }
    return null;
}
 
源代码29 项目: AndroidComponentPlugin   文件: ContextImpl.java
static ContextImpl getImpl(Context context) {
    Context nextContext;
    while ((context instanceof ContextWrapper) &&
            (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
        context = nextContext;
    }
    return (ContextImpl)context;
}
 
源代码30 项目: Orin   文件: MusicPlayerRemote.java
public static void unbindFromService(@Nullable 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()) {
        musicService = null;
    }
}
 
 类所在包
 同包方法