下面列出了android.content.Context#getApplicationInfo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* MUST be called on non-Main Thread
* @param names array of file names in 'assets' directory
*/
public static void copyJarsFromAssets(final Context cxt, final String[] names) {
if(debug) {
Log.d(TAG, "copyJarsFromAssets(" + Arrays.deepToString(names) + ")");
}
final File dexDir = cxt.getDir(DIR_SUBDEX, Context.MODE_PRIVATE); // this API creates the directory if not exist
File apkFile = new File(cxt.getApplicationInfo().sourceDir);
// should copy subdex JARs to dexDir?
final boolean shouldInit = shouldDexOpt(apkFile, dexDir, names);
if (shouldInit) {
try {
copyToInternal(cxt, dexDir, names);
appendOdexesToClassPath(cxt, dexDir, names);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} else {
if (!inAppended(names)) {
appendOdexesToClassPath(cxt, dexDir, names);
}
}
}
public static String getVersionName(Context context) {
if (!TextUtils.isEmpty(sAppVersion)) {
return sAppVersion;
} else {
String appVersion = "";
try {
String pkgName = context.getApplicationInfo().packageName;
appVersion = context.getPackageManager().getPackageInfo(pkgName, 0).versionName;
if (appVersion != null && appVersion.length() > 0) {
Matcher matcher = VERSION_NAME_PATTERN.matcher(appVersion);
if (matcher.matches()) {
appVersion = matcher.group(1);
sAppVersion = appVersion;
}
}
} catch (Throwable t) {
LogHelper.e(TAG, t.toString());
}
return appVersion;
}
}
public boolean validateSignature(Context context, String packageName) {
String brand = Build.BRAND;
int applicationFlags = context.getApplicationInfo().flags;
if (brand.startsWith("generic") && (applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// We are debugging on an emulator, don't validate package signature.
return true;
}
PackageInfo packageInfo = null;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
String hashedSignature = Utility.sha1hash(signature.toByteArray());
if (validAppSignatureHashes.contains(hashedSignature)) {
return true;
}
}
return false;
}
/**
* @return the path to native libraries.
*/
@SuppressWarnings("unused")
@CalledByNative
private static String getNativeLibraryDirectory(Context appContext) {
ApplicationInfo ai = appContext.getApplicationInfo();
if ((ai.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0 ||
(ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
return ai.nativeLibraryDir;
}
return "/system/lib/";
}
/**
* Gets the application name to display on the UI.
*/
final String getApplicationName() {
final Context context = getActivity();
final Resources res = getResources();
final int applicationLabelRes = context.getApplicationInfo().labelRes;
return res.getString(applicationLabelRes);
}
public static void toggleAppIcon(final Context context) {
final int appInfoFlags = context.getApplicationInfo().flags;
final boolean isSystemApp = (appInfoFlags & ApplicationInfo.FLAG_SYSTEM) > 0;
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "toggleAppIcon() : FLAG_SYSTEM = " + isSystemApp);
}
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
context.getPackageManager().setComponentEnabledSetting(
new ComponentName(context, SetupActivity.class),
Settings.readShowSetupWizardIcon(prefs, context)
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
/**
* 判断当前应用是否是debug状态
*/
public static boolean isApkInDebug(Context context) {
try {
ApplicationInfo info = context.getApplicationInfo();
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
return false;
}
}
public static boolean isDebug(Context c) {
try {
return (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception ignored) {
}
return false;
}
static int calculateMemoryCacheSize(Context context) {
ActivityManager am = ContextCompat.getSystemService(context, ActivityManager.class);
boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
int memoryClass = largeHeap ? am.getLargeMemoryClass() : am.getMemoryClass();
// Target ~15% of the available heap.
return (int) (1024L * 1024L * memoryClass / 7);
}
/**
* @hide
*/
public DownloadManager(Context context) {
mResolver = context.getContentResolver();
mPackageName = context.getPackageName();
// Callers can access filename columns when targeting old platform
// versions; otherwise we throw telling them it's deprecated.
mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
}
public static String getDataDir(Context ctx) {
ApplicationInfo ai = ctx.getApplicationInfo();
if (ai.dataDir != null)
return fixLastSlash(ai.dataDir);
else
return "/data/data/" + ai.packageName + "/";
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.M) {
mForegroundDelegate = new ForegroundDelegate(this);
mForegroundDelegate.init(context, attrs, defStyleAttr, defStyleRes);
}
}
public SpaceCalculateTask(Context context, StorageSettingsAdapter adapter) {
mServerManager = ServerConfigManager.getInstance(context);
mDataDir = new File(context.getApplicationInfo().dataDir);
mAdapter = new WeakReference<>(adapter);
}
public static String getApplicationName(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
int stringId = applicationInfo.labelRes;
return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
}
/**
* Creates a new ViewTreeObserver. This constructor should not be called
*/
ViewTreeObserver(Context context) {
sIllegalOnDrawModificationIsFatal =
context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O;
}
@Override
public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
try {
cl.loadClass(className);
Log.i(TAG, String.format("newActivity[%s]", className));
} catch (ClassNotFoundException e) {
ComponentName component = PluginUtil.getComponent(intent);
if (component == null) {
return newActivity(mBase.newActivity(cl, className, intent));
}
String targetClassName = component.getClassName();
Log.i(TAG, String.format("newActivity[%s : %s/%s]", className, component.getPackageName(), targetClassName));
LoadedPlugin plugin = this.mPluginManager.getLoadedPlugin(component);
if (plugin == null) {
// Not found then goto stub activity.
boolean debuggable = false;
try {
Context context = this.mPluginManager.getHostContext();
debuggable = (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Throwable ex) {
}
if (debuggable) {
throw new ActivityNotFoundException("error intent: " + intent.toURI());
}
Log.i(TAG, "Not found. starting the stub activity: " + StubActivity.class);
return newActivity(mBase.newActivity(cl, StubActivity.class.getName(), intent));
}
Activity activity = mBase.newActivity(plugin.getClassLoader(), targetClassName, intent);
activity.setIntent(intent);
// for 4.1+
Reflector.QuietReflector.with(activity).field("mResources").set(plugin.getResources());
return newActivity(activity);
}
return newActivity(mBase.newActivity(cl, className, intent));
}
/**
* Construct a new Switch with a default style determined by the given theme
* attribute or style resource, overriding specific style attributes as
* requested.
*
* @param context The Context that will determine this widget's theming.
* @param attrs Specification of attributes that should deviate from the
* default styling.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme. Can be 0
* to not look for defaults.
*/
public Switch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
final Resources res = getResources();
mTextPaint.density = res.getDisplayMetrics().density;
mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.Switch, defStyleAttr, defStyleRes);
mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
if (mThumbDrawable != null) {
mThumbDrawable.setCallback(this);
}
mTrackDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_track);
if (mTrackDrawable != null) {
mTrackDrawable.setCallback(this);
}
mTextOn = a.getText(com.android.internal.R.styleable.Switch_textOn);
mTextOff = a.getText(com.android.internal.R.styleable.Switch_textOff);
mShowText = a.getBoolean(com.android.internal.R.styleable.Switch_showText, true);
mThumbTextPadding = a.getDimensionPixelSize(
com.android.internal.R.styleable.Switch_thumbTextPadding, 0);
mSwitchMinWidth = a.getDimensionPixelSize(
com.android.internal.R.styleable.Switch_switchMinWidth, 0);
mSwitchPadding = a.getDimensionPixelSize(
com.android.internal.R.styleable.Switch_switchPadding, 0);
mSplitTrack = a.getBoolean(com.android.internal.R.styleable.Switch_splitTrack, false);
mUseFallbackLineSpacing = context.getApplicationInfo().targetSdkVersion >= VERSION_CODES.P;
ColorStateList thumbTintList = a.getColorStateList(
com.android.internal.R.styleable.Switch_thumbTint);
if (thumbTintList != null) {
mThumbTintList = thumbTintList;
mHasThumbTint = true;
}
PorterDuff.Mode thumbTintMode = Drawable.parseTintMode(
a.getInt(com.android.internal.R.styleable.Switch_thumbTintMode, -1), null);
if (mThumbTintMode != thumbTintMode) {
mThumbTintMode = thumbTintMode;
mHasThumbTintMode = true;
}
if (mHasThumbTint || mHasThumbTintMode) {
applyThumbTint();
}
ColorStateList trackTintList = a.getColorStateList(
com.android.internal.R.styleable.Switch_trackTint);
if (trackTintList != null) {
mTrackTintList = trackTintList;
mHasTrackTint = true;
}
PorterDuff.Mode trackTintMode = Drawable.parseTintMode(
a.getInt(com.android.internal.R.styleable.Switch_trackTintMode, -1), null);
if (mTrackTintMode != trackTintMode) {
mTrackTintMode = trackTintMode;
mHasTrackTintMode = true;
}
if (mHasTrackTint || mHasTrackTintMode) {
applyTrackTint();
}
final int appearance = a.getResourceId(
com.android.internal.R.styleable.Switch_switchTextAppearance, 0);
if (appearance != 0) {
setSwitchTextAppearance(context, appearance);
}
a.recycle();
final ViewConfiguration config = ViewConfiguration.get(context);
mTouchSlop = config.getScaledTouchSlop();
mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
// Refresh display with current params
refreshDrawableState();
setChecked(isChecked());
}
public static void toggleLogging(Context ctx) {
mLoggingEnabled = (0 != (ctx.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
}
/**
* Initialize the GcmHelper class. To be called from the application class onCreate or from the
* onCreate of the main activity
*
* @param context An instance of the Application Context
*/
public synchronized void init(@NonNull Context context) {
if(!isGooglePlayservicesAvailable(context)){
throw new IllegalArgumentException("Not using the recommended Play Services version");
}
//get the GCM sender id from strings.xml
if (TextUtils.isEmpty(senderID)) {
int id =
context.getResources().getIdentifier("gcm_authorized_entity", "string", context.getPackageName());
senderID = context.getResources().getString(id);
}
if(TextUtils.isEmpty(senderID)){
throw new IllegalArgumentException("No SenderId provided!! Cannot instantiate");
}
SharedPreferences localPref = getSharedPreference(context);
//get topics array
if (localPref.contains(PREF_KEY_SUBSCRIPTION)) {
String subscription = localPref.getString(PREF_KEY_SUBSCRIPTION, null);
if (!TextUtils.isEmpty(subscription)) {
try {
JSONArray array = new JSONArray(subscription);
int length = array.length();
topics = new ArrayList<>();
for (int i = 0; i < length; i++) {
topics.add(array.getString(i));
}
} catch (JSONException ignored) {
if (DEBUG_ENABLED) Log.e(TAG, "init: while processing subscription list", ignored);
}
}
}
boolean registrationReq = true;
if (localPref.contains(PREF_KEY_TOKEN)) {
pushToken = localPref.getString(PREF_KEY_TOKEN, null);
if(!TextUtils.isEmpty(pushToken)){
registrationReq = false;
//don't pass token if already present
}
}
if(registrationReq){
//register for push token
Intent registration = new Intent(context, RegistrationIntentService.class);
registration.setAction(RegistrationIntentService.ACTION_REGISTER);
context.startService(registration);
}
//check if debug build and enable DEBUG MODE
DEBUG_ENABLED = (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
initialized = true;
}
/**
* Returns the integer identifier for the default app icon.
*
* @param context The Android context
* @return The integer identifier for the image resource
*/
static int getAppIconAsIntId(final Context context) {
ApplicationInfo ai = context.getApplicationInfo();
return ai.icon;
}