下面列出了怎么用android.content.pm.ApplicationInfo的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
throws NameNotFoundException {
if (app.packageName.equals("system")) {
return mContext.mMainThread.getSystemUiContext().getResources();
}
final boolean sameUid = (app.uid == Process.myUid());
final Resources r = mContext.mMainThread.getTopLevelResources(
sameUid ? app.sourceDir : app.publicSourceDir,
sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
mContext.mPackageInfo);
if (r != null) {
return r;
}
throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
}
public static Drawable getApkIcon(Context context, String apkPath) {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(apkPath,
PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
appInfo.sourceDir = apkPath;
appInfo.publicSourceDir = apkPath;
try {
return appInfo.loadIcon(pm);
} catch (OutOfMemoryError e) {
// Log.e(LOG_TAG, e.toString());
}
}
return null;
}
static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
final Intent intent = new Intent(action);
for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
if (info.activityInfo != null &&
(info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
final String packageName = info.activityInfo.packageName;
try {
final Resources res = pm.getResourcesForApplication(packageName);
return Pair.create(packageName, res);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected Void doInBackground(Void... unused) {
if(pkgAppsList == null && appsList == null){
//something went really bad here
return null;
}
if(appsList == null){
appsList = new ArrayList<ApplicationInfo>();
for(PackageInfo pkg : pkgAppsList){
appsList.add(pkg.applicationInfo);
}
}
AppComparator comparer = new AppComparator(getContext());
Collections.sort(appsList, comparer);
appsList.add(0, null);
return null;
}
/**
* Register a handler in the package manager for a image capture intent
*/
private void registerMediaStoreIntentHandler()
{
// Add something that will 'handle' the media capture intent
RobolectricPackageManager packageManager = shadowOf(RuntimeEnvironment.application.getPackageManager());
ResolveInfo info = new ResolveInfo();
info.isDefault = true;
ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.packageName = "does.not.matter";
info.activityInfo = new ActivityInfo();
info.activityInfo.applicationInfo = applicationInfo;
info.activityInfo.name = "DoesNotMatter";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
packageManager.addResolveInfoForIntent(intent, info);
}
/**
* 读取微信的AppKey
* @param context context
* @return String
*/
public static String getWeixinKey(Context context) {
try {
ApplicationInfo appInfo = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
if(null != appInfo) {
Bundle bundle = appInfo.metaData;
String key = null;
if(null != bundle) {
key = String.valueOf(bundle.get(WEIXIN_KEY));
}
if(!TextUtils.isEmpty(key)) {
return key;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/** @hide */
@Override
public Resources getResourcesForApplicationAsUser(String appPackageName, int userId)
throws NameNotFoundException {
if (userId < 0) {
throw new IllegalArgumentException(
"Call does not support special user #" + userId);
}
if ("system".equals(appPackageName)) {
return mContext.mMainThread.getSystemContext().getResources();
}
try {
ApplicationInfo ai = mPM.getApplicationInfo(appPackageName, sDefaultFlags, userId);
if (ai != null) {
return getResourcesForApplication(ai);
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException("Package " + appPackageName + " doesn't exist");
}
/** @hide */
@Override
public Resources getResourcesForApplicationAsUser(String appPackageName, int userId)
throws NameNotFoundException {
if (userId < 0) {
throw new IllegalArgumentException(
"Call does not support special user #" + userId);
}
if ("system".equals(appPackageName)) {
return mContext.mMainThread.getSystemContext().getResources();
}
try {
ApplicationInfo ai = mPM.getApplicationInfo(appPackageName, sDefaultFlags, userId);
if (ai != null) {
return getResourcesForApplication(ai);
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException("Package " + appPackageName + " doesn't exist");
}
public boolean isUninstallable(Context context) {
if (this.isMediaInstalled(context)) {
return true;
} else if (this.isInstalled(context)) {
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(this.packageName,
PackageManager.GET_UNINSTALLED_PACKAGES);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
// System apps aren't uninstallable.
final boolean isSystem = (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return !isSystem && this.isInstalled(context);
} else {
return false;
}
}
/**
* Tests whether packageName exists in application list.
*
* @param packageName package name
* @return true if packageName exists, false otherwise
*/
private boolean existApplicationFromPackageName(final String packageName) {
if (packageName == null) {
return false;
}
final PackageManager pm = getActivity().getPackageManager();
final int flags = PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS;
final List<ApplicationInfo> installedAppList = pm.getInstalledApplications(flags);
for (ApplicationInfo app : installedAppList) {
if (app.packageName.equals(packageName)) {
return true;
}
}
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CustomViewHolder cvh;
if (convertView == null) {
cvh = new CustomViewHolder();
convertView = LayoutInflater.from(HeaderFooterActivity.this).inflate(R.layout.item_custom_2, null);
cvh.imgLogo = (ImageView) convertView.findViewById(R.id.img_item_edit);
cvh.txtName = (TextView) convertView.findViewById(R.id.txt_item_edit);
cvh.imgLogo2 = (ImageView) convertView.findViewById(R.id.img_item_edit2);
convertView.setTag(cvh);
} else {
cvh = (CustomViewHolder) convertView.getTag();
}
ApplicationInfo item = (ApplicationInfo) this.getItem(position);
cvh.txtName.setText(item.loadLabel(getPackageManager()));
cvh.imgLogo.setImageDrawable(item.loadIcon(getPackageManager()));
cvh.imgLogo2.setImageDrawable(item.loadIcon(getPackageManager()));
return convertView;
}
public static String getBuildDate(Context context)
{
if ( build != null )
return build;
try
{
ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
ZipFile file = new ZipFile(info.sourceDir);
ZipEntry entry = file.getEntry("classes.dex");
long time = entry.getTime();
build = SimpleDateFormat.getInstance().format(new java.util.Date(time));
}
catch (Exception e)
{ build = "Unknown"; }
if ( debug_build(context) )
build += " [debug]";
return build;
}
/**
* プラグインSDKのバージョンを取得します.
*
* @param info アプリケーション情報
* @return バージョン名
*/
private VersionName getPluginSDKVersion(final ApplicationInfo info) {
VersionName versionName = null;
if (info.metaData != null && info.metaData.get(PLUGIN_SDK_META_DATA) != null) {
PackageManager pkgMgr = mContext.getPackageManager();
XmlResourceParser xpp = info.loadXmlMetaData(pkgMgr, PLUGIN_SDK_META_DATA);
try {
String str = parsePluginSDKVersionName(xpp);
if (str != null) {
versionName = VersionName.parse(str);
}
} catch (Exception e) {
// NOP
}
}
if (versionName != null) {
return versionName;
} else {
return VersionName.parse("1.0.0");
}
}
private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,
final String packageName, ApplicationInfo appInfo) {
AppEntry appEntry = appEntries.get(packageName);
if (appEntry == null) {
if (appInfo == null) {
try {
appInfo = mPm.getApplicationInfo(packageName,
PackageManager.GET_DISABLED_COMPONENTS
| PackageManager.GET_UNINSTALLED_PACKAGES);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Unable to find info for package " + packageName);
return null;
}
}
appEntry = new AppEntry(this, appInfo);
appEntry.loadLabel(context);
appEntries.put(packageName, appEntry);
}
return appEntry;
}
ChronusResourceProvider(@NonNull Context c, @NonNull String pkgName,
@NonNull ResourceProvider defaultProvider) {
this.defaultProvider = defaultProvider;
try {
context = c.createPackageContext(
pkgName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
PackageManager manager = context.getPackageManager();
ApplicationInfo info = manager.getApplicationInfo(pkgName, PackageManager.GET_META_DATA);
providerName = manager.getApplicationLabel(info).toString();
iconDrawable = context.getApplicationInfo().loadIcon(context.getPackageManager());
} catch (Exception e) {
buildDefaultInstance(c);
}
}
/**
* Get whether given app is a debug app.
*
* @param pkgName the package name
* @return true if it is
*/
public static boolean isAppDebug(final String pkgName) {
if (StringUtils.isSpace(pkgName)) return false;
try {
PackageManager pm = UtilsApp.getApp().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(pkgName, 0);
return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
private Application changeTopApplication(String appClassName) {
//有值的话调用该Applicaiton
Object currentActivityThread = Reflect.invokeMethod("android.app.ActivityThread", null, "currentActivityThread", new Object[]{}, null);
Object mBoundApplication = Reflect.getFieldValue(
"android.app.ActivityThread", currentActivityThread,
"mBoundApplication");
Object loadedApkInfo = Reflect.getFieldValue(
"android.app.ActivityThread$AppBindData",
mBoundApplication, "info");
//把当前进程的mApplication 设置成了null
Reflect.setFieldValue("android.app.LoadedApk", loadedApkInfo, "mApplication", null);
Object oldApplication = Reflect.getFieldValue(
"android.app.ActivityThread", currentActivityThread,
"mInitialApplication");
//http://www.codeceo.com/article/android-context.html
ArrayList<Application> mAllApplications = (ArrayList<Application>) Reflect
.getFieldValue("android.app.ActivityThread",
currentActivityThread, "mAllApplications");
mAllApplications.remove(oldApplication);//删除oldApplication
ApplicationInfo loadedApk = (ApplicationInfo) Reflect
.getFieldValue("android.app.LoadedApk", loadedApkInfo,
"mApplicationInfo");
ApplicationInfo appBindData = (ApplicationInfo) Reflect
.getFieldValue("android.app.ActivityThread$AppBindData",
mBoundApplication, "appInfo");
loadedApk.className = appClassName;
appBindData.className = appClassName;
Application app = (Application) Reflect.invokeMethod(
"android.app.LoadedApk", loadedApkInfo, "makeApplication",
new Object[]{false, null},
boolean.class, Instrumentation.class);//执行 makeApplication(false,null)
Reflect.setFieldValue("android.app.ActivityThread", currentActivityThread, "mInitialApplication", app);
return app;
}
/**
* get all the dex path
*
* @param context the application context
* @return all the dex path
* @throws PackageManager.NameNotFoundException Exception
* @throws IOException Exception
*/
public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
File sourceApk = new File(applicationInfo.sourceDir);
List<String> sourcePaths = new ArrayList<>();
sourcePaths.add(applicationInfo.sourceDir); //add the default apk path
//the prefix of extracted file, ie: test.classes
String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
//如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了
//通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的
if (!isVMMultidexCapable()) {
//the total dex numbers
int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);
for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
//for each dex file, ie: test.classes2.zip, test.classes3.zip...
String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
File extractedFile = new File(dexDir, fileName);
if (extractedFile.isFile()) {
sourcePaths.add(extractedFile.getAbsolutePath());
//we ignore the verify zip part
} else {
throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");
}
}
}
if (Utils.isAppDebug()) {
// Search instant run support only debuggable
sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));
}
return sourcePaths;
}
private void setData() {
mAsyncTask = new AsyncTask<Void,Void,ArrayList<LedListItem>>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
@Override
protected ArrayList<LedListItem> doInBackground(Void... arg0) {
ArrayList<LedListItem> itemList = new ArrayList<LedListItem>();
PackageManager pm = LedControlActivity.this.getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
Collections.sort(packages, new ApplicationInfo.DisplayNameComparator(pm));
for(ApplicationInfo ai : packages) {
if (isCancelled()) break;
if (ai.packageName.equals(LedControlActivity.this.getPackageName())) continue;
LedListItem item = new LedListItem(LedControlActivity.this, ai);
if (mShowActiveOnly && !item.isEnabled()) continue;
itemList.add(item);
}
return itemList;
}
@Override
protected void onPostExecute(ArrayList<LedListItem> result) {
dismissProgressDialog();
mSearchEditText.setText("");
mList.setAdapter(new LedListAdapter(LedControlActivity.this, result,
LedControlActivity.this));
((LedListAdapter)mList.getAdapter()).notifyDataSetChanged();
mSearchEditText.setVisibility(mShowActiveOnly ? View.GONE : View.VISIBLE);
}
}.execute();
}
/**
* Get the main dex path and split dex paths
*/
static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
List<String> sourcePaths = new ArrayList<>();
sourcePaths.add(applicationInfo.sourceDir);
if (BcmInnerRouter.isDebuggable()) {
sourcePaths.addAll(tryLoadDexFile(applicationInfo));
}
return sourcePaths;
}
static boolean isPackageExists(Context context, String targetPackage) {
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if (packageInfo.packageName.equals(targetPackage)) return true;
}
return false;
}
@Override
public List<AppInfo> getAllAppInfoList() {
List<ApplicationInfo> applicationInfoList = queryCurrentInstalledApps();
List<AppInfo> appInfoList = new ArrayList<>(applicationInfoList.size());
for (ApplicationInfo applicationInfo : applicationInfoList) {
AppInfo appInfo = new AppInfo();
appInfo.setAppName(mPackageManager.getApplicationLabel(applicationInfo).toString());
appInfo.setPackageName(applicationInfo.packageName);
appInfo.setIcon(mPackageManager.getApplicationIcon(applicationInfo));
appInfoList.add(appInfo);
}
return appInfoList;
}
/**
* 判断App是否是系统应用
*
* @param packageName 包名
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isSystemApp(String packageName) {
if (isSpace(packageName)) return false;
try {
PackageManager pm = Utils.getContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
return ai != null && (ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
@Override
protected Void doInBackground(Void... params) {
String whitelisted = prefs.getString("whitelisted_apps", null);
ArrayList<String> packages = new ArrayList<String>();
whitelistedAppList = new ArrayList<ApplicationInfo>();
if (whitelisted != null){
packages = gson.fromJson(whitelisted, new TypeToken<ArrayList<String>>(){}.getType());
}
applist = checkForLaunchIntent(packageManager.getInstalledApplications(packageManager.GET_META_DATA));
for(ApplicationInfo info : applist){
if (packages.contains(info.packageName)){
whitelistedAppList.add(info);
; }
}
if (whitelistedAppList.size() == 0){
textVisible = true;
} else {
textVisible = false;
}
listAdapter=new AppAdapter(getActivity(),R.layout.listview_whitelist, whitelistedAppList);
return null;
}
@Override protected Long doInBackground(Void... params) {
long beforeMemory = 0;
long endMemory = 0;
ActivityManager.MemoryInfo memoryInfo
= new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
beforeMemory = memoryInfo.availMem;
List<ActivityManager.RunningAppProcessInfo> appProcessList
= AndroidProcesses.getRunningAppProcessInfo(mContext);
ApplicationInfo appInfo = null;
for (ActivityManager.RunningAppProcessInfo info : appProcessList) {
String packName = info.processName;
try {
packageManager.getApplicationInfo(info.processName, 0);
} catch (PackageManager.NameNotFoundException e) {
appInfo = getApplicationInfo(
info.processName.split(":")[0]);
if (appInfo != null) {
packName = info.processName.split(":")[0];
}
}
List<Ignore> ignores = mFinalDb.findAllByWhere(Ignore.class,
"packName='" + packName + "'");
if (ignores.size() == 0) {
L.e(info.processName);
killBackgroundProcesses(info.processName);
}
}
activityManager.getMemoryInfo(memoryInfo);
endMemory = memoryInfo.availMem;
return endMemory - beforeMemory;
}
@Override
protected List<AppModel> loadData(ProgressCallback callback) {
List<AppModel> list = new ArrayList<AppModel>();
final PackageManager pm = getActivity().getPackageManager();
List<ApplicationInfo> la = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (final ApplicationInfo info : la) {
final AppModel app = new AppModel();
app.packageName = info.packageName;
app.title = pm.getApplicationLabel(info).toString();
app.iconRefreshRunnable = new Runnable() {
@Override
public void run() {
app.icon = new WeakReference<Drawable>(pm.getApplicationIcon(info));
}
};
list.add(app);
callback.updateProgress(list.size(), la.size());
}
Collections.sort(list, new Comparator<AppModel>() {
@Override
public int compare(AppModel p1, AppModel p2) {
return Collator.getInstance().compare(p1.title, p2.title);
}
});
// Add the Global config entry
AppModel global = new AppModel();
global.packageName = "global";
global.title = getString(R.string.global);
global.icon = null;
list.add(0, global);
return list;
}
public ApplicationInfo getApplicationInfo(int flags) throws Exception {
ApplicationInfo applicationInfo = mParser.generateApplicationInfo(flags);
fixApplicationInfo(applicationInfo);
if (TextUtils.isEmpty(applicationInfo.processName)) {
applicationInfo.processName = applicationInfo.packageName;
}
return applicationInfo;
}
/**
* 读取application 节点 meta-data 信息
*/
public static String buildChannel() {
try {
ApplicationInfo appInfo = mContext.getPackageManager()
.getApplicationInfo(mContext.getPackageName(),
PackageManager.GET_META_DATA);
String mTag = appInfo.metaData.getString("UMENG_CHANNEL");
return mTag;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
public boolean isEnabled(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
return Objects.requireNonNull(appOpsManager).checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
applicationInfo.uid, applicationInfo.packageName) == AppOpsManager.MODE_ALLOWED;
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return false;
}
private CharSequence getApplicationLabel(CharSequence packageName) {
PackageManager packageManager = service.getPackageManager();
if (packageManager == null) {
return null;
}
ApplicationInfo applicationInfo;
try {
applicationInfo = packageManager.getApplicationInfo(packageName.toString(), 0 /* no flag */);
} catch (PackageManager.NameNotFoundException exception) {
return null;
}
return packageManager.getApplicationLabel(applicationInfo);
}