下面列出了android.content.res.XmlResourceParser#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static int readScriptId(final Resources resources, final InputMethodSubtype subtype) {
final String layoutSetName = KEYBOARD_LAYOUT_SET_RESOURCE_PREFIX
+ SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype);
final int xmlId = getXmlId(resources, layoutSetName);
final XmlResourceParser parser = resources.getXml(xmlId);
try {
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
// Bovinate through the XML stupidly searching for TAG_FEATURE, and read
// the script Id from it.
parser.next();
final String tag = parser.getName();
if (TAG_FEATURE.equals(tag)) {
return readScriptIdFromTagFeature(resources, parser);
}
}
} catch (final IOException | XmlPullParserException e) {
throw new RuntimeException(e.getMessage() + " in " + layoutSetName, e);
} finally {
parser.close();
}
// If the tag is not found, then the default script is Latin.
return ScriptUtils.SCRIPT_LATIN;
}
static int readScriptId(final Resources resources, final InputMethodSubtype subtype) {
final String layoutSetName = KEYBOARD_LAYOUT_SET_RESOURCE_PREFIX
+ SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype);
final int xmlId = getXmlId(resources, layoutSetName);
final XmlResourceParser parser = resources.getXml(xmlId);
try {
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
// Bovinate through the XML stupidly searching for TAG_FEATURE, and read
// the script Id from it.
parser.next();
final String tag = parser.getName();
if (TAG_FEATURE.equals(tag)) {
return readScriptIdFromTagFeature(resources, parser);
}
}
} catch (final IOException | XmlPullParserException e) {
throw new RuntimeException(e.getMessage() + " in " + layoutSetName, e);
} finally {
parser.close();
}
// If the tag is not found, then the default script is Latin.
return ScriptUtils.SCRIPT_LATIN;
}
private void parseKeyboardLayoutSet(final Resources res, final int resId)
throws XmlPullParserException, IOException {
final XmlResourceParser parser = res.getXml(resId);
try {
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
final int event = parser.next();
if (event == XmlPullParser.START_TAG) {
final String tag = parser.getName();
if (TAG_KEYBOARD_SET.equals(tag)) {
parseKeyboardLayoutSetContent(parser);
} else {
throw new XmlParseUtils.IllegalStartTag(parser, tag, TAG_KEYBOARD_SET);
}
}
}
} finally {
parser.close();
}
}
static int readScriptId(final Resources resources, final InputMethodSubtype subtype) {
final String layoutSetName = KEYBOARD_LAYOUT_SET_RESOURCE_PREFIX
+ SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype);
final int xmlId = getXmlId(resources, layoutSetName);
final XmlResourceParser parser = resources.getXml(xmlId);
try {
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
// Bovinate through the XML stupidly searching for TAG_FEATURE, and read
// the script Id from it.
parser.next();
final String tag = parser.getName();
if (TAG_FEATURE.equals(tag)) {
return readScriptIdFromTagFeature(resources, parser);
}
}
} catch (final IOException | XmlPullParserException e) {
throw new RuntimeException(e.getMessage() + " in " + layoutSetName, e);
} finally {
parser.close();
}
// If the tag is not found, then the default script is Latin.
return ScriptUtils.SCRIPT_LATIN;
}
private Drawable getRoundIcon(Context context,String packageName, int iconDpi) {
mPackageManager = context.getPackageManager();
try {
Resources resourcesForApplication = mPackageManager.getResourcesForApplication(packageName);
AssetManager assets = resourcesForApplication.getAssets();
XmlResourceParser parseXml = assets.openXmlResourceParser("AndroidManifest.xml");
int eventType;
while ((eventType = parseXml.nextToken()) != XmlPullParser.END_DOCUMENT)
if (eventType == XmlPullParser.START_TAG && parseXml.getName().equals("application"))
for (int i = 0; i < parseXml.getAttributeCount(); i++)
if (parseXml.getAttributeName(i).equals("roundIcon"))
return resourcesForApplication.getDrawableForDensity(Integer.parseInt(parseXml.getAttributeValue(i).substring(1)), iconDpi, context.getTheme());
parseXml.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private void parseKeyboardLayoutSet(final Resources res, final int resId)
throws XmlPullParserException, IOException {
final XmlResourceParser parser = res.getXml(resId);
try {
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
final int event = parser.next();
if (event == XmlPullParser.START_TAG) {
final String tag = parser.getName();
if (TAG_KEYBOARD_SET.equals(tag)) {
parseKeyboardLayoutSetContent(parser);
} else {
throw new XmlParseUtils.IllegalStartTag(parser, tag, TAG_KEYBOARD_SET);
}
}
}
} finally {
parser.close();
}
}
public static String getSettingsActivity(Context context, ServiceInfo si)
throws XmlPullParserException, IOException {
PackageManager pm = context.getPackageManager();
XmlResourceParser parser = null;
try {
parser = si.loadXmlMetaData(pm, RecognitionService.SERVICE_META_DATA);
if (parser == null) {
throw new XmlPullParserException("No " + RecognitionService.SERVICE_META_DATA + " meta-data");
}
int type;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& type != XmlPullParser.START_TAG) {
}
String nodeName = parser.getName();
if (!"recognition-service".equals(nodeName)) {
throw new XmlPullParserException(
"Meta-data does not start with recognition-service tag");
}
return parser.getAttributeValue("http://schemas.android.com/apk/res/android",
"settingsActivity");
} finally {
if (parser != null) parser.close();
}
}
/**
* Gets search information for the given activity.
*
* @param context Context to use for reading activity resources.
* @param activityInfo Activity to get search information from.
* @return Search information about the given activity, or {@code null} if
* the activity has no or invalid searchability meta-data.
*
* @hide For use by SearchManagerService.
*/
public static SearchableInfo getActivityMetaData(Context context, ActivityInfo activityInfo,
int userId) {
Context userContext = null;
try {
userContext = context.createPackageContextAsUser("system", 0,
new UserHandle(userId));
} catch (NameNotFoundException nnfe) {
Log.e(LOG_TAG, "Couldn't create package context for user " + userId);
return null;
}
// for each component, try to find metadata
XmlResourceParser xml =
activityInfo.loadXmlMetaData(userContext.getPackageManager(), MD_LABEL_SEARCHABLE);
if (xml == null) {
return null;
}
ComponentName cName = new ComponentName(activityInfo.packageName, activityInfo.name);
SearchableInfo searchable = getActivityMetaData(userContext, xml, cName);
xml.close();
if (DBG) {
if (searchable != null) {
Log.d(LOG_TAG, "Checked " + activityInfo.name
+ ",label=" + searchable.getLabelId()
+ ",icon=" + searchable.getIconId()
+ ",suggestAuthority=" + searchable.getSuggestAuthority()
+ ",target=" + searchable.getSearchActivity().getClassName()
+ ",global=" + searchable.shouldIncludeInGlobalSearch()
+ ",settingsDescription=" + searchable.getSettingsDescriptionId()
+ ",threshold=" + searchable.getSuggestThreshold());
} else {
Log.d(LOG_TAG, "Checked " + activityInfo.name + ", no searchable meta-data");
}
}
return searchable;
}
private ColorStateList loadColorStateList(TypedValue value, int id) throws NotFoundException {
final long key = (((long) value.assetCookie) << 32) | value.data;
ColorStateList csl;
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
csl = ColorStateList.valueOf(value.data);
return csl;
}
csl = getCachedColorStateList(key);
if (csl != null) {
return csl;
}
if (value.string == null) {
throw new NotFoundException("Resource is not a ColorStateList (color or path): " + value);
}
String file = value.string.toString();
if (file.endsWith(".xml")) {
try {
XmlResourceParser rp = loadXmlResourceParserReflect(file, id, value.assetCookie, "colorstatelist");
if (rp == null) {
rp = loadXmlResourceParserEqual(file, id, value.assetCookie, "colorstatelist");
}
csl = ColorStateList.createFromXml(this, rp);
rp.close();
} catch (Exception e) {
NotFoundException rnf = new NotFoundException("File " + file + " from color state list resource ID #0x" + Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
} else {
throw new NotFoundException("File " + file + " from drawable resource ID #0x" + Integer.toHexString(id) + ": .xml extension required");
}
if (csl != null) {
synchronized (mAccessLock) {
mColorStateListCache.put(key, new WeakReference<ColorStateList>(csl));
}
}
return csl;
}
protected static PackageLite parse(XmlResourceParser xmlResourceParser) throws Exception {
int currentTag = xmlResourceParser.next();
PackageLite mPackageLite = new PackageLite();
while (currentTag != XmlPullParser.END_DOCUMENT) {
switch (currentTag) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if (xmlResourceParser.getName().equals("manifest")) {
parserManifestAttribute(xmlResourceParser, mPackageLite);
}
if (xmlResourceParser.getName().equals("application")) {
if (!parseApplication(mPackageLite, (xmlResourceParser),
(xmlResourceParser))) {
return null;
}
return mPackageLite;
}
break;
case XmlPullParser.END_DOCUMENT:
xmlResourceParser.close();
break;
case XmlPullParser.END_TAG:
break;
default:
break;
}
currentTag = xmlResourceParser.next();
}
return mPackageLite;
}
private void loadResource(Context context, Resources resources, @XmlRes int resourceId) {
final XmlResourceParser parser = resources.getXml(resourceId);
final int bitmapRes;
final float hotSpotX;
final float hotSpotY;
try {
XmlUtils.beginDocument(parser, "pointer-icon");
final TypedArray a = resources.obtainAttributes(
parser, com.android.internal.R.styleable.PointerIcon);
bitmapRes = a.getResourceId(com.android.internal.R.styleable.PointerIcon_bitmap, 0);
hotSpotX = a.getDimension(com.android.internal.R.styleable.PointerIcon_hotSpotX, 0);
hotSpotY = a.getDimension(com.android.internal.R.styleable.PointerIcon_hotSpotY, 0);
a.recycle();
} catch (Exception ex) {
throw new IllegalArgumentException("Exception parsing pointer icon resource.", ex);
} finally {
parser.close();
}
if (bitmapRes == 0) {
throw new IllegalArgumentException("<pointer-icon> is missing bitmap attribute.");
}
Drawable drawable;
if (context == null) {
drawable = resources.getDrawable(bitmapRes);
} else {
drawable = context.getDrawable(bitmapRes);
}
if (drawable instanceof AnimationDrawable) {
// Extract animation frame bitmaps.
final AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
final int frames = animationDrawable.getNumberOfFrames();
drawable = animationDrawable.getFrame(0);
if (frames == 1) {
Log.w(TAG, "Animation icon with single frame -- simply treating the first "
+ "frame as a normal bitmap icon.");
} else {
// Assumes they have the exact duration.
mDurationPerFrame = animationDrawable.getDuration(0);
mBitmapFrames = new Bitmap[frames - 1];
final int width = drawable.getIntrinsicWidth();
final int height = drawable.getIntrinsicHeight();
for (int i = 1; i < frames; ++i) {
Drawable drawableFrame = animationDrawable.getFrame(i);
if (!(drawableFrame instanceof BitmapDrawable)) {
throw new IllegalArgumentException("Frame of an animated pointer icon "
+ "must refer to a bitmap drawable.");
}
if (drawableFrame.getIntrinsicWidth() != width ||
drawableFrame.getIntrinsicHeight() != height) {
throw new IllegalArgumentException("The bitmap size of " + i + "-th frame "
+ "is different. All frames should have the exact same size and "
+ "share the same hotspot.");
}
BitmapDrawable bitmapDrawableFrame = (BitmapDrawable) drawableFrame;
mBitmapFrames[i - 1] = getBitmapFromDrawable(bitmapDrawableFrame);
}
}
}
if (!(drawable instanceof BitmapDrawable)) {
throw new IllegalArgumentException("<pointer-icon> bitmap attribute must "
+ "refer to a bitmap drawable.");
}
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
final Bitmap bitmap = getBitmapFromDrawable(bitmapDrawable);
validateHotSpot(bitmap, hotSpotX, hotSpotY);
// Set the properties now that we have successfully loaded the icon.
mBitmap = bitmap;
mHotSpotX = hotSpotX;
mHotSpotY = hotSpotY;
}
public static Map<String,String> getHashMapResource(Context c, int hashMapResId) {
Map<String,String> map = null;
XmlResourceParser parser = c.getResources().getXml(hashMapResId);
String key = null, value = null;
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
Log.d("utils","Start document");
} else if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("map")) {
boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);
map = isLinked ? new LinkedHashMap<String, String>() : new HashMap<String, String>();
} else if (parser.getName().equals("entry")) {
key = parser.getAttributeValue(null, "key");
if (null == key) {
parser.close();
return null;
}
}
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("entry")) {
map.put(key, value);
key = null;
value = null;
}
} else if (eventType == XmlPullParser.TEXT) {
if (null != key) {
value = parser.getText();
}
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return map;
}
static void init() {
if (CMDS != null && SWS != null)
return;
final XmlResourceParser xml = ThisApplication
.getXmlResource(R.xml.apdu7816);
try {
// START__DOCUMENT
xml.next();
if (xml.next() == START_TAG
&& "apdu".equalsIgnoreCase(xml.getName())) {
while (xml.next() != END_DOCUMENT) {
Apdu7816 cmds = readTag(Apdu7816.CMDS.class, xml);
if (cmds != null) {
CMDS = cmds;
continue;
}
Apdu7816 sws = readTag(Apdu7816.SWS.class, xml);
if (sws != null) {
SWS = sws;
continue;
}
break;
}
}
} catch (Exception e) {
} finally {
if (xml != null)
xml.close();
}
if (CMDS == null)
CMDS = new Apdu7816.CMDS();
if (SWS == null)
SWS = new Apdu7816.SWS();
}
@SuppressWarnings("UseSpecificCatch")
private static Map<String, Map<String, FontInfo>> fonts() {
if (font_map != null)
return font_map;
font_map = new LinkedHashMap<>();
Map<String, FontInfo> family = new LinkedHashMap<>();
family.put("Sans Serif Regular", new FontInfo(false, false, Typeface.SANS_SERIF));
family.put("Sans Serif Italic", new FontInfo(false, true, Typeface.SANS_SERIF));
family.put("Sans Serif Bold", new FontInfo(true, false, Typeface.SANS_SERIF));
family.put("Sans Serif Bold Italic", new FontInfo(true, true, Typeface.SANS_SERIF));
font_map.put("Sans Serif", family);
family = new LinkedHashMap<>();
family.put("Serif", new FontInfo(false, false, Typeface.SERIF));
font_map.put("Serif", family);
family = new LinkedHashMap<>();
family.put("Monospace", new FontInfo(false, false, Typeface.MONOSPACE));
font_map.put("Monospace", family);
XmlResourceParser parser = MainActivity.current.getResources().getXml(AndroidFileBridge.getResourceID("xml", "fontlist"));
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (parser.getName().equals("font")) {
String file = parser.getAttributeValue(null, "file");
String familyname = parser.getAttributeValue(null, "family");
String name = parser.getAttributeValue(null, "name");
boolean bold = parser.getAttributeBooleanValue(null, "bold", false);
boolean italic = parser.getAttributeBooleanValue(null, "italic", false);
family = font_map.get(familyname);
if (family == null) {
family = new LinkedHashMap<>();
font_map.put(familyname, family);
}
family.put(name, new FontInfo(bold, italic, file));
}
break;
default:
break;
}
eventType = parser.next();
}
parser.close();
} catch (Exception e) {
}
return font_map;
}
private void parseIncludeInternal(final XmlPullParser parser, final KeyboardRow row,
final boolean skip) throws XmlPullParserException, IOException {
if (skip) {
XmlParseUtils.checkEndTag(TAG_INCLUDE, parser);
if (DEBUG) startEndTag("</%s> skipped", TAG_INCLUDE);
return;
}
final AttributeSet attr = Xml.asAttributeSet(parser);
final TypedArray keyboardAttr = mResources.obtainAttributes(
attr, R.styleable.Keyboard_Include);
final TypedArray includeAttr = mResources.obtainAttributes(
attr, R.styleable.Keyboard);
mParams.mDefaultRowHeight = (int)ResourceUtils.getDimensionOrFraction(includeAttr,
R.styleable.Keyboard_rowHeight, mParams.mBaseHeight, mParams.mDefaultRowHeight);
final TypedArray keyAttr = mResources.obtainAttributes(attr, R.styleable.Keyboard_Key);
int keyboardLayout = 0;
try {
XmlParseUtils.checkAttributeExists(
keyboardAttr, R.styleable.Keyboard_Include_keyboardLayout, "keyboardLayout",
TAG_INCLUDE, parser);
keyboardLayout = keyboardAttr.getResourceId(
R.styleable.Keyboard_Include_keyboardLayout, 0);
if (row != null) {
// Override current x coordinate.
row.setXPos(row.getKeyX(keyAttr));
// Push current Row attributes and update with new attributes.
row.pushRowAttributes(keyAttr);
}
} finally {
keyboardAttr.recycle();
keyAttr.recycle();
includeAttr.recycle();
}
XmlParseUtils.checkEndTag(TAG_INCLUDE, parser);
if (DEBUG) {
startEndTag("<%s keyboardLayout=%s />",TAG_INCLUDE,
mResources.getResourceEntryName(keyboardLayout));
}
final XmlResourceParser parserForInclude = mResources.getXml(keyboardLayout);
try {
parseMerge(parserForInclude, row, skip);
} finally {
if (row != null) {
// Restore Row attributes.
row.popRowAttributes();
}
parserForInclude.close();
}
}
/**
* Inflate a new hierarchy from the specified xml resource. Throws
* InflaterException if there is an error.
*
* @param resource ID for an XML resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional root to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter?
* @return The root of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public T inflate(int resource, P root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getXml(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of LayoutParams values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter? If false, root is only used to create the
* correct subclass of LayoutParams for the root view in the XML.
* @return The root View of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new hierarchy from the specified xml resource. Throws
* InflaterException if there is an error.
*
* @param resource ID for an XML resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional root to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter?
* @return The root of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public T inflate(int resource, P root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getXml(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new hierarchy from the specified xml resource. Throws
* InflaterException if there is an error.
*
* @param resource ID for an XML resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional root to be the parent of the generated hierarchy (if
* <em>attachToRoot</em> is true), or else simply an object that
* provides a set of values for root of the returned
* hierarchy (if <em>attachToRoot</em> is false.)
* @param attachToRoot Whether the inflated hierarchy should be attached to
* the root parameter?
* @return The root of the inflated hierarchy. If root was supplied and
* attachToRoot is true, this is root; otherwise it is the root of
* the inflated XML file.
*/
public T inflate(@XmlRes int resource, P root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getXml(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
* Inflate a new item hierarchy from the specified xml resource. Throws
* InflaterException if there is an error.
*
* @param resource ID for an XML resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional parent of the generated hierarchy.
* @return The root of the inflated hierarchy. If root was supplied,
* this is the root item; otherwise it is the root of the inflated
* XML file.
*/
public Preference inflate(int resource, @Nullable PreferenceGroup root) {
XmlResourceParser parser = getContext().getResources().getXml(resource);
try {
return inflate(parser, root);
} finally {
parser.close();
}
}