Example usage for android.os HandlerThread HandlerThread

List of usage examples for android.os HandlerThread HandlerThread

Introduction

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

Prototype

public HandlerThread(String name) 

Source Link

Usage

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Starts a background thread and its {@link Handler}.
 *//*from w w  w  .  j ava2s . c  om*/
private void startBackgroundThread() {
    mBackgroundThread = new HandlerThread("CameraBackground");
    mBackgroundThread.start();
    synchronized (mCameraStateLock) {
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

private void initMediaSession() {
    ComponentName componentName = new ComponentName(this, MediaButtonReceiver.class);
    mMediaSession = new MediaSessionCompat(getApplicationContext(), "Tomahawk", componentName, null);
    mMediaSession.setFlags(//from   w  ww .j  a  va  2 s. c  om
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    Intent intent = new Intent(PlaybackService.this, TomahawkMainActivity.class);
    intent.setAction(TomahawkMainActivity.SHOW_PLAYBACKFRAGMENT_ON_STARTUP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(PlaybackService.this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mMediaSession.setSessionActivity(pendingIntent);
    HandlerThread thread = new HandlerThread("playbackservice_callback");
    thread.start();
    mCallbackHandler = new Handler(thread.getLooper());
    mMediaSession.setCallback(mMediaSessionCallback, mCallbackHandler);
    mMediaSession.setRatingType(RatingCompat.RATING_HEART);
    Bundle extras = new Bundle();
    extras.putString(EXTRAS_KEY_PLAYBACKMANAGER, mPlaybackManager.getId());
    mMediaSession.setExtras(extras);
    updateMediaPlayState();
    setSessionToken(mMediaSession.getSessionToken());
}

From source file:com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.java

/**
 * Schedule an auto-reconnect attempt using backoff logic.
 *
 * @return true if attempt was scheduled, false otherwise.
 *///from   w  w w .j av a  2s. c om
private boolean scheduleReconnect() {
    LOGGER.info("schedule Reconnect attempt " + autoReconnectsAttempted + " of " + maxAutoReconnectAttempts
            + " in " + currentReconnectRetryTime + " seconds.");
    // schedule a reconnect if unlimited or if we haven't yet hit the limit

    if (maxAutoReconnectAttempts == -1 || autoReconnectsAttempted < maxAutoReconnectAttempts) {
        //Start a separate thread to do reconnect, because connection must not occur on the main thread.
        final HandlerThread ht = new HandlerThread("Reconnect thread");
        ht.start();
        Looper looper = ht.getLooper();
        Handler handler = new Handler(looper);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LOGGER.debug("TID: " + ht.getThreadId() + " trying to reconnect to session");
                if (mqttClient != null && !mqttClient.isConnected()) {
                    reconnectToSession();
                }
            }
        }, MILLIS_IN_ONE_SECOND * currentReconnectRetryTime);
        currentReconnectRetryTime = Math.min(currentReconnectRetryTime * 2, maxReconnectRetryTime);
        return true;
    } else {
        LOGGER.warn("schedule reconnect returns false");
        return false;
    }
}

From source file:eu.fistar.sdcs.pa.PAManagerService.java

/**
 * Discover all the DA available on the system
 *///from w w  w .ja v a  2 s  .c  o m
private void discoverDAs() {
    Log.i(PAAndroidConstants.PA_LOGTAG, "Starting Device Adapter discovery");

    // Create the Intent to broadcast
    Intent intent = new Intent(DA_DISCOVERY.REQUEST_ACTION);
    intent.putExtra(DA_DISCOVERY.BUNDLE_REPACT, DA_DISCOVERY.REPLY_ACTION);

    // Create the Intent Filter to receive broadcast replies
    IntentFilter filter = new IntentFilter();
    filter.addAction(DA_DISCOVERY.REPLY_ACTION);

    // Register the Broadcast Receiver for replies and set it to run in another thread
    HandlerThread ht = new HandlerThread("ht");
    ht.start();
    registerReceiver(broadcastDiscoveryDA, filter, null, new Handler(ht.getLooper()));

    // Send in broadcast the Intent for discovery
    sendBroadcast(intent);

    // Create a new Thread object to stop the discovery and also use it as a lock
    ScanningStopAndLock r = new ScanningStopAndLock();

    // Set the timeout for receiving replies
    r.start();

    // Wait for the scanning to be done before returning
    synchronized (r) {
        while (!r.isDiscoveryDone()) {
            try {
                r.wait();
            } catch (InterruptedException e) {
                // Just wait until scanning is done
            }
        }
    }

}

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

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs//from  w w  w  .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();
}

From source file:org.matrix.console.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs/*w w  w. j  a v a 2s .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 {
                                    if (null != cursor) {
                                        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() {
                                        if ((null != fMimeType) && fMimeType.startsWith("video/")) {
                                            mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null,
                                                    fMimeType);
                                        } else {
                                            mConsoleMessageListFragment.uploadFileContent(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();
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

public void initialize(ConfigurationProvider cfgProvider, MainService mainService) {
    T.UI();// ww w . java 2  s .c  om
    mCfgProvider = cfgProvider;
    mMainService = mainService;
    mContext = mainService;

    List<BrandedItem> copy = new ArrayList<BrandingMgr.BrandedItem>();
    Collections.copy(mQueue, copy);
    for (BrandedItem item : copy)
        if (item.status != BrandedItem.STATUS_TODO)
            dequeue(item, false);

    mDownloaderThread = new HandlerThread("rogerthat_branding_worker");
    mDownloaderThread.start();
    Looper looper = mDownloaderThread.getLooper();
    mDownloaderHandler = new Handler(looper);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    mContext.registerReceiver(mBroadcastReceiver, filter);
    initStorageSettings();

    mInitialized = true;

    mMainService.postOnBIZZHandler(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            if (mMainService.getPluginDBUpdates(BrandingMgr.class).contains(MUST_DELETE_ATTACHMENTS_INTENT)) {
                synchronized (mLock) {
                    IOUtils.deleteRecursive(getAttachmentsRootDirectory());
                }
                mMainService.clearPluginDBUpdate(BrandingMgr.class, MUST_DELETE_ATTACHMENTS_INTENT);
            }
        }
    });
}

From source file:com.android.server.MountService.java

/**
 * Constructs a new MountService instance
 *
 * @param context  Binder context for this service
 *//*from w  w  w. ja v  a  2  s  .co m*/
public MountService(Context context) {
    sSelf = this;

    mContext = context;

    synchronized (mVolumesLock) {
        readStorageListLocked();
    }

    // XXX: This will go away soon in favor of IMountServiceObserver
    mPms = (PackageManagerService) ServiceManager.getService("package");

    HandlerThread hthread = new HandlerThread(TAG);
    hthread.start();
    mHandler = new MountServiceHandler(hthread.getLooper());

    // Watch for user changes
    final IntentFilter userFilter = new IntentFilter();
    userFilter.addAction(Intent.ACTION_USER_ADDED);
    userFilter.addAction(Intent.ACTION_USER_REMOVED);
    mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);

    // Watch for USB changes on primary volume
    final StorageVolume primary = getPrimaryPhysicalVolume();
    if (primary != null && primary.allowMassStorage()) {
        mContext.registerReceiver(mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
    }

    // Add OBB Action Handler to MountService thread.
    mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());

    // Initialize the last-fstrim tracking if necessary
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
    if (!mLastMaintenanceFile.exists()) {
        // Not setting mLastMaintenance here means that we will force an
        // fstrim during reboot following the OTA that installs this code.
        try {
            (new FileOutputStream(mLastMaintenanceFile)).close();
        } catch (IOException e) {
            Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
        }
    } else {
        mLastMaintenance = mLastMaintenanceFile.lastModified();
    }

    /*
     * Create the connection to vold with a maximum queue of twice the
     * amount of containers we'd ever expect to have. This keeps an
     * "asec list" from blocking a thread repeatedly.
     */
    mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25, null);

    Thread thread = new Thread(mConnector, VOLD_TAG);
    thread.start();

    // Add ourself to the Watchdog monitors if enabled.
    if (WATCHDOG_ENABLE) {
        Watchdog.getInstance().addMonitor(this);
    }
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();//from  ww w  . j  av  a 2  s  . c  o m
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command");
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log");
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats");
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for interactive state changes
    last_interactive = Util.isInteractive(this);
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    ifInteractive.addAction(ACTION_SCREEN_OFF_DELAYED);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:com.csipsimple.service.SipService.java

private static Looper createLooper() {
    //   synchronized (executorThread) {
    if (executorThread == null) {
        Log.d(THIS_FILE, "Creating new handler thread");
        // ADT gives a fake warning due to bad parse rule.
        executorThread = new HandlerThread("SipService.Executor");
        executorThread.start();//  w ww  . ja  v  a2 s  . c  o  m
    }
    //   }
    return executorThread.getLooper();
}