Use try-with-resources to avoid accidentaly leaking unclosed objects.

Try-with-resources guarantees that objects will be closed even if an
exception happens after their creation. It also handles nulls and avoids
throwing NPE.

Test: built and launched Cuttlefish.
Change-Id: I80e767d1fbbca25a724bfe94e1752f88891a6bb0
This commit is contained in:
Mateus Azis
2023-04-18 17:07:00 -07:00
parent a1355bc271
commit 75eb42b914

View File

@@ -96,31 +96,30 @@ public final class WallpaperInfo implements Parcelable {
throws XmlPullParserException, IOException {
mService = service;
ServiceInfo si = service.serviceInfo;
final PackageManager pm = context.getPackageManager();
XmlResourceParser parser = null;
try {
parser = si.loadXmlMetaData(pm, WallpaperService.SERVICE_META_DATA);
try (XmlResourceParser parser = si.loadXmlMetaData(pm,
WallpaperService.SERVICE_META_DATA)) {
if (parser == null) {
throw new XmlPullParserException("No "
+ WallpaperService.SERVICE_META_DATA + " meta-data");
}
Resources res = pm.getResourcesForApplication(si.applicationInfo);
AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& type != XmlPullParser.START_TAG) {
}
String nodeName = parser.getName();
if (!"wallpaper".equals(nodeName)) {
throw new XmlPullParserException(
"Meta-data does not start with wallpaper tag");
}
TypedArray sa = res.obtainAttributes(attrs,
com.android.internal.R.styleable.Wallpaper);
mSettingsActivityName = sa.getString(
@@ -159,8 +158,6 @@ public final class WallpaperInfo implements Parcelable {
} catch (NameNotFoundException e) {
throw new XmlPullParserException(
"Unable to create context for: " + si.packageName);
} finally {
if (parser != null) parser.close();
}
}