Android onProgressUpdate只能调用静态方法吗?

时间:2016-04-29 21:36:09

标签: java android

我的安卓游戏中有问题。我使用AsyncTask并在onProgressUpdate中从活动类调用Static方法。像这样:

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

然后在onlineGameActivity方法中,我需要调用一些其他非静态方法来提升游戏状态,例如:

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;
}

有可能做到这样吗?

1 个答案:

答案 0 :(得分:1)

是。您可以将os.Handler实例传递给AsyncTask,然后向其发送空消息。类似于以下内容:

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();
    }
}

和您的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]);
    }
}