简体   繁体   中英

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. Those java programs work perfectly. 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 ).

Now, im totally new to android and i want to make an equal client for android but i faced those problems:

1) I can't update the UI from a background thread just passing parameters(like java).

2) I want that one thread to update 2 or 3 Activies(i need 2-3 because the lack of screen space)

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. So my question is what method should i use on android to achieve that " message listener/UI updater " thread.

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??

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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