自定义监听器

时间:2015-01-04 08:20:49

标签: java android sockets listener

我正在开发聊天应用程序。目前我确实喜欢这样,当我打开ChatActvity时,所有套接字都被注册并且聊天工作......现在我想改变编码结构..我想在类中打开套接字,而不是在Activity类中我需要为该类添加一个监听器。我是如何实现这个的??

private class Chatroom {
    private static void initialise() {
        // Initialising the sockets and registering listeners to each socket
    }
}

我希望在我的activity类中通知Chatroom类中的套接字侦听器被调用..

1 个答案:

答案 0 :(得分:2)

这可能是你需要的:

    public class RequestSender extends AsyncTask<String, Void, String> {

    private final static String serverIP = "192.168.1.1";
    private final static Integer serverPort = 1234;
    private ServerResponseListener listener = null;

    public void setServerResponseListener(ServerResponseListener listener){
         this.listener=listener;
    }

    public interface ServerResponseListener {
         public void onResponseReceive(String response);
    }


    @Override
    protected String doInBackground(String... params) {
        Socket socket = null;
        try {
             socket = new Socket(serverIP, serverPort);
        } catch (IOException e) {
             // return "server is unreachable" message or something
        }

        PrintWriter requestWriter = new PrintWriter(socket.getOutputStream());
        BufferedReader resultReader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
        String request = params[0] //for example
        requestWriter.println(request);
        requestWriter.flush();
        String result = null;
        while ((result = resultReader.readLine()) != null) {}
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        listener.onResponseReceive(result);
    }

}

这里是如何从Activity:

执行AsynchTask的示例
public class MainActivity extends Activity{
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         RequestSender requestSender = new RequestSender();
         requestSender.setServerResponseListener(new RequestSender.ServerResponseListener(){
             @override
             public void onResponseReceive(String response){
                 //
             }
         });
         requestSender.execute("message");
     }
}

请阅读:http://developer.android.com/reference/android/os/AsyncTask.html