简体   繁体   English

Android:如何创建一个等待服务器消息并更新UI的线程?

[英]Android: How to make a thread which waits for server messages and updates the UI?

i have made a java server and java client programms that communicate with TCP sockets sending String messages. 我已经制作了一个Java服务器和Java客户端程序,可以与发送String消息的TCP套接字进行通信。 Those java programs work perfectly. 这些java程序运行完美。 The client logic is that it has a UI and a thread , which is waiting all the time for new messages and updates the UI accordingly what message it recieved ( ex add buttons,set buttons visible, change texts ). 客户端逻辑是它具有一个UI和一个线程 ,该线程一直在等待新消息并相应地更新UI接收到的消息( 例如添加按钮,设置按钮可见,更改文本 )。

Now, im totally new to android and i want to make an equal client for android but i faced those problems: 现在,我对android完全陌生,我想为android做一个平等的客户,但我遇到了这些问题:

1) I can't update the UI from a background thread just passing parameters(like java). 1)我不能仅通过参数(如java)从后台线程更新UI。

2) I want that one thread to update 2 or 3 Activies(i need 2-3 because the lack of screen space) 2)我希望一个线程更新2或3个活动(我需要2-3个活动,因为缺少屏幕空间)

I have read about AsyncTask but they say it is recommended for sort tasks, then i read about threads with handlers but they say is difficult to work with and i got confused. 我已经阅读了有关AsyncTask的信息,但他们说建议将其用于排序任务,然后我阅读了有关带有处理程序的线程的信息,但他们说很难使用,并且感到困惑。 So my question is what method should i use on android to achieve that " message listener/UI updater " thread. 所以我的问题是我应该在android上使用哪种方法来实现“ 消息监听器/ UI更新器 ”线程。

UPDATE : Ok, i used threads and handlers and my main activity got updated, but now how i can update the second Activitie from that thread too?? 更新 :好的,我使用了线程和处理程序,并且我的主要活动得到了更新,但是现在我如何也可以从该线程更新第二个Activitie?

well, you can start a thread for some specific time and after that check if there is any message from server, if not, restart the thread or else do your work. 好了,您可以在一个特定的时间启动一个线程,然后检查服务器是否有任何消息,如果没有,则重新启动该线程或执行您的工作。 hope this is helpful. 希望这会有所帮助。

you can implement it like this package com.example.a41264.myapplication; 您可以像com.example.a41264.myapplication这个程序包一样实现它;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by 41264 on 04/23/17.
 */

public class Client implements Runnable{
   final  CopyOnWriteArrayList<MsgListener> listeners = new CopyOnWriteArrayList<>();
    @Override
    public void run() {
        Socket socket = new Socket();
        try {
            int yourPort = 0;
            SocketAddress address = new InetSocketAddress("your ip",yourPort);
            socket.connect(address);
            int your_buffer_size = 1024;
            byte[] buffers = new byte[your_buffer_size];
            InputStream is = socket.getInputStream();
            int resultLength;
            String msg;
            while(true){
                resultLength = is.read(buffers);
                msg = new String(buffers,0,resultLength);
                if(listeners.size() != 0){
                    for(MsgListener msgListener: listeners){
                        msgListener.onMsgRecived(msg);
                    }
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addListener(MsgListener listener){
        listeners.add(listener);
    }
    public void removeListener(MsgListener listener){
        listeners.remove(listener);
    }

    public interface MsgListener{
        void onMsgRecived(String msg);
    }
}

and do your work at activity like this 并在这样的活动中做你的工作

package com.example.a41264.myapplication;

import android.app.Activity;
import android.util.Log;

/**
 * Created by 41264 on 04/23/17.
 */

public class YourActivity extends Activity{

    private Client client; //you need to get your clent;

    private Client.MsgListener msgListener = new Client.MsgListener() {
        @Override
        public void onMsgRecived(final String msg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //do your own work in main thread
                    Log.i("tag",msg);
                }
            });
        }
    };

    @Override
    protected void onRestart() {
        super.onRestart();
        client.addListener(msgListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        client.removeListener(msgListener);
    }
}

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

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