Search code examples
androidcocos2d-x

cocos2d-x: threads


I get a small problem: I need using async task in cocos2d-x on Android.

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

But this code crash application with error Can't create handler inside thread that has not called Looper.prepare(). I solve this by adding 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)); 
}
});

Where "me" is my Activity. Code from 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 task its a simple AsyncTask that get JSON from server. So, my question: is this solution is right/wrong? Or you can give me other solution?


Solution

  • I don't see why you couldn't do that. You could also use libcurl like m.ding mentioned, along with pthreads and a json parser. But the problem there is that you'd need to manage the pthreads yourself. It's "messier" than just doing it the way you're doing it now. Then again, using the JNI isn't exactly pretty either. It's one big giant trade-off, probably leaning in favor of the JNI & Android Java SDK.

    On iOS and Android, pthreads are the underlying threading mechanism, which are already managed for you when you use things like iOS's NSOperation and Android's AsyncTask (I'm assuming..)