程序中有一個 AsyncTask 方法,當程序退出之前會被執行。它可以得到當前位置並解析 xml配置文件。當前位置被檢索了,但是解析操作未執行。
在 Main Activity 中調用 AsyncTask
public void quitApplication()
{
FinishProcess fProcess = new FinishProcess();
fProcess.execute(this);
}
AsyncTask:
public class FinishProcess extends AsyncTask<Main, Void, Void>
{
@Override
protected Void doInBackground(Main... params) {
LocationHandler lh = new LocationHandler();
try {
lh.getLocationSingle(null, params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}
parseXML(params[0]);
return null;
}
private void parseXML(Main params)
{
String ANDROID_ID = "android:id";
Resources resources = params.getResources();
try {
InputStream fXmlFile = resources.openRawResource(R.raw.pages);
//Reads xml file and gets the node types and attributes
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("*");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println(eElement.getNodeName());
}
}
}
catch (Exception e) {
System.out.println("Catch");
e.printStackTrace();
}
}
}
如果你的應用程序啟動完上面這段程序後就退出,那麼當主線程在 AsyncTask 運行時,主線程就可能死亡,從而就會孤立它。如果在退出時候需要這樣做,就在 Application.onTerminate 線程中運行,不要在 AsyncTask 線程中。