2015-06-16 34 views
0

我有一個IP掃描例程來查找局域網上的Web服務器,然後根據此掃描的結果,我需要通過運行第二個來確定哪個IP地址是我正在尋找的IP地址IP掃描例程的onPostExecute中的異步任務。使用嵌套的異步任務更新變量

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(); 
     } 

正如你所看到的,它會啓動該檢查HTTP響應關鍵詞來indentify如果每個發現的IP地址是一個第二的AsyncTask我在尋找。第二屆異步TAKS結束這樣的:

@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 
     } 

我現在面臨的問題是,一個在子程序和變量,我在子程序更新前調用程序執行的吐司味精當我測試if語句中的內容時,它顯然還沒有更新「if(systemNameScan!=」Unknown「){... etc。systemNameScan的值在該階段爲null,所以我的檢查不工作...

有人可以解釋爲什麼在第二個異步任務onPostExecute完全完成之前調用例程正在繼續嗎?更重要的是,如何更好地構造此IP掃描任務並對網頁進行後續內容分析以避免此問題克問題?

我試圖將檢查例程移動到第二個異步任務,但後來找不到使用傳遞給異步任務的IP地址的方法,因爲第二個Async不知道變量「serverCheck」任務...

回答

0

我看到2個問題:


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); 
+0

我調整了它,現在它的工作原理:String systemNameScan; private String currentIP; public IdentifyServerTask(String IdentifyServerTask){this.liveIP = serverCheck; } -----謝謝! – Gaetano

+0

我調整它如下,它的工作原理:String systemNameScan; private String currentIP; public IdentifyServerTask(String IdentifyServerTask){this.liveIP = serverCheck; – Gaetano