简体   繁体   English

在Java类之间进行通信

[英]Communicating between Java Classes

I've been trying to write a simple 3 class java app for android but i can't figure out one thing. 我一直在尝试为Android编写一个简单的3类Java应用程序,但我一无所获。 How would one approach the problem of passing data between classes? 如何处理在类之间传递数据的问题? In my case I have 3 classes: 就我而言,我有3个班级:

  1. Waits on a socket for data 在套接字上等待数据
  2. Parses the data 解析数据
  3. Writes the data on the screen 在屏幕上写入数据

The third class cannot do the network part because it involves a waiting loop which cannot be done in the Activity class. 第三类不能做网络部分,因为它涉及一个等待循环,这在Activity类中是无法完成的。

So how should I do that? 那我该怎么办呢?

You can define a Listener which is implemented by the "writes-on-the-screen" class and which the "parses-the-data" class uses to talk to it. 您可以定义一个侦听器,该侦听器由“屏幕上写”类实现,并且“解析数据”类用于与其进行对话。 Example: 例:

class Parser {
    private ParsingFinishedListener callback;

    public Parser(ParsingFinishedListener c) {
        this.callback = c;
    }

    //some code

    public void parse(String stuffToParse) {
         //code
         callback.onTextParsed(parsedText);
    }

    public interface ParsingFinishedListener {
         public void onTextParsed(String textToVizualize);
    }
}

class MyTask extends AsyncTask<Void, Void, Void> {
    private ParsingFinishedListener callback;         
    public MyTask(ParsingFinishedListener c) {
        this.callback = c;
    }

    ..doInBackground..

    ..onPostExecute(String result) {
        Parser p = new Parser(callback);
        p.parse(result);
    }
}

class MyActivity extends Activity implements ParsingFinishedListener {

    ...onCreate(...) {
        ...
        MyTask task = new MyTask((ParsingFinishedListener) this);
        task.execute();
    }
    //some code

    @Override
    public void onTextParsed(String result) {
         //do something with the result
    }

}

You define your listener in the Parser and when finished parsing, you use it to get to the Activity, which should have implemented it. 您可以在解析器中定义您的侦听器,并在完成解析后使用它来访问应该已经实现了它的Activity。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM