Example usage for android.os Handler Handler

List of usage examples for android.os Handler Handler

Introduction

In this page you can find the example usage for android.os Handler Handler.

Prototype

@UnsupportedAppUsage
public Handler(boolean async) 

Source Link

Document

Use the Looper for the current thread and set whether the handler should be asynchronous.

Usage

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

public MessagingManagerThread(final Context context) {
    mContext = context;/* ww  w. j a  va2  s  .  c o m*/
    mHelper = DBHelper.getGlobal(context);
    mIdent = new DBIdentityProvider(mHelper);
    mMessageDropHandler = new MessageDropHandler();

    ConnectionStatus status = new ConnectionStatus() {
        public boolean isConnected() {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            return info != null && info.isConnected();
        }
    };
    mMessenger = new RabbitMQMessengerService(wrapIdent(mIdent), status);
    mMessenger.addStateListener(new StateListener() {
        public void onReady() {
            Log.i(TAG, "Connected to message transport!");
        }

        public void onNotReady() {
            Log.i(TAG, "Message transport not available.");
        }
    });
    mMessenger.addMessageListener(new MessageListener() {
        public void onMessage(IncomingMessage incoming) {
            if (DBG)
                Log.i(TAG, "Got incoming message " + incoming);
            handleIncomingMessage(incoming);
        }
    });
    mMessenger.addConnectionStatusListener(new ConnectionStatusListener() {

        @Override
        public void onStatus(String msg, Exception e) {
            StringWriter err = new StringWriter();
            PrintWriter p = new PrintWriter(err);
            if (e != null) {
                p.println(e.toString());
                p.println(e.getMessage());
                e.printStackTrace(p);
            }
            Log.e(TAG, "Connection Status: " + msg + "\n" + err.toString());
        }
    });

    mOco = new ObjectContentObserver(new Handler(mContext.getMainLooper()));
    mContext.getContentResolver()
            .registerContentObserver(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feeds"), true, mOco);
    mContext.getContentResolver()
            .registerContentObserver(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/out"), true, mOco);
}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * Connect to WebSocketServer with additional Header.
 * When unsubscribe is called, the observable will disconnect automatically.
 * <p>/* w w  w. ja v a2s  .c  o m*/
 * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD,
 * you have to use subscribeOn to specify thread model.
 *
 * @param uri
 * @param extraHeaders
 * @return
 */
public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) {
    this.disconnect(false);

    this.mUri = uri;
    this.mExtraHeaders = extraHeaders;
    this.mParser = new HybiParser(this);

    this.mHandlerThread = new HandlerThread(getClass().getName());
    this.mHandlerThread.start();
    this.mHandler = new Handler(mHandlerThread.getLooper());

    return Observable.create(new Observable.OnSubscribe<Event>() {
        @Override
        public void call(Subscriber<? super Event> subscriber) {
            try {
                mSubscriber = subscriber;
                String secret = createSecret();
                String scheme = mUri.getScheme();

                // uri have invalid scheme throw MalformedURLException
                if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) {
                    new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\".");
                }

                int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80);
                String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath();
                if (!TextUtils.isEmpty(mUri.getQuery())) {
                    path += "?" + mUri.getQuery();
                }

                String originScheme = scheme.equals("wss") ? "https" : "http";
                Uri origin = Uri.parse(originScheme + "://" + mUri.getHost());

                SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory()
                        : SocketFactory.getDefault();
                mSocket = factory.createSocket(mUri.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mUri.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (Pair<String, String> pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.first, pair.second));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new ConnectException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new ProtocolException(
                            "Server sent invalid response code " + statusLine.getStatusCode()
                                    + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS);
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new ProtocolException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new ProtocolException("No Sec-WebSocket-Accept header.");
                }

                mIsConnected = true;
                emitterOnNext(new Event(EventType.CONNECT));

                // Now decode websocket frames.
                mParser.start(stream);
            } catch (Exception e) {
                emitterOnError(e);
            }
        }
    }).doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            RxWebSocketClient.this.disconnect(false);
        }
    });
}