2011-12-02 29 views
0

第一關 - 我寧願在Java的新手,所以如果這個問題沒有意義不要讓我知道。的Java(Android版):從調用上下文的功能,而不投

基本上我做Android應用程序與我的web服務進行通信,所以我做了一個單獨的類來處理通信,其中還包括的AsyncTask(我在這裏去掉了很多代碼只是預覽):

public class api { 

private String caller = null; 
Context that = null; 

api(Context that) { 

    this.that = that; 
    this.caller = that.getClass().getSimpleName(); 

} 

void call(String action) { 

    /* .... */ 

    } 

    new back().execute(param1, param2); 

} 

void callback(String action, String result){ 

    that.callback(action, result); 

} 



public class back extends AsyncTask<String, Void, String> { 

    public String response = null; 

    protected String doInBackground(String... params) { 

     response = connection.executeRequest(params[1]); 
     return response; 

    } 

    protected void onPostExecute(String result) { 

     callback("a", "b");     

    } 

}  


} 

當我使用類從應用程序的某些部分(比方說SomeClass.class),我做的:

api WS = new api(this); 
WS.call("...."); 

而且它應該執行功能「回調'在SomeClass中。 但這裏的關鍵問題是這一行:

that.callback(action, result); 

的Eclipse讓我在劇組添加了「來電顯示」類的名稱:

(SomeClass) that.callback(action, result); 

但是,這並不爲我工作,因爲我使用來自許多不同類的'api'類,所以理想情況下我需要在演員表中放置一個變量。我得到這裏的「來電顯示」類的名稱:

this.caller = that.getClass().getSimpleName(); 
//obviously this won't work: 
(this.caller) that.callback(action, result); 

反正有做到這一點,還是我做一些根本性的錯誤?

謝謝。

回答

1

目前您的API類接受它的默認構造上下文對象。使用包含回調方法的新類來擴展Context是更有意義的,然後您可以在SomeClass等子類中重寫這些回調方法,否則無需在您的api類中投射。例如:

public class APIContext extends Context 
{ 
    public void callback(String action, String result) 
    { 
     /* ... */ 
    } 
} 

public class SomeClass extends APIContext 
{ 
    @Override 
    public void callback(String action, String result) 
    { 
     /* ... */ 
    } 
} 

public class api 
{ 
    private APIContext callerContext = null; 

    public api(APIContext context) 
    { 
     this.callerContext = context; 
    } 

    public void callback(String action, String result) 
    { 
     callerContext.callback(action, result); 
    } 
} 
+0

我說'公共類SomeClass擴展APIContext'不行,因爲現在它擴展了Activity嗎? – void0

+0

您可以擁有一個具有相同方法簽名的類APIActivity,然後讓SomeClass實現該方法。然後將一個APIActivity對象作爲構造函數參數傳遞給api實例。爲什麼要傳遞一個Context實例有什麼特別的理由?活動(和APIActivity,如果你寫它)擴展上下文,所以你不會失去任何功能,如果你通過它而不是。 – wrren

+0

上下文我正在傳遞,以便在完成AsyncTask之後可以訪問調用者的callback()函數 - 在沒有使函數靜態的情況下沒有找到任何其他適當的方法。 **根據您的示例,擴展活動**效果非常好,非常感謝! – void0

相關問題