Example usage for android.os Message sendToTarget

List of usage examples for android.os Message sendToTarget

Introduction

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

Prototype

public void sendToTarget() 

Source Link

Document

Sends this Message to the Handler specified by #getTarget .

Usage

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Finish response by freeing resource and sending message to the client <br>
 * This method can(must) be called after overriding {@link #onResponse(LLHttpClientBaseResponse)}.
 * //from  ww w.ja v a  2  s.  c om
 * @param _msg
 *            the message that will be sent through {@link #mHandler}
 * @param _r
 *            the {@link LLAbstractResponse} or a decorated subclass of it that contains information after requesting.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected void finishResponse(int _msg, LLAbstractResponse _r) throws IOException {
    LL.i(":) " + getClass().getSimpleName() + " is successfully:" + _r.toString());
    if (mHandler != null) {
        Message msg = Message.obtain(mHandler, _msg, _r);
        msg.sendToTarget();
    }
    // Free http's thing i.e stream and client.
    // If error at releasing, the request seems failed as well.
    _r.release();
}

From source file:com.hang.exoplayer.PlayService.java

public void pause() {
    Message message = playHandler.obtainMessage();
    message.what = 2;
    message.sendToTarget();
}

From source file:sample.multithreading.ImageDownloaderThread.java

public void run() {
    mThread = Thread.currentThread();
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    Bitmap bmReturn = null;// w ww .  ja  v a  2s  . c  o m
    try {
        if (Thread.interrupted())
            return;
        byte[] imageBuf = sCache.get(mLocation);
        if (null == imageBuf) {
            mHandler.sendEmptyMessage(DOWNLOAD_STARTED);
            InputStream is = null;
            try {
                HttpURLConnection httpConn = (HttpURLConnection) mLocation.openConnection();
                httpConn.setRequestProperty("User-Agent", NetworkDownloadService.USER_AGENT);
                if (Thread.interrupted())
                    return;
                is = httpConn.getInputStream();
                if (Thread.interrupted())
                    return;
                int contentLength = httpConn.getContentLength();

                /*
                 * We take advantage of the content length if it is returned
                 * to preallocate our buffer. If it is not returned, we end
                 * up thrashing memory a bit more.
                 */
                if (-1 == contentLength) {
                    byte[] buf = new byte[READ_SIZE];
                    int bufferLeft = buf.length;
                    int offset = 0;
                    int result = 0;
                    outer: do {
                        while (bufferLeft > 0) {
                            result = is.read(buf, offset, bufferLeft);
                            if (result < 0) {
                                // we're done
                                break outer;
                            }
                            offset += result;
                            bufferLeft -= result;
                            if (Thread.interrupted())
                                return;
                        }
                        // resize
                        bufferLeft = READ_SIZE;
                        int newSize = buf.length + READ_SIZE;
                        byte[] newBuf = new byte[newSize];
                        System.arraycopy(buf, 0, newBuf, 0, buf.length);
                        buf = newBuf;
                    } while (true);
                    imageBuf = new byte[offset];
                    System.arraycopy(buf, 0, imageBuf, 0, offset);
                } else {
                    imageBuf = new byte[contentLength];
                    int length = contentLength;
                    int offset = 0;
                    while (length > 0) {
                        int result = is.read(imageBuf, offset, length);
                        if (result < 0) {
                            throw new EOFException();
                        }
                        offset += result;
                        length -= result;
                        if (Thread.interrupted())
                            return;
                    }
                }
                if (Thread.interrupted())
                    return;
            } catch (IOException e) {
                return;
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (Exception e) {

                    }
                }
            }
        }
        mHandler.sendEmptyMessage(DECODE_QUEUED);
        try {
            sCoreAvailable.acquire();
            mHandler.sendEmptyMessage(DECODE_STARTED);
            BitmapFactory.Options bfo = new BitmapFactory.Options();
            int targetWidth = mTargetWidth;
            int targetHeight = mTargetHeight;
            if (Thread.interrupted())
                return;
            bfo.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(imageBuf, 0, imageBuf.length, bfo);
            int hScale = bfo.outHeight / targetHeight;
            int wScale = bfo.outWidth / targetWidth;
            int sampleSize = Math.max(hScale, wScale);
            if (sampleSize > 1) {
                bfo.inSampleSize = sampleSize;
            }
            if (Thread.interrupted())
                return;
            bfo.inJustDecodeBounds = false;
            // oom handling in decode stage
            for (int i = 0; i < NUMBER_OF_DECODE_TRIES; i++) {
                try {
                    bmReturn = BitmapFactory.decodeByteArray(imageBuf, 0, imageBuf.length, bfo);
                    // break out of OOM loop
                    break;
                } catch (Throwable e) {
                    Log.e(LOG_TAG, "Out of memory in decode stage. Throttling.");
                    java.lang.System.gc();
                    if (Thread.interrupted())
                        return;
                    try {
                        Thread.sleep(0xfa);
                    } catch (java.lang.InterruptedException ix) {

                    }
                }
            }
            if (mCache) {
                sCache.put(mLocation, imageBuf);
            }
        } catch (java.lang.InterruptedException x) {
            x.printStackTrace();
        } finally {
            sCoreAvailable.release();
        }
    } finally {
        mThread = null;
        if (null == bmReturn) {
            mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
        } else {
            Message completeMessage = mHandler.obtainMessage(TASK_COMPLETE, bmReturn);
            completeMessage.sendToTarget();
        }
        // clear interrupt flag
        Thread.interrupted();
    }
}

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   w w  w .j a va  2s  . c o  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.example.android.threadsample.PhotoManager.java

/**
 * Handles state messages for a particular task object
 * @param photoTask A task object//from  w ww . j a  va2  s .c  o  m
 * @param state The state of the task
 */
@SuppressLint("HandlerLeak")
public void handleState(PhotoTask photoTask, int state) {
    switch (state) {

    // The task finished downloading and decoding the image
    case TASK_COMPLETE:

        // Puts the image into cache
        if (photoTask.isCacheEnabled()) {
            // If the task is set to cache the results, put the buffer
            // that was
            // successfully decoded into the cache
            mPhotoCache.put(photoTask.getImageURL(), photoTask.getByteBuffer());
        }

        // Gets a Message object, stores the state in it, and sends it to the Handler
        Message completeMessage = mHandler.obtainMessage(state, photoTask);
        completeMessage.sendToTarget();
        break;

    // The task finished downloading the image
    case DOWNLOAD_COMPLETE:
        /*
         * Decodes the image, by queuing the decoder object to run in the decoder
         * thread pool
         */
        mDecodeThreadPool.execute(photoTask.getPhotoDecodeRunnable());

        // In all other cases, pass along the message without any other action.
    default:
        mHandler.obtainMessage(state, photoTask).sendToTarget();
        break;
    }

}

From source file:com.example.hotnewsapp.imageutil.PhotoManager.java

/**
 * Handles state messages for a particular task object
 * /*from w  w w.  j a va2  s .c o m*/
 * @param photoTask
 *            A task object
 * @param state
 *            The state of the task
 */
@SuppressLint("HandlerLeak")
public void handleState(PhotoTask photoTask, int state) {
    switch (state) {

    // The task finished downloading and decoding the image
    case TASK_COMPLETE:

        // Puts the image into cache
        if (photoTask.isCacheEnabled()) {
            // If the task is set to cache the results, put the buffer
            // that was
            // successfully decoded into the cache
            mPhotoCache.put(photoTask.getImageURL(), photoTask.getByteBuffer());
        }

        // Gets a Message object, stores the state in it, and sends it to
        // the Handler
        Message completeMessage = mHandler.obtainMessage(state, photoTask);
        completeMessage.sendToTarget();
        break;

    // The task finished downloading the image
    case DOWNLOAD_COMPLETE:
        /*
         * Decodes the image, by queuing the decoder object to run in the
         * decoder thread pool
         */
        mDecodeThreadPool.execute(photoTask.getPhotoDecodeRunnable());

        // In all other cases, pass along the message without any other
        // action.
    default:
        mHandler.obtainMessage(state, photoTask).sendToTarget();
        break;
    }

}

From source file:com.comic.lazyupload.image.PhotoManager.java

/**
 * Handles state messages for a particular task object
 * //from  w  w w. j  a v  a  2s.co m
 * @param photoTask
 *            A task object
 * @param state
 *            The state of the task
 */
public void handleState(PhotoTask photoTask, int state) {
    switch (state) {

    // The task finished downloading and decoding the image
    case TASK_COMPLETE:
        Loge.i("TASK_COMPLETE");
        // Puts the image into cache
        if (photoTask.isCacheEnabled()) {
            // If the task is set to cache the results, put the buffer
            // that was
            // successfully decoded into the cache
            mPhotoCache.put(photoTask.getImageURL(), photoTask.getByteBuffer());
        }

        // Gets a Message object, stores the state in it, and sends it to
        // the Handler
        Message completeMessage = mHandler.obtainMessage(state, photoTask);
        completeMessage.sendToTarget();
        break;

    // The task finished downloading the image
    case DOWNLOAD_COMPLETE:
        Loge.i("DOWNLOAD_COMPLETE");
        /*
         * Decodes the image, by queuing the decoder object to run in the
         * decoder thread pool
         */
        mDecodeThreadPool.execute(photoTask.getPhotoDecodeRunnable());

        // In all other cases, pass along the message without any other
        // action.
    default:
        mHandler.obtainMessage(state, photoTask).sendToTarget();
        break;
    }

}

From source file:ti.modules.titanium.geolocation.TiLocation.java

public void reverseGeocode(double latitude, double longitude, GeocodeResponseHandler responseHandler) {
    String geocoderUrl = buildGeocoderURL(TiC.PROPERTY_REVERSE, mobileId, appGuid, sessionId,
            latitude + "," + longitude, countryCode);
    if (geocoderUrl != null) {
        Message message = runtimeHandler.obtainMessage(MSG_LOOKUP);
        message.getData().putString(TiC.PROPERTY_DIRECTION, TiC.PROPERTY_REVERSE);
        message.getData().putString(TiC.PROPERTY_URL, geocoderUrl);

        message.obj = responseHandler;/*  w ww.j  av a  2s  .co  m*/
        message.sendToTarget();

    } else {
        Log.e(TAG, "Unable to reverse geocode, geocoder url is null");
    }
}

From source file:org.navitproject.navit.NavitDownloadSelectMapActivity.java

private void askForMapDeletion(final String map_location) {
    AlertDialog.Builder deleteMapBox = new AlertDialog.Builder(this);
    deleteMapBox.setTitle(Navit.getInstance().getTstring(R.string.map_delete));
    deleteMapBox.setCancelable(true);// w w  w  .  j  a  va2s  . c  o  m

    NavitMap maptoDelete = new NavitMap(map_location);
    deleteMapBox
            .setMessage(maptoDelete.mapName + " " + String.valueOf(maptoDelete.size() / 1024 / 1024) + "MB");

    // TRANS
    deleteMapBox.setPositiveButton(Navit.getInstance().getTstring(R.string.yes),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Log.d(TAG, "Delete Map");
                    Message msg = Message.obtain(Navit.getInstance().getNavitGraphics().callback_handler,
                            NavitGraphics.msg_type.CLB_DELETE_MAP.ordinal());
                    Bundle b = new Bundle();
                    b.putString("title", map_location);
                    msg.setData(b);
                    msg.sendToTarget();
                    finish();
                }
            });

    // TRANS
    deleteMapBox.setNegativeButton((Navit.getInstance().getTstring(R.string.no)),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Log.d(TAG, "don't delete map");
                }
            });
    deleteMapBox.show();
}

From source file:com.mobicomkit.api.attachment.AttachmentManager.java

/**
 * Handles state messages for a particular task object
 *
 * @param photoTask A task object//from  w  w  w.j av a 2s  . c o m
 * @param state     The state of the task
 */
@SuppressLint("HandlerLeak")
public void handleState(AttachmentTask photoTask, int state) {
    switch (state) {

    // The task finished downloading and decoding the image
    case TASK_COMPLETE:

        // Puts the image into cache
        if (photoTask.isCacheEnabled()) {
            // If the task is set to cache the results, put the buffer
            // that was
            // successfully decoded into the cache
            mPhotoCache.put(photoTask.getImageURL(), photoTask.getImage());
        }
        // Gets a Message object, stores the state in it, and sends it to the Handler
        Message completeMessage = mHandler.obtainMessage(state, photoTask);
        completeMessage.sendToTarget();
        break;

    // The task finished downloading the image
    case DOWNLOAD_COMPLETE:
        /*
         * If it is a image than decodes the image, by queuing the decoder object to run in the decoder
         *
         */
        if (photoTask.getPhotoView() != null && photoTask.getContentType() != null
                && photoTask.getContentType().contains("image")) {
            mDecodeThreadPool.execute(photoTask.getPhotoDecodeRunnable());
        } else {
            //We need not to cache the Data here ..as we have nothing to load
            // ...directly sending TASK complete message is enough
            mHandler.obtainMessage(TASK_COMPLETE, photoTask).sendToTarget();
            BroadcastService.sendMessageUpdateBroadcast(photoTask.getContext(),
                    BroadcastService.INTENT_ACTIONS.MESSAGE_ATTACHMENT_DOWNLOAD_DONE.toString(),
                    photoTask.getMessage());
        }

        // In all other cases, pass along the message without any other action.
    default:
        mHandler.obtainMessage(state, photoTask).sendToTarget();
        break;
    }

}