Example usage for android.os Handler post

List of usage examples for android.os Handler post

Introduction

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

Prototype

public final boolean post(Runnable r) 

Source Link

Document

Causes the Runnable r to be added to the message queue.

Usage

From source file:io.selendroid.server.ServerInstrumentation.java

@SuppressWarnings("unchecked")
@Override/*ww w.  j av  a  2 s  .co m*/
public void onCreate(Bundle arguments) {
    Handler mainThreadHandler = new Handler();
    this.args = new InstrumentationArguments(arguments);

    mainActivityName = arguments.getString("main_activity");

    int parsedServerPort = 0;

    try {
        String port = args.getServerPort();
        if (port != null && !port.isEmpty()) {
            parsedServerPort = Integer.parseInt(port);
        }
    } catch (NumberFormatException ex) {
        SelendroidLogger
                .error("Unable to parse the value of server_port key, defaulting to " + this.serverPort);
        parsedServerPort = this.serverPort;
    }

    if (isValidPort(parsedServerPort)) {
        this.serverPort = parsedServerPort;
    }

    SelendroidLogger.info("Instrumentation initialized with main activity: " + mainActivityName);
    instance = this;

    final Context context = getTargetContext();
    if (args.isLoadExtensions()) {
        extensionLoader = new ExtensionLoader(context, ExternalStorage.getExtensionDex().getAbsolutePath());
        String bootstrapClassNames = args.getBootstrapClassNames();
        if (bootstrapClassNames != null) {
            extensionLoader.runBeforeApplicationCreateBootstrap(instance, bootstrapClassNames.split(","));
        }
    } else {
        extensionLoader = new ExtensionLoader(context);
    }

    // Queue bootstrapping and starting of the main activity on the main thread.
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            UncaughtExceptionHandling.clearCrashLogFile();
            UncaughtExceptionHandling.setGlobalExceptionHandler();

            if (args.isLoadExtensions() && args.getBootstrapClassNames() != null) {
                extensionLoader.runAfterApplicationCreateBootstrap(instance,
                        args.getBootstrapClassNames().split(","));
            }

            startMainActivity();
            try {
                startServer();
            } catch (Exception e) {
                SelendroidLogger.error("Failed to start selendroid server", e);
            }
        }
    });
}

From source file:github.popeen.dsub.util.Notifications.java

public static void showDownloadingNotification(final Context context, final DownloadService downloadService,
        Handler handler, DownloadFile file, int size) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        getDownloadingNotificationChannel(context);
    }/*  ww w.jav a2s.  co  m*/

    Intent cancelIntent = new Intent(context, DownloadService.class);
    cancelIntent.setAction(DownloadService.CANCEL_DOWNLOADS);
    PendingIntent cancelPI = PendingIntent.getService(context, 0, cancelIntent, 0);

    String currentDownloading, currentSize;
    if (file != null) {
        currentDownloading = file.getSong().getTitle();
        currentSize = Util.formatLocalizedBytes(file.getEstimatedSize(), context);
    } else {
        currentDownloading = "none";
        currentSize = "0";
    }

    NotificationCompat.Builder builder;
    builder = new NotificationCompat.Builder(context).setSmallIcon(android.R.drawable.stat_sys_download)
            .setContentTitle(context.getResources().getString(R.string.download_downloading_title, size))
            .setContentText(
                    context.getResources().getString(R.string.download_downloading_summary, currentDownloading))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(context.getResources().getString(
                    R.string.download_downloading_summary_expanded, currentDownloading, currentSize)))
            .setProgress(10, 5, true).setOngoing(true).addAction(R.drawable.notification_close,
                    context.getResources().getString(R.string.common_cancel), cancelPI)
            .setChannelId("downloading-channel");

    Intent notificationIntent = new Intent(context, SubsonicFragmentActivity.class);
    notificationIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD_VIEW, true);

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    builder.setContentIntent(PendingIntent.getActivity(context, 2, notificationIntent, 0));

    final Notification notification = builder.build();
    downloadShowing = true;
    if (playShowing) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID_DOWNLOADING, notification);
    } else {
        downloadForeground = true;
        handler.post(new Runnable() {
            @Override
            public void run() {
                startForeground(downloadService, NOTIFICATION_ID_DOWNLOADING, notification);
            }
        });
    }

}

From source file:com.segma.trim.InAppBillingUtilities.InAppBillingHelper.java

/**
 * Asynchronous wrapper for inventory query. This will perform an inventory
 * query as described in {@link #queryInventory}, but will do so asynchronously
 * and call back the specified listener upon completion. This method is safe to
 * call from a UI thread./*  www .  j  a va 2 s  . c  o m*/
 *
 * @param querySkuDetails as in {@link #queryInventory}
 * @param moreItemSkus as in {@link #queryInventory}
 * @param moreSubsSkus as in {@link #queryInventory}
 * @param listener The listener to notify when the refresh operation completes.
 */
public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreItemSkus,
        final List<String> moreSubsSkus, final QueryInventoryFinishedListener listener)
        throws InAppBillingAsyncInProgressException {
    final Handler handler = new Handler();
    checkNotDisposed();
    checkSetupDone("queryInventory");
    flagStartAsync("refresh inventory");
    (new Thread(new Runnable() {
        public void run() {
            InAppBillingResult result = new InAppBillingResult(BILLING_RESPONSE_RESULT_OK,
                    "Inventory refresh successful.");
            Inventory inv = null;
            try {
                inv = queryInventory(querySkuDetails, moreItemSkus, moreSubsSkus);
            } catch (InAppBillingException ex) {
                result = ex.getResult();
            }

            flagEndAsync();

            final InAppBillingResult result_f = result;
            final Inventory inv_f = inv;
            if (!mDisposed && listener != null) {
                handler.post(new Runnable() {
                    public void run() {
                        listener.onQueryInventoryFinished(result_f, inv_f);
                    }
                });
            }
        }
    })).start();
}

From source file:net.tac42.subtails.util.Util.java

public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService,
        Handler handler, MusicDirectory.Entry song) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String text = song.getArtist();

    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(R.drawable.stat_notify_playing, title,
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);

    // Set the album art.
    try {/*from w ww .  ja va2  s . c o  m*/
        int size = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
        Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, song, size);
        if (bitmap == null) {
            // set default album art
            contentView.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
        } else {
            contentView.setImageViewBitmap(R.id.notification_image, bitmap);
        }
    } catch (Exception x) {
        Log.w(TAG, "Failed to get notification cover art", x);
        contentView.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    contentView.setTextViewText(R.id.notification_title, title);
    contentView.setTextViewText(R.id.notification_artist, text);

    Pair<Integer, Integer> colors = getNotificationTextColors(context);
    if (colors.getFirst() != null) {
        contentView.setTextColor(R.id.notification_title, colors.getFirst());
    }
    if (colors.getSecond() != null) {
        contentView.setTextColor(R.id.notification_artist, colors.getSecond());
    }

    notification.contentView = contentView;

    Intent notificationIntent = new Intent(context, DownloadActivity.class);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    // Send the notification and put the service in the foreground.
    handler.post(new Runnable() {
        @Override
        public void run() {
            startForeground(downloadService, Constants.NOTIFICATION_ID_PLAYING, notification);
        }
    });

    // Update widget
    SubtailsAppWidgetProvider.getInstance().notifyChange(context, downloadService, true);
}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

@Override
public void onIceServersError(final String description) {
    // Important: need to fire the event in UI context cause currently we 're in JAIN SIP thread
    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override//from w ww.j  a  v a  2s  .co  m
        public void run() {
            handleDisconnect(null);

            if (RCDevice.state == RCDevice.DeviceState.BUSY) {
                RCDevice.state = RCDevice.DeviceState.READY;
            }

            RCConnection.this.listener.onDisconnected(RCConnection.this,
                    RCClient.ErrorCodes.ERROR_CONNECTION_WEBRTC_TURN_ERROR.ordinal(), description);
        }
    };
    mainHandler.post(myRunnable);
}

From source file:com.echopf.ECHODataObject.java

/**
 * Does Fetch data from the remote server in a background thread.
 * /*  www .  j  a va2 s. com*/
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the fetching is completed
 * @throws ECHOException 
 */
protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            ECHOException exception = null;
            JSONObject data = null;

            try {

                synchronized (lock) {
                    data = ECHOQuery.getRequest(getRequestURLPath());
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;

                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHODataObject.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;

            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:github.popeen.dsub.util.Notifications.java

public static void showPlayingNotification(final Context context, final DownloadService downloadService,
        final Handler handler, MusicDirectory.Entry song) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        getPlayingNotificationChannel(context);
    }/*w  w w .j  a v  a 2 s. c  o  m*/

    // Set the icon, scrolling text and timestamp
    final Notification notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.stat_notify_playing).setTicker(song.getTitle())
            .setWhen(System.currentTimeMillis()).setChannelId("now-playing-channel").build();

    final boolean playing = downloadService.getPlayerState() == PlayerState.STARTED;
    if (playing) {
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    }
    boolean remote = downloadService.isRemoteEnabled();
    boolean isSingle = downloadService.isCurrentPlayingSingle();
    boolean shouldFastForward = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews expandedContentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_expanded);
        setupViews(expandedContentView, context, song, true, playing, remote, isSingle, shouldFastForward);
        notification.bigContentView = expandedContentView;
        notification.priority = Notification.PRIORITY_HIGH;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification.visibility = Notification.VISIBILITY_PUBLIC;

        if (Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_HEADS_UP_NOTIFICATION, false)
                && !UpdateView.hasActiveActivity()) {
            notification.vibrate = new long[0];
        }
    }

    RemoteViews smallContentView = new RemoteViews(context.getPackageName(), R.layout.notification);
    setupViews(smallContentView, context, song, false, playing, remote, isSingle, shouldFastForward);
    notification.contentView = smallContentView;

    Intent notificationIntent = new Intent(context, SubsonicFragmentActivity.class);
    notificationIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD, true);

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    playShowing = true;
    if (downloadForeground && downloadShowing) {
        downloadForeground = false;
        handler.post(new Runnable() {
            @Override
            public void run() {
                stopForeground(downloadService, true);
                showDownloadingNotification(context, downloadService, handler,
                        downloadService.getCurrentDownloading(),
                        downloadService.getBackgroundDownloads().size());

                try {
                    startForeground(downloadService, NOTIFICATION_ID_PLAYING, notification);
                } catch (Exception e) {
                    Log.e(TAG, "Failed to start notifications after stopping foreground download");
                }
            }
        });
    } else {
        handler.post(new Runnable() {
            @Override
            public void run() {

                if (playing) {
                    try {
                        startForeground(downloadService, NOTIFICATION_ID_PLAYING, notification);
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to start notifications while playing");
                    }
                } else {
                    playShowing = false;
                    persistentPlayingShowing = true;
                    NotificationManager notificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    stopForeground(downloadService, false);

                    try {
                        notificationManager.notify(NOTIFICATION_ID_PLAYING, notification);
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to start notifications while paused");
                    }
                }
            }
        });
    }

    // Update widget
    DSubWidgetProvider.notifyInstances(context, downloadService, playing);
}

From source file:com.echopf.ECHODataObject.java

/**
 * Does Delete an object from the remote server in a background thread.
 * // ww w.j  a  v  a 2  s  .c  o  m
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the deleting in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the deleting is completed
 * @throws ECHOException 
 */
protected void doDelete(final boolean sync, final DeleteCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            JSONObject data = null;
            ECHOException exception = null;
            try {

                synchronized (lock) {
                    data = ECHOQuery.deleteRequest(getRequestURLPath());

                    refid = null;
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;

                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHODataObject.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;

            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:org.cryptsecure.Communicator.java

/**
 * Update sent received read async.//from w  w  w  . j ava  2s  .  c om
 * 
 * @param context
 *            the context
 * @param mid
 *            the mid
 * @param hostUid
 *            the host uid
 * @param sent
 *            the sent
 * @param received
 *            the received
 * @param read
 *            the read
 * @param revoked
 *            the revoked
 */
public static void updateSentReceivedReadAsync(final Context context, final int mid, final int hostUid,
        final boolean sent, final boolean received, final boolean read, final boolean revoked,
        final boolean decryptionfailed) {
    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    Log.d("communicator",
                            " GROUP updateSentReceivedReadAsync() #1 " + Conversation.getHostUid() + " == "
                                    + hostUid + ", mid=" + mid + ", sent=" + sent + ", received=" + received
                                    + ", read=" + read);
                    if (Conversation.isAlive() && (Conversation.getHostUid() == hostUid || hostUid == -1)) {
                        Log.d("communicator", " GROUP updateSentReceivedReadAsync() #2");

                        if (decryptionfailed) {
                            Conversation.setDecryptionFailed(context, mid);
                        } else if (read) {
                            Conversation.setRead(context, mid);
                        } else if (received) {
                            Conversation.setReceived(context, mid);
                        } else if (sent) {
                            Conversation.setSent(context, mid);
                        }
                    }
                    if (revoked) {
                        Log.d("communicator",
                                "REVOKE GROUP AS SENDER??? updateSentReceivedReadAsync() Conversation.getHostUid()="
                                        + Conversation.getHostUid() + ", hostUid=" + hostUid);

                        if (Conversation.getInstance() != null
                                && (Conversation.getHostUid() == hostUid || hostUid == -1)) {
                            Log.d("communicator",
                                    "REVOKE GROUP AS SENDER updateSentReceivedReadAsync() #3 mid=" + mid);
                            Conversation.setRevokedInConversation(context, mid);
                        }
                        // for precaution: clear system notifications
                        // for this user
                        if (Utility.loadBooleanSetting(context, Setup.OPTION_NOTIFICATION,
                                Setup.DEFAULT_NOTIFICATION)) {
                            Communicator.cancelNotification(context, hostUid);
                        }
                    }
                    // If message is sent, we possibly want the update the
                    // userlist if it is visible!
                    if (revoked || sent) {
                        if (Main.getInstance() != null) {
                            // in the revoked case we also want to update
                            // the first line!
                            Main.getInstance().rebuildUserlist(context, false);
                        }
                    }
                }
            }, 200);
        }
    });
}

From source file:im.vector.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs//from   w ww.j av  a2  s.c o m
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    cursor.close();
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType,
                                                fFilename);
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}