Advertisement
Howtocode

Untitled

Aug 24th, 2015
915
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.95 KB | None | 0 0
  1. public class MainActivity extends Activity implements WebSocketListener {
  2.    
  3.     private static final String SLACK_RTM_URL = "https://slack.com/api/rtm.start";
  4.     private static final String TAG = MainActivity.class.getSimpleName();
  5.     private static final String TOKEN = "...";
  6.    
  7.     private final Executor writeExecutor = Executors.newSingleThreadExecutor();
  8.    
  9.     WebSocket mWebSocket = null;
  10.  
  11.     String url = "";
  12.  
  13.     int socket_id = 1;
  14.  
  15.     @Override
  16.     protected void onCreate(Bundle savedInstanceState) {
  17.         super.onCreate(savedInstanceState);
  18.         setContentView(R.layout.activity_main);
  19.  
  20.         mHandler = new Handler();
  21.         VolleyHelper.init(this);
  22.         getRtmResponse(TOKEN);
  23.  
  24.         if (savedInstanceState == null) {
  25.             getFragmentManager().beginTransaction()
  26.                     .add(R.id.container, new PlaceholderFragment())
  27.                     .commit();
  28.         }
  29.     }
  30.  
  31.     public void initSocket() {
  32.         OkHttpClient client = new OkHttpClient();
  33.  
  34.         Request request = new Request.Builder()
  35.                 .url(url)
  36.                 .build();
  37.         WebSocketCall.create(client, request).enqueue(this);
  38.  
  39.         // Trigger shutdown of the dispatcher's executor so this process can exit cleanly.
  40.         client.getDispatcher().getExecutorService().shutdown();
  41.     }
  42.    
  43.     public void sendMessage(View view) {
  44.         EditText editText = (EditText) findViewById(R.id.message);
  45.         final String msg = editText.getText().toString();
  46.         writeExecutor.execute(new Runnable() {
  47.             @Override
  48.             public void run() {
  49.                 try {
  50.                     JSONObject msgJson = new JSONObject();
  51.                     try {
  52.                         msgJson.put("id", ++socket_id);
  53.                         msgJson.put("type", "message");
  54.                         msgJson.put("channel", "C07V5R9U6");
  55.                         msgJson.put("text", msg);
  56.                     } catch (JSONException e) {
  57.                         e.printStackTrace();
  58.                     }
  59.                     mWebSocket.sendMessage(TEXT, new Buffer().writeUtf8(msgJson.toString()));
  60.                 } catch (IOException e) {
  61.                     System.err.println("Unable to send messages: " + e.getMessage());
  62.                 }
  63.             }
  64.         });
  65.         editText.setText("");
  66.     }
  67.  
  68.     @Override
  69.     public void onOpen(final WebSocket webSocket, Response response) {
  70.         writeExecutor.execute(new Runnable() {
  71.             @Override
  72.             public void run() {
  73.                 mWebSocket = webSocket;
  74.             }
  75.         });
  76.     }
  77.  
  78.     @Override
  79.     public void onFailure(IOException e, Response response) {
  80.         e.printStackTrace();
  81.     }
  82.  
  83.     @Override
  84.     public void onMessage(final BufferedSource payload, WebSocket.
  85.             PayloadType type) throws IOException {
  86.         switch (type) {
  87.             case TEXT: {
  88.                 final String message = payload.readUtf8();
  89.                 System.out.println("MESSAGE: " + message);
  90.  
  91.                 runOnUiThread(new Runnable() {
  92.                     @Override
  93.                     public void run() {
  94.                         TextView textView = (TextView) findViewById(R.id.messages);
  95.                         textView.setText(textView.getText() + "\n" + message);
  96.                         Log.i("jhjhkhkj", message);
  97.                     }
  98.                 });
  99.             }
  100.             break;
  101.             case BINARY: {
  102.                 final String message = payload.readByteString().hex();
  103.                 System.out.println("MESSAGE: " + message);
  104.  
  105.                 runOnUiThread(new Runnable() {
  106.                     @Override
  107.                     public void run() {
  108.                         TextView textView = (TextView) findViewById(R.id.messages);
  109.                         textView.setText(textView.getText() + "\n" + message);
  110.                     }
  111.                 });
  112.             }
  113.             break;
  114.             default:
  115.                 throw new IllegalStateException("Unknown payload type: " + type);
  116.         }
  117.         payload.close();
  118.     }
  119.  
  120.     @Override
  121.     public void onPong(Buffer payload) {
  122.         Log.d(TAG, "PONG: " + payload.readUtf8());
  123.     }
  124.  
  125.     @Override
  126.     public void onClose(int code, String reason) {
  127.         Log.d(TAG, "CLOSE: " + code + " " + reason);
  128.     }
  129.  
  130.     void getRtmResponse(String token) {
  131.         RequestQueue queue = VolleyHelper.getRequestQueue();
  132.         JSONObject reqParams = null;
  133.         final String transmitUrl = SLACK_RTM_URL + "?token=" + token;
  134.         JsonObjectRequest staticDataReq = new JsonObjectRequest(com.android.volley.Request.Method.GET,
  135.                 transmitUrl, reqParams,
  136.                 getTransactionByIdSuccessListener(),
  137.                 getTransactionByIdErrorListener()) {
  138.         };
  139.  
  140.         queue.add(staticDataReq);
  141.     }
  142.  
  143.     private com.android.volley.Response.Listener<JSONObject> getTransactionByIdSuccessListener() {
  144.         return new com.android.volley.Response.Listener<JSONObject>() {
  145.             @Override
  146.             public void onResponse(JSONObject response) {
  147.                 Log.i(TAG, "getTransactionByIdSuccessListener response" + response);
  148.                 try {
  149.                     url = response.getString("url");
  150.                     initSocket();
  151.                     Log.i(TAG, "Url -" + response.getString("url"));
  152.                 } catch (Exception e) {
  153.                     Log.e(TAG, "getTransactionByIdSuccessListener Could not parse malformed JSON: \"" + response + "\"");
  154.                     e.printStackTrace();
  155.                 }
  156.             }
  157.         };
  158.     }
  159.  
  160.     private com.android.volley.Response.ErrorListener getTransactionByIdErrorListener() {
  161.         return new com.android.volley.Response.ErrorListener() {
  162.             @Override
  163.             public void onErrorResponse(VolleyError error) {
  164.                 Log.i(TAG, "Error" + error.getMessage());
  165.             }
  166.         };
  167.     }
  168.  
  169.     private Handler mHandler;
  170.  
  171.     Runnable mStatusChecker = new Runnable() {
  172.         @Override
  173.         public void run() {
  174.             ping();
  175.             int interval = 3000;
  176.             mHandler.postDelayed(mStatusChecker, interval);
  177.         }
  178.     };
  179.  
  180.     public void ping() {
  181.         writeExecutor.execute(new Runnable() {
  182.             @Override
  183.             public void run() {
  184.                 try {
  185.                     JSONObject msgJson = new JSONObject();
  186.                     try {
  187.                         msgJson.put("id", ++socket_id);
  188.                         msgJson.put("type", "ping");
  189.                     } catch (JSONException e) {
  190.                         e.printStackTrace();
  191.                     }
  192.                     mWebSocket.sendMessage(TEXT, new Buffer().writeUtf8(msgJson.toString()));
  193.                 } catch (IOException e) {
  194.                     System.err.println("Unable to send messages: " + e.getMessage());
  195.                 }
  196.             }
  197.         });
  198.  
  199.     }
  200. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement