MaTo MaTo - 7 months ago 18
Java Question

Android onProgressUpdate can only call static method?

I have a problem in my android game. I use AsyncTask and in onProgressUpdate I call Static method from activity class. Something like this:

protected void onProgressUpdate(Message... values) {
super.onProgressUpdate(values);
OnlineGameActivity.refreshGame(values[0]);
}


And then in onlineGameActivity method refreshGame I need call some other non-static method which upate game status for example:

public class OnlineGameActivity extends Activity {

public static void refreshGame(Message message) {
switch (message.getType()) {
case 1:
methode1();
break;
case 2:
methode2();
break;
case 3:
methode3();
break;
}


It is possible do something like this?

Answer

Yes. You can pass an os.Handler instance to your AsyncTask and then send an empty message to it. Something similar to the following:

public class OnlineGameActivity extends Activity {

    Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 0:
                   ...
                   break;

                ...
            }
        }
    }

    public OnlineGameActivity(...) {
        ...

        YourAsyncTask task = new YourAsyncTask(myHandler);
        task.execute();
    }
}

and your AsyncTask:

public class YourAsyncTask extends AsyncTask<...> {

    Handler myHandler;

    public YourAsyncTask(Handler myHandler) {
        this.myHandler = myHandler;
    }

    ...

    @Override
    protected void onProgressUpdate(Message... values) {
        myHandler.sendEmptyMessage(values[0]);
    }
}