文件目录:
android-1.6_r2\frameworks\base\core\java\android\content\pm\PackageParser.java
# PackageParser.java
1. 解析 APK 包名
public static String parsePackageName(String packageFilePath, int flags) { XmlResourceParser parser = null; AssetManager assmgr = null; try { assmgr = new AssetManager(); // 创建 AssetManager 对象 int cookie = assmgr.addAssetPath(packageFilePath); // 插入 安装包文件 路径 parser = assmgr.openXmlResourceParser(cookie, "AndroidManifest.xml"); // 解析 Androidmanifest.xml 文件 } catch (Exception e) { if (assmgr != null) assmgr.close(); Log.w(TAG, "Unable to read AndroidManifest.xml of " + packageFilePath, e); return null; } AttributeSet attrs = parser; String errors[] = new String[1]; String packageName = null; try { packageName = parsePackageName(parser, attrs, flags, errors); } catch (IOException e) { Log.w(TAG, packageFilePath, e); } catch (XmlPullParserException e) { Log.w(TAG, packageFilePath, e); } finally { if (parser != null) parser.close(); if (assmgr != null) assmgr.close(); } if (packageName == null) { Log.e(TAG, "parsePackageName error: " + errors[0]); return null; } return packageName; }
private static String parsePackageName(XmlPullParser parser, AttributeSet attrs, int flags, String[] outError) throws IOException, XmlPullParserException { int type; while ((type=parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { ; } if (type != parser.START_TAG) { outError[0] = "No start tag found"; return null; } if ((flags&PARSE_CHATTY) != 0 && Config.LOGV) Log.v( TAG, "Root element name: '" + parser.getName() + "'"); if (!parser.getName().equals("manifest")) { outError[0] = "No <manifest> tag"; return null; } String pkgName = attrs.getAttributeValue(null, "package"); // 解析 package tag if (pkgName == null || pkgName.length() == 0) { outError[0] = "<manifest> does not specify package"; return null; } String nameError = validateName(pkgName, true); // 校验包名 if (nameError != null && !"android".equals(pkgName)) { // 过滤 "android" 包名 outError[0] = "<manifest> specifies bad package name \"" + pkgName + "\": " + nameError; return null; } return pkgName.intern(); }
private static String validateName(String name, boolean requiresSeparator) { final int N = name.length(); boolean hasSep = false; boolean front = true; for (int i=0; i<N; i++) { final char c = name.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { front = false; continue; } if (!front) { if ((c >= '0' && c <= '9') || c == '_') { continue; } } if (c == '.') { hasSep = true; front = true; continue; } return "bad character '" + c + "'"; } return hasSep || !requiresSeparator ? null : "must have at least one '.' separator"; }