这该怎么办? (安卓)

发布于 2024-10-28 09:32:57 字数 354 浏览 0 评论 0原文

我对如何实现某件事以及应该如何完成某件事感到困惑,因为我相信方法不止一种;

我有一个应用程序,一开始它会建立到服务器的 TCP 连接,然后时不时地假装您按下按钮并向服务器发送一个字符串。实际上,连接(我使用过 java.net.Socket)应该在主 UI 线程(当前所在的位置)之外的单独线程中运行。

我有一个公共方法,因此当按下按钮时,会调用该方法并发送数据,但这又是从主 UI 线程运行的。由于连接在应用程序的整个生命周期中保持不变,因此它可能应该是一个意向服务,但是您可以在意向服务中拥有一个可调用的方法来通过后台连接在后台发送数据吗?

或者在 onStart() 方法中连接套接字然后在服务内实现 asynctask 的服务?我迷路了!

I am confused as to how I can achieve something and how it should be done as I believe there is more than one method;

I have an app and at the start it establishes a TCP connection to a server, then every now and again lets pretend you press a button and send a string to the server. Really the connection (I've used java.net.Socket) should run in a separate thread out of the main UI thread (which is where it currently is).

I have a public method so when the button is pressed, the method is called, and the data sent but again this runs from the main UI thread. Since the connection is constant throughout the life cycle of the app it should probably be an intent service, but can you have a call'able method within an intent service to send the data in the back ground over the back ground connection?

Or a service which connects the socket in the onStart() method and then within the service implement an asynctask? I'm lost!

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

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

发布评论

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

评论(2

画中仙 2024-11-04 09:32:57

例如,您可以使用 synchronized 来执行此操作(当然,这只是一个临时措施,不处理任何异常):

public class SyncedTcpClient extends Thread{
    synchronized boolean new_data_available = false;
    String _data = null;
    public void run()
    {
        Socket s = new Socket("127.0.0.1", 3000);

        while(1)
        {
           synchronized(this)
            {
                if(new_data_available)
                {
                   // send data
                       new_data_available = false;
                }
                else
                {
                   wait();
                }
            }
        }
    }
    public void setData(String data)
    {
        _date = data;
        new_data_available = true;
    }
}

在您的活动 (MyActivity.java) 中添加:

OnClickListener myListener = new OnClickListener(){
    public void onClick(View v) {
        tcpThread.setData(data_to_send);
        tcpThread.notify();
    }
};

在建立连接之后,客户端将检查是否有新的数据发送可用,如果没有,它将等待通知。另外,您可能会发现这个问题很有用

编辑:
由于评论太多,我编辑了我的答案。

您必须从某个地方启动 tcpClient 线程,对吧?所以从你的活动中去做吧。这样您将拥有线程的对象(正如我们在 myListener 中使用的那样)。关于 notify() - 当我们不谈论线程时,这是没有意义的(如果我错了,请有人纠正我),它的目的是“释放”由于以下原因而处于等待状态的线程继续执行相同的对象,在本例中是客户端线程本身(synchronized(this)),因此我们告诉它继续,在此之前,我们将循环中的条件更改为 true (在方法中setData(String)),因此现在它将发送数据,并再次进入等待模式。

You can use synchronized to perform that, for example (and this is just a scratch of course, not handling any exception):

public class SyncedTcpClient extends Thread{
    synchronized boolean new_data_available = false;
    String _data = null;
    public void run()
    {
        Socket s = new Socket("127.0.0.1", 3000);

        while(1)
        {
           synchronized(this)
            {
                if(new_data_available)
                {
                   // send data
                       new_data_available = false;
                }
                else
                {
                   wait();
                }
            }
        }
    }
    public void setData(String data)
    {
        _date = data;
        new_data_available = true;
    }
}

And in your activity (MyActivity.java) you add:

OnClickListener myListener = new OnClickListener(){
    public void onClick(View v) {
        tcpThread.setData(data_to_send);
        tcpThread.notify();
    }
};

after the connection is established, the client will check if new data to send available, and if not, it will wait to notify. Also, you might find this question useful

EDIT:
Since it's too much for a comment, I edited my answer.

You have to start the tcpClient thread from somewhere, right? So do it from your activity. This way you'll have the object of the thread (as we used it in myListener). regarding notify() - this is meaningless when we are not talking about threads (If I'm wrong, please someone correct me) and it's purpose is to "free" threads that are on wait because of the same object to continue in execution, in this case is the client thread itself(synchronized(this)) so we tell it to continue, and just before that, we change the condition in the loop to be true (in the method setData(String)) so it will now send the data, and go into wait mode again.

清引 2024-11-04 09:32:57

您可以使用 AsyncTask。在 doInBackground 函数中,您将发送数据、获取响应等。这将释放 UI 线程。在 onPostExecute 中,您可以使用后台任务的结果更新 UI 线程。

You could use an AsyncTask. Inside your doInBackground function, you would send your data, get the response, etc. This will free up the UI thread. In onPostExecute, you can update the UI thread with the results of the background task.

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