我有一个IP扫描例程来查找局域网上的Web服务器,然后根据此扫描的结果,我需要通过在onPostExecute中运行第二个异步任务来确定我要查找的IP地址。 IP扫描程序。
此阶段的IP是硬编码的,但我将使用数组来存储扫描结果,并在我使这个核心逻辑工作后立即使用数组按顺序尝试每个IP。
第一个异步任务完成如下:
@Override
protected void onPostExecute(String s) {
progressBarServerScan.setProgress(Integer.valueOf(100));
tvScanProgressText.setText("Server scan progress " + "100" + " %");
//must try home dir, I hope all will be "home"...else must manage different folders
// check for each system type
String serverCheck = "http://192.168.0.12/home";
new identifyServer().execute(serverCheck);
if (systemNameScan!="Unknown"){
Toast.makeText(getBaseContext(),"Found "+systemNameScan+" system at "+serverCheck,Toast.LENGTH_SHORT).show();
}
正如您所看到的,它启动了第二个asyncTask,它检查HTTP响应中的关键字,以便识别每个找到的IP地址是否是我要查找的IP地址。第二次异步结束如下:
@Override
protected void onPostExecute(String result) {
Pattern HPPattern = Pattern.compile("Visit\\sthe\\sHewlett\\sPackard\\swebsite.*");
Matcher mHP = HPPattern.matcher(result);
if (mHP.find()) {
systemNameScan = "Hewlett Packard";
Toast.makeText(getBaseContext(),"systemNameScan is: "+systemNameScan,Toast.LENGTH_LONG).show();
} else {
systemNameScan = "Unknown";
Toast.makeText(getBaseContext(),"systemNameScan is: "+systemNameScan,Toast.LENGTH_LONG).show();
//offer option to post the HTML page found to the developer
// for analysis
}
我面临的问题是调用例程的Toast msg在子例程中执行之前执行,而我在子例程中更新的变量在我测试其内容时显然尚未更新在if语句" if(systemNameScan!=" Unknown"){...等。 systemNameScan的值在该阶段为null,因此我的检查无效...
有人可以解释为什么调用例程在第二个异步任务onPostExecute完全完成之前正在进行吗?更重要的是,如何更好地构建此IP扫描任务以及网页的后续内容分析以避免此时间问题?
我尝试将检查例程移动到第二个异步任务,但后来我找不到使用传递给异步任务的IP地址的方法作为变量" serverCheck"第二个异步任务不知道...
答案 0 :(得分:0)
我看到两个问题:
1)有人可以解释为什么调用例程在第二个异步任务onPostExecute完全完成之前正在进行吗?
因为通话
new identifyServer().execute(serverCheck);
仅启动identifyServer任务。在单独的线程上启动任务后,此调用将返回。因此,在调用线程(即正在执行第一个任务的onPostExecute方法的线程)中,Toast的显示是下一个要执行的代码。正如您所观察到的那样,时间有时会在第二个任务完成之前显示。
2)如何更好地构建此IP扫描任务以及网页的后续内容分析以避免此时间问题?
将检查例程移动到第二个任务是有问题的,因为正如您所述:第二个异步任务不知道变量“serverCheck”。因此您可以通过将其保存为实例变量:
// Note I took the liberty of renaming this class to start with a
// capital letter. This is a Java convention.
class IdentifyServerTask extends AsyncTask<String, Integer, String> {
private String serverCheck;
public IdentifyServerTask(String IdentifyServerTask) {
this.serverCheck = serverCheck;
}
}
现在需要serverCheck值来创建任务实例:
IdentifyServerTask task2 = new IdentifyServerTask(serverCheck);
task.execute(serverCheck);