Example usage for android.os Message obtain

List of usage examples for android.os Message obtain

Introduction

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

Prototype

public static Message obtain(Handler h, int what, Object obj) 

Source Link

Document

Same as #obtain() , but sets the values of the target, what, and obj members.

Usage

From source file:com.chess.genesis.net.SyncClient.java

@Override
public boolean handleMessage(final Message msg) {
    final JSONObject json = (JSONObject) msg.obj;

    try {/*from   w  w  w  .  ja va2s.  co m*/
        if (json.getString("result").equals("error")) {
            callback.sendMessage(Message.obtain(callback, MSG, json));
            error = true;
            return true;
        }
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    switch (msg.what) {
    case NetworkClient.GAME_STATUS:
        game_status(json);
        break;
    case NetworkClient.GAME_INFO:
        game_info(json);
        break;
    case NetworkClient.GAME_DATA:
        game_data(json);
        break;
    case NetworkClient.SYNC_GAMIDS:
        if (gameType == Enums.ONLINE_GAME)
            sync_active(json);
        else
            sync_archive(json);
        break;
    case NetworkClient.SYNC_GAMES:
        sync_recent(json);
        break;
    case NetworkClient.SYNC_MSGS:
        saveMsgs(json);
        break;
    }
    // release lock
    lock--;
    return true;
}

From source file:es.upm.dit.gsi.noticiastvi.gtv.thread.GetItemsThread.java

@Override
public void run() {
    ArrayList<Video> videos;
    try {//from  ww  w.j  av  a2s.co  m
        if (TEST) {
            videos = getTestVideos();
            handler.sendMessage(Message.obtain(handler, RESULT_OK, videos));
        } else {
            InputStream source = retrieveStream();
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                Type type = new TypeToken<ArrayList<Video>>() {
                }.getType();
                videos = gson.fromJson(reader, type);
                handler.sendMessage(Message.obtain(handler, RESULT_OK, videos));
            } else {
                handler.sendEmptyMessage(RESULT_ERROR);
            }
        }
    } catch (Exception e) {
        handler.sendEmptyMessage(RESULT_ERROR);
        Log.e("ERROR", e.getMessage());
    }
}

From source file:es.upm.dit.gsi.noticiastvi.gtv.account.CreateThread.java

@Override
public void run() {
    DefaultHttpClient client = new DefaultHttpClient();
    StringBuilder query = new StringBuilder();
    try {/*from www.j a  v  a  2  s.com*/
        query.append(Constant.SERVER_URL + "?action=" + ACTION + "&name=");
        query.append(URLEncoder.encode(username.trim(), "UTF-8"));
        HttpGet get = new HttpGet(query.toString());
        HttpResponse getResponse = client.execute(get);
        final int statusCode = getResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(), "Error " + statusCode);
            handler.sendEmptyMessage(RESULT_ERROR);
            return;
        }
        InputStream source = getResponse.getEntity().getContent();
        if (source != null) {
            Gson gson = new Gson();
            Reader reader = new InputStreamReader(source);
            Account account = gson.fromJson(reader, Account.class);
            if (account.getNombre() != null && account.getNombre() != "") {
                handler.sendMessage(Message.obtain(handler, RESULT_OK, account));
            } else {
                handler.sendEmptyMessage(RESULT_ERROR);
            }
        } else {
            handler.sendEmptyMessage(RESULT_ERROR);
        }
    } catch (Exception e) {
        handler.sendEmptyMessage(RESULT_ERROR);
        Log.e("ERROR", e.getMessage());
    }
}

From source file:org.ale.scanner.zotero.web.APIRequest.java

public void run() {
    mHandler.sendMessage(Message.obtain(mHandler, APIHandler.START, new APIResponse(this, null)));
    HttpResponse response = null;//from  ww  w .  java  2 s  . co m
    try {
        response = mHttpsClient.execute(mRequest);

        StatusLine status = response.getStatusLine();
        mHandler.sendMessage(Message.obtain(mHandler, APIHandler.STATUSLINE, new APIResponse(this, status)));

        // Check the status code if it's 400 or higher then we don't need to
        // finish reading the response, the APIHandler should know what to do.
        if (status.getStatusCode() <= 399) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();

            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            byte[] sBuffer = new byte[BUFFER_SIZE];
            while ((readBytes = inputStream.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes);
            }

            // Return result from buffered stream
            String dataAsString = new String(content.toByteArray());
            mHandler.sendMessage(
                    Message.obtain(mHandler, APIHandler.SUCCESS, new APIResponse(this, dataAsString)));
        }
    } catch (Exception e) {
        // TODO: list of all exceptions that could occur here
        mHandler.sendMessage(Message.obtain(mHandler, APIHandler.EXCEPTION, new APIResponse(this, e)));
    } finally {
        mHandler.sendMessage(Message.obtain(mHandler, APIHandler.FINISH, new APIResponse(this, null)));
    }
}

From source file:eu.andlabs.gcp.GCPService.java

private void dispatchMessage(int what, String thing) {
    try {/* www  .j  ava  2 s . co m*/
        mChatGame.send(Message.obtain(mHandler, what, thing));
    } catch (RemoteException e) {
        log("Error: " + e.toString());
    }
}

From source file:cc.wulian.smarthomev5.fragment.singin.handler.DecodeHandler.java

/**
 * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency, reuse the same reader objects from one decode to the next.
 * /*from ww  w .  j  a  v  a  2  s .co  m*/
 * @param data
 *          The YUV preview frame.
 * @param width
 *          The width of the preview frame.
 * @param height
 *          The height of the preview frame.
 */
private void decode(byte[] data, int width, int height) {
    long start = System.currentTimeMillis();
    Result rawResult = null;
    // /start rotate 90 2013.02.04///
    if (!CameraManager.get().isLandscape()) {
        byte[] rotatedData = new byte[data.length];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int index1 = (x * height + height - y - 1);
                int index2 = (x + y * width);
                if (index1 < rotatedData.length && index2 < data.length) {
                    rotatedData[index1] = data[index2];
                }
            }
        }
        int tmp = width; // Here we are swapping, that's the difference to #11
        width = height;
        height = tmp;
        data = rotatedData;
    }
    // //end rotate////
    PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(data, width, height);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    if (bitmap != null) {
        Log.d(TAG, "decode: bitmap is exists");
    } else {
        Log.d(TAG, "decode: bitmap is null");
    }
    try {
        rawResult = multiFormatReader.decodeWithState(bitmap);
    } catch (ReaderException re) {
        Log.d(TAG, "decode: ", re);
    } finally {
        multiFormatReader.reset();
    }

    if (rawResult != null) {
        long end = System.currentTimeMillis();
        Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());
        Message message = Message.obtain(scanHandlerResult.getHandler(), R.id.decode_succeeded, rawResult);
        Bundle bundle = new Bundle();
        bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());

        message.setData(bundle);
        // Log.d(TAG, "Sending decode succeeded message...");
        message.sendToTarget();
    } else {
        Message message = Message.obtain(scanHandlerResult.getHandler(), R.id.decode_failed);
        message.sendToTarget();
    }
}

From source file:com.github.shareme.gwsmaterialuikit.library.toast.ToastCompat.java

/**
 * Show the view for the specified duration.
 *///from   w w  w  .j av  a 2s  . co m
public void show() {
    if (mNextView == null) {
        throw new RuntimeException("setView must have been called");
    }
    TN tn = mTN;
    tn.mNextView = mNextView;
    Message.obtain(mHandler, MSG_ENQUEUE_TOAST, this).sendToTarget();
}

From source file:com.chess.genesis.net.SyncClient.java

@Override
public synchronized void run() {
    switch (syncType) {
    case FULL_SYNC:
        gameType = Enums.ONLINE_GAME;//w ww.j  ava2 s. c o m
        net.sync_gameids("active");
        net.run();
        trylock();

        gameType = Enums.ARCHIVE_GAME;
        net.sync_gameids("archive");
        net.run();
        trylock();

        net.sync_msgs(0);
        net.run();
        trylock();
        break;
    case REGULAR_SYNC:
        final Pref pref = new Pref(context);
        final long mtime = pref.getLong(R.array.pf_lastmsgsync);
        final long gtime = pref.getLong(R.array.pf_lastgamesync);

        net.sync_games(gtime);
        net.run();
        trylock();

        net.sync_msgs(mtime);
        net.run();
        trylock();
        break;
    case ACTIVE_SYNC:
        gameType = Enums.ONLINE_GAME;
        net.sync_gameids("active");
        net.run();
        trylock();
        break;
    case ARCHIVE_SYNC:
        gameType = Enums.ARCHIVE_GAME;
        net.sync_gameids("archive");
        net.run();
        trylock();
        break;
    case MSG_SYNC:
        net.sync_msgs(0);
        net.run();
        trylock();
        break;
    }

    if (!error) {
        final JSONObject json = new JSONObject();
        try {
            json.put("result", "ok");
            json.put("reason", "gamelist updated");
        } catch (final JSONException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        callback.sendMessage(Message.obtain(callback, MSG, json));
    }
}

From source file:uk.co.tekkies.readings.activity.ReadingsActivity.java

private void showNewsToast() {
    final String versionName = getVersionName();
    Thread thread = new Thread(new Runnable() {
        @Override/*from ww  w. j av a  2  s.co  m*/
        public void run() {
            String summary = backgroundDownloadNewsToast(versionName);
            if (summary != null && summary != "") {
                Message message = Message.obtain(newsToastHandler, 0, summary);
                newsToastHandler.sendMessage(message);
            }
        }
    });
    thread.setName("Download news toast");
    thread.start();
}

From source file:com.github.shareme.gwsmaterialuikit.library.toast.ToastCompat.java

/**
 * Close the view if it's showing, or don't show it if it isn't showing yet.
 * You do not normally have to call this.  Normally view will disappear on its own
 * after the appropriate duration./*from ww  w.  jav a2s  . com*/
 */
public void cancel() {
    Message.obtain(mHandler, MSG_CANCEL_TOAST, this).sendToTarget();
}