0

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?

MaTo
  • 3
  • 2
  • You either need to make the methods you are calling static, or somehow add a reference to an instance and make it static, or pass an instance to the object the methods are in in the `onProgressUpdate` method – Austin Apr 29 '16 at 21:45
  • You can't use `static` methods there because you can't do anything useful with them. You need to have a reference to the Activity that started this `AsyncTask`. If your task is defined outside the activity like http://stackoverflow.com/a/5523637 for example – zapl Apr 29 '16 at 23:15

1 Answers1

1

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]);
    }
}
UFC Insider
  • 838
  • 1
  • 7
  • 19