2016-11-14 157 views
0

我正在嘗試爲websocket發送創建庫。在Websocket onMessage中的android回調接口

public class SocketCls { 
    private WebSocketClient mWebSocketClient; 
    private void connectWebSocket(String url) throws URISyntaxException { 
     URI uri; 
     uri = new URI(url); 

     mWebSocketClient = new WebSocketClient(uri) { 
      @Override 
      public void onOpen(ServerHandshake serverHandshake) { 
       Log.i("Websocket", "Opened"); 
       mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); 
      } 

      @Override 
      public void onMessage(String s) { 
       final String message = s; 
       // Here i want to use callback 
      } 

      @Override 
      public void onClose(int i, String s, boolean b) { 
       Log.i("Websocket", "Closed " + s); 
      } 

      @Override 
      public void onError(Exception e) { 
       Log.i("Websocket", "Error " + e.getMessage()); 
      } 
     }; 
     mWebSocketClient.connect(); 
    } 
} 

通常我可以實現它,但是當我想它放在單獨的包如何使用回調?請誰能幫助我走出這個

回答

1

你可以添加一些接口WebSocketListener, 其中將包含的onMessage,OnClose中,onError的等

,並在您SocketCls的構造函數,你可以設置此監聽器,並用它WebSockets的回調

public class SocketCls { 
public interface SocketListener { 
    void onOpen(ServerHandshake serverHandshake); 
    void onMessage(String s); 
    void onClose(int i, String s, boolean b); 

} 

SocketListener listener; 

public SocketCls(SocketListener l) { 
    listener = l; 
} 
private WebSocketClient mWebSocketClient; 
private void connectWebSocket(String url) throws URISyntaxException { 
    URI uri; 
    uri = new URI(url); 

    mWebSocketClient = new WebSocketClient(uri) { 
     @Override 
     public void onOpen(ServerHandshake serverHandshake) { 
      Log.i("Websocket", "Opened"); 
      mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); 
      listener.onOpen(serverHandshake); 
     } 

     @Override 
     public void onMessage(String s) { 
      final String message = s; 
      // Here i want to use callback 
      listener.onMessage(s); 
     } 

     @Override 
     public void onClose(int i, String s, boolean b) { 
      Log.i("Websocket", "Closed " + s); 
      listener.onClose(i, s, b); 
     } 

     @Override 
     public void onError(Exception e) { 
      Log.i("Websocket", "Error " + e.getMessage()); 
     } 
    }; 
    mWebSocketClient.connect(); 
} 

}

+0

能否請你解釋我如何調用connectWebSocket方法在另一個包與聽衆..請 – Viresh

+0

如果你想打電話給連接到ctWebSocket,你應該公開它 – Pein