2012-09-26 52 views
0

我得到一個小問題:我需要在Android上使用cocos2d-x中的異步任務。cocos2d-x:線程

private void parseJSONJava() throws ClientProtocolException, IOException, JSONException 
{ 
    STAJSONParser jPars = new STAJSONParser(); 
    jPars.makeHttpRequest(String.format("%s/app/%s/json",STA_URL,STA_APP_UID)); 
} 

但此代碼崩潰的應用程序與錯誤Can't create handler inside thread that has not called Looper.prepare()。我解決這個問題,加入runOnUiThread

me.runOnUiThread(new Runnable(){ 
public void run(){ 
    STAJSONParser jPars = new STAJSONParser(); 
    jPars.makeHttpRequest(String.format("%s/app/%s/json",STA_URL,STA_APP_UID)); 
} 
}); 

當「我」是我的活動。 代碼從STAJSONParser

public JSONObject makeHttpRequest(String url) { 
AsyncGetJson Task= new AsyncGetJson(url); 
try { 
    return Task.execute().get(); 
} catch (InterruptedException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    return null; 
} catch (ExecutionException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    return null; 
} 

AsyncGetJson任務的一個簡單的AsyncTask,從服務器獲取JSON。 所以,我的問題是:這個解決方案是對/錯?或者你可以給我其他解決方案?

+0

是的,這是正確的(和我相信這是最簡單的方法。另一種方法是,在C++中使用libcurl) –

回答

0

我不明白爲什麼你不能這樣做。你也可以像使用m.ding一樣使用libcurl,以及pthread和json解析器。但問題是你需要自己管理pthreads。它比現在這樣做更「混亂」。然後,再次,使用JNI也不完全相當。這是一個巨大的交易,可能傾向於支持JNI & Android Java SDK。

在iOS和Android,並行線程是底層的線程機制,它已經爲你管理的,當你使用的東西,喜歡的iOS的的NSOperation和Android的的AsyncTask(我假設..)