2016-06-13 55 views
0

我正在尋找一種方法將套接字服務中接收到的數據(設置標誌時接收)發送到綁定到服務的活動。做這個的最好方式是什麼 ?處理程序,AsyncTask或其他東西?Android將套接字服務收到的數據發送到活動

這是SocketClass我使用開始連接和處理傳入的消息:

class connectSocket implements Runnable { 

    @Override 
    public void run() { 

     running= true; 
     try { 
      socket = new Socket(serverAddr, SERVERPORT); 
      try { 
       mBufferOut = new ObjectOutputStream(socket.getOutputStream()); 
       mBufferIn = new ObjectInputStream(socket.getInputStream()); 
       while(running){ 
        msg = (Message) mBufferIn.readObject(); 
       } 

      } 
      catch (Exception e) { 
       Log.e("TCP", "S: Error", e); 
      } 
     } catch (Exception e) { 
      Log.e("TCP", "C: Error", e); 
     } 

    } 

} 

更新:

public class SocketService extends Service { 
private static final String TAG = "com.oos.kiesa.chat"; 
public static final String SERVERIP = "192.168.X.X"; 
public static final int SERVERPORT = 4444; 
private ObjectOutputStream mBufferOut; 
private ObjectInputStream mBufferIn; 
Socket socket; 
InetAddress serverAddr; 
boolean mRun; 
Object msg; 
public Integer command; 
@Override 
public IBinder onBind(Intent intent) { 
    return myBinder; 
} 

private final IBinder myBinder = new LocalBinder(); 

public class LocalBinder extends Binder { 
    public SocketService getService() { 
     return SocketService.this; 

    } 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 
} 

public void IsBoundable(){ 
    Toast.makeText(this,"is boundable", Toast.LENGTH_LONG).show(); 
} 


public void sendMessage(String message) throws IOException { 
    if (mBufferOut != null) { 
     mBufferOut.writeObject(message); 
     mBufferOut.flush(); 
    } 
} 

public void sendMessage(Message message) throws IOException { 
    if (mBufferOut != null) { 
     mBufferOut.writeObject(message); 
     mBufferOut.flush(); 
    } 
} 

public void sendMessage(User user) throws IOException { 
    if (mBufferOut != null) { 
     mBufferOut.writeObject(user); 
     mBufferOut.flush(); 
    } 
} 

public void sendMessage(int command) throws IOException { 
    if (mBufferOut != null) { 
     mBufferOut.writeInt(command); 
     mBufferOut.flush(); 
    } 
} 


@Override 
public int onStartCommand(Intent intent,int flags, int startId){ 
    super.onStartCommand(intent, flags, startId); 
    System.out.println("I am in on start"); 
    Runnable connect = new connectSocket(); 
    new Thread(connect).start(); 
    return START_STICKY; 
} 

public void stopClient() throws IOException{ 

    if (mBufferOut != null) { 
     mBufferOut.flush(); 
     mBufferOut.close(); 
    } 

    mBufferIn = null; 
    mBufferOut = null; 
    socket.close(); 
} 

class connectSocket implements Runnable { 

    @Override 
    public void run() { 

     mRun = true; 
     try { 
      socket = new Socket(serverAddr, SERVERPORT); 
      try { 
       mBufferOut = new ObjectOutputStream(socket.getOutputStream()); 
       mBufferIn = new ObjectInputStream(socket.getInputStream()); 
       while(mRun){ 
        switch(command.intValue()){ 
         case Constants.ADD_MESSAGE: 
          msg = (Message) mBufferIn.readObject(); // send message to Activity 
          break; 
        } 
       } 

      } 
      catch (Exception e) { 
       Log.e("TCP", "S: Error", e); 
      } 
     } catch (Exception e) { 
      Log.e("TCP", "C: Error", e); 
     } 

    } 

} 
@Override 
public void onDestroy() { 
    super.onDestroy(); 
    try { 
     socket.close(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    socket = null; 
} 

}

一些指導/例子是非常感謝

+0

和例如實現它在Singleton Sockethandlerimpl類中,您可以從任何地方訪問。 – mrkernelpanic

+0

我正在做一個非常基本的聊天應用程序,收到的消息必須儘快顯示在列表視圖中。我認爲我需要在一個線程(Activity內部的處理程序)或其他東西中完成它,除此之外,我沒有那麼多的java經驗,因爲我希望擁有這些經驗。 – Kiesa

回答

1

我送你我的,希望這將有助於:

class SocketRequestHandler extends Thread { 

    static String EOF = "<EOF>"; 

    TCPResponseModel tcpResponseDS; 
    Activity activity; 
    boolean doSkip = false; 

    String responseStringComplete = ""; 
    Socket clientSocekt; 
    OutputStream clientSocketOutputStream; 
    PrintWriter clinetSocketPrintWriter; 
    DataInputStream clientSocketInputStream; 

    private SocketRequestHandler(TCPResponseModel tcpResponseDS, Activity activity, SaloonListener listener) { 
     this.tcpResponseDS = tcpResponseDS; 
     this.activity = activity; 
     this.listener = listener; 
     moreStores = tcpResponseDS.StoresFound; 
    } 

    public static SocketRequestHandler pingAll(Activity activity, TCPResponseModel tcpResponseDS, SaloonListener listener) { 
     SocketRequestHandler requestHandler = new SocketRequestHandler(tcpResponseDS, activity, listener); 
     requestHandler.start(); 
     return requestHandler; 
    } 

    private void closeStreams() { 
     try { 
      clientSocekt.close(); 
      clientSocketInputStream.close(); 
      clinetSocketPrintWriter.close(); 
      clientSocketOutputStream.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void run() { 
     try { 
      String pingingHost = "URL_TO_PING"; 
      clientSocekt = new Socket(pingingHost, 12000); 
      clientSocketOutputStream = clientSocekt.getOutputStream(); 
      clinetSocketPrintWriter = new PrintWriter(clientSocketOutputStream); 
      String firstPing = "{\"RequestId\":" + tcpResponseDS.RequestId + "}<EOF>"; 
      clinetSocketPrintWriter.println(firstPing); 
      clinetSocketPrintWriter.flush(); 
      byte[] bytes; 
      String pingStr = ""; 
      clientSocketInputStream = new DataInputStream(clientSocekt.getInputStream()); 
      while (true) { 
       bytes = new byte[1024]; 
       clientSocketInputStream.read(bytes); 
       bytes = trim(bytes); 
       if (bytes.length > 0 && !doSkip) { 
        String newString = new String(bytes, "UTF-8"); 
        String decoded = pingStr + newString; 
        pingStr = checkForMessage(decoded); 
        responseStringComplete += newString; 
       } 
       if (doSkip) { 
        break; 
       } 
      } 
      closeStreams(); 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      System.out.print(responseStringComplete); 
     } 
    } 


} 

要廣播聊天數據只是做:

msg = (Message) mBufferIn.readObject(); // Do code after this line        
Intent localIntent = new Intent("CHAT_MESSAGE"); 
localIntent.putExtra("message", msg); 

LocalBroadcastManager.getInstance(上下文).sendBroadcast(localIntent);

現在在你是顯示聊天列表中的活動爲什麼不使用普通的Java,即定義您的回調接口,你可以做

class ReceiveMessages extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      final String action = intent.getAction(); 
      if (action.equals("CHAT_MESSAGE")) { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         String chatMessage = getIntent().getStringExtra("message"); 
         //get data from intent and update your chat list. 
        } 
       }); 
      } 
     } 
    } 
    ReceiveMessages myReceiver; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //your code 
     myReceiver = new ReceiveMessages(); 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, 
       new IntentFilter("CHAT_MESSAGE")); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver); 
    } 
+0

嘿,那裏,謝謝你分享你的代碼。我試圖做一個簡單的聊天應用程序,我的服務正在運行,而TCP連接是打開的,所以我可以隨時在任何Activity中獲取數據,我只是沒有真正知道如何顯示例如從服務器在我的列表視圖(ChatActivity) – Kiesa

+0

如果你的服務器能夠處理套接字連接,那麼這是你可以做的最好最快的事情。您只需要在連續運行的服務上運行此代碼,該服務將打開客戶端套接字並進行通信。現在使用本地廣播只是播放從服務器獲取的所有數據。現在,您只需將接收器放在任何託管活動中,您就可以輕鬆獲得聊天數據。 – Neo

+0

我更新了我的問題,包括整個服務類。我很確定我錯過了一些重要的東西,我只是不知道該怎麼做。我正在尋找我的大腦即將爆炸的日子。你能看看它嗎? – Kiesa

0

/** * 創建者Tanveer Bulsari於2013年7月9日 */ 公共類AsyncHttpClient {

public AsyncHttpClient() { 

} 

public static class SocketIORequest { 

    private String mUri; 
    private String mEndpoint; 
    private List<BasicNameValuePair> mHeaders; 

    public SocketIORequest(String uri) { 
     this(uri, null); 
    } 

    public SocketIORequest(String uri, String endpoint) { 
     this(uri, endpoint, null); 
    } 

    public SocketIORequest(String uri, String endpoint, List<BasicNameValuePair> headers) { 
     mUri = Uri.parse(uri).buildUpon().encodedPath("/socket.io/1/").build().toString(); 
     mEndpoint = endpoint; 
     mHeaders = headers; 
    } 

    public String getUri() { 
     return mUri; 
    } 

    public String getEndpoint() { 
     return mEndpoint; 
    } 

    public List<BasicNameValuePair> getHeaders() { 
     return mHeaders; 
    } 
} 

public static interface StringCallback { 
    public void onCompleted(final Exception e, String result); 
} 

public static interface WebSocketConnectCallback { 
    public void onCompleted(Exception ex, WebSocketClient webSocket); 
} 

public void executeString(final SocketIORequest socketIORequest, final StringCallback stringCallback) { 

    new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... params) { 

      AndroidHttpClient httpClient = AndroidHttpClient.newInstance("android-websockets-2.0"); 
      HttpPost post = new HttpPost(socketIORequest.getUri()); 
      addHeadersToRequest(post, socketIORequest.getHeaders()); 

      try { 
       HttpResponse res = httpClient.execute(post); 
       String responseString = readToEnd(res.getEntity().getContent()); 

       if (stringCallback != null) { 
        stringCallback.onCompleted(null, responseString); 
       } 

      } catch (IOException e) { 

       if (stringCallback != null) { 
        stringCallback.onCompleted(e, null); 
       } 
      } finally { 
       httpClient.close(); 
       httpClient = null; 
      } 
      return null; 
     } 

     private void addHeadersToRequest(HttpRequest request, List<BasicNameValuePair> headers) { 
      if (headers != null) { 
       Iterator<BasicNameValuePair> it = headers.iterator(); 
       while (it.hasNext()) { 
        BasicNameValuePair header = it.next(); 
        request.addHeader(header.getName(), header.getValue()); 
       } 
      } 
     } 
    }.execute(); 
} 

private byte[] readToEndAsArray(InputStream input) throws IOException { 
    DataInputStream dis = new DataInputStream(input); 
    byte[] stuff = new byte[1024]; 
    ByteArrayOutputStream buff = new ByteArrayOutputStream(); 
    int read = 0; 
    while ((read = dis.read(stuff)) != -1) { 
     buff.write(stuff, 0, read); 
    } 

    return buff.toByteArray(); 
} 

private String readToEnd(InputStream input) throws IOException { 
    return new String(readToEndAsArray(input)); 
} 
+0

使用此套接字客戶端 –

相關問題