下面列出了怎么用android.content.ContextWrapper的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 通过上下问获取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();
}
/**
* 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();
}
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;
}
/**
* 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;
}
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;
}
};
}
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;
}
@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());
}
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;
}
}
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;
}
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();
}
});
}
/**
* 反射获取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");
}
}
/**
* 获取 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;
}
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);
}
};
}
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);
}
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);
}
/**
* 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;
}
/**
* 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);
}
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();
}
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;
}
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;
}
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;
}
public Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
static ContextImpl getImpl(Context context) {
Context nextContext;
while ((context instanceof ContextWrapper) &&
(nextContext=((ContextWrapper)context).getBaseContext()) != null) {
context = nextContext;
}
return (ContextImpl)context;
}
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;
}
}