Android 解析Xml 的方式有多种,SAX、DOM、Pull 都可以实现,这里使用的是其中的一种.
下面的代码主要是在IntentService 里面解析一个xml 白名单的.主要是记录一下,时间长了容易忘记.
public class NameListServices extends IntentService {
private final static String TAG = "NameListServices";
private List<AppInfo> infos = new ArrayList<AppInfo>();
public NameListServices() {
super("NameListServices");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent");
if(intent != null) {
String uri = intent.getStringExtra("uri");
InputStream is = null;
if(uri != null) {
try {
is = getContentResolver().openInputStream(Uri.fromFile(new File(uri)));
readXml(is);
//updateInfoToDB();
} catch (FileNotFoundException e) {
e.printStackTrace();
if(is != null) {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
private void readXml(InputStream is) {
Log.i(TAG, "readXml");
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "UTF-8");
int eventType = parser.getEventType();
AppInfo appInfo ;
while(eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
String name = parser.getName();
if(name != null && name.trim().equals("AppInfo")) {
String pkg = parser.getAttributeValue(null,"pkg");
String type = parser.getAttributeValue(null,"type");
appInfo = new AppInfo(pkg, type);
Log.i(TAG, "appInfo:" + appInfo);
infos.add(appInfo);
}
break;
case XmlPullParser.END_TAG:
break;
default:
break;
}
eventType = parser.next();
}
}catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<AppInfo pkg = "com.android.settings" type="projection" />
<AppInfo pkg = "cn.nubia.gallery3d" type="projection" />
<AppInfo pkg = "cn.nubia.contacts" type="hook" />
<AppInfo pkg = "cn.nubia.browser" type="hook" />
<AppInfo pkg = "cn.nubia.neoshare" type="projection_hook" />
<AppInfo pkg = "cn.nubia.mms" type="projection_hook" />
</resources>