Android:不同类文件中的可运行对象

发布于 2024-12-01 18:51:14 字数 208 浏览 2 评论 0原文

我正在创建一个 Android 应用程序,并且正在与远程服务器连接并交换数据。到目前为止,我一直在我的活动类中使用线程和处理程序来与服务器交互,但代码变得越来越混乱和冗长。我相信拥有更多的类会让它(代码)更容易管理。

这可能是我的编程知识中的一个很大的差距,但我无法弄清楚如何将可运行对象放入不同的类中,然后让它们将消息返回到主要活动。

提前谢谢您,答案中首选示例代码。

I am creating an android app and I am connecting and exchanging data with a remote server. Up to now, I have been using threads and handlers withing my activity class to interface with the server, but the code is getting increasingly messy and long. I believe that having more classes would make it (the code) easier to manage.

This is probably a large gap in my programming knowledge, but I can't figure out how to put runnables in different classes and then have them return messages to the main activity.

Thankyou in advance, sample code is preferred in answers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城孤痞 2024-12-08 18:51:14

您可以将处理程序从活动传递到第二个类,并在需要时通过它传递消息。

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstance) {
        // ....
        Handler myHandler = new Handler() {
            @Override
            public void handleMessage (Message msg) {
                doCoolStuffWhenMessageReceived();
            }
        }
        MySecondClass secondClass = new MySecondClass(myHandler);
        // ....
    }
}

public class MySecondClass {
    private Handler handler;
    public MySecondClass(Handler handler){
        this.handler = handler;
    }

    private void someMethodToCallActivity() {
        handler.sendEmptyMessage(0);
    }

}

You can pass a handler from the activity to the second class, and pass a message through it when needed.

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstance) {
        // ....
        Handler myHandler = new Handler() {
            @Override
            public void handleMessage (Message msg) {
                doCoolStuffWhenMessageReceived();
            }
        }
        MySecondClass secondClass = new MySecondClass(myHandler);
        // ....
    }
}

public class MySecondClass {
    private Handler handler;
    public MySecondClass(Handler handler){
        this.handler = handler;
    }

    private void someMethodToCallActivity() {
        handler.sendEmptyMessage(0);
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文