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, int priority) 

Source Link

Document

Constructs a HandlerThread.

Usage

From source file:im.neon.util.VectorUtils.java

/**
 * Set the user avatar in an imageView.// w w w . ja  va  2s  . c  om
 *
 * @param context     the context
 * @param session     the session
 * @param imageView   the image view
 * @param avatarUrl   the avatar url
 * @param userId      the user id
 * @param displayName the user display name
 */
public static void loadUserAvatar(final Context context, final MXSession session, final ImageView imageView,
        final String avatarUrl, final String userId, final String displayName) {
    // sanity check
    if ((null == session) || (null == imageView) || !session.isAlive()) {
        return;
    }

    // reset the imageView tag
    imageView.setTag(null);

    if (session.getMediasCache().isAvatarThumbnailCached(avatarUrl,
            context.getResources().getDimensionPixelSize(R.dimen.profile_avatar_size))) {
        session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(), imageView, avatarUrl,
                context.getResources().getDimensionPixelSize(R.dimen.profile_avatar_size));
    } else {
        if (null == mImagesThread) {
            mImagesThread = new HandlerThread("ImagesThread", Thread.MIN_PRIORITY);
            mImagesThread.start();
            mImagesThreadHandler = new android.os.Handler(mImagesThread.getLooper());
            mUIHandler = new Handler(Looper.getMainLooper());
        }

        final Bitmap bitmap = VectorUtils.getAvatar(imageView.getContext(), VectorUtils.getAvatarColor(userId),
                TextUtils.isEmpty(displayName) ? userId : displayName, false);

        // test if the default avatar has been computed
        if (null != bitmap) {
            imageView.setImageBitmap(bitmap);

            final String tag = avatarUrl + userId + displayName;
            imageView.setTag(tag);

            if (!MXMediasCache.isMediaUrlUnreachable(avatarUrl)) {
                mImagesThreadHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.equals(tag, (String) imageView.getTag())) {
                            session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(),
                                    imageView, avatarUrl,
                                    context.getResources().getDimensionPixelSize(R.dimen.profile_avatar_size),
                                    bitmap);
                        }
                    }
                });
            }
        } else {
            final String tmpTag0 = "00" + avatarUrl + "-" + userId + "--" + displayName;
            imageView.setTag(tmpTag0);

            // create the default avatar in the background thread
            mImagesThreadHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (TextUtils.equals(tmpTag0, (String) imageView.getTag())) {
                        imageView.setTag(null);
                        setDefaultMemberAvatar(imageView, userId, displayName);

                        if (!MXMediasCache.isMediaUrlUnreachable(avatarUrl)) {
                            final String tmpTag1 = "11" + avatarUrl + "-" + userId + "--" + displayName;
                            imageView.setTag(tmpTag1);

                            // wait that it is rendered to load the right one
                            mUIHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // test if the imageView tag has not been updated
                                    if (TextUtils.equals(tmpTag1, (String) imageView.getTag())) {
                                        final String tmptag2 = "22" + avatarUrl + userId + displayName;
                                        imageView.setTag(tmptag2);

                                        mImagesThreadHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                // test if the imageView tag has not been updated
                                                if (TextUtils.equals(tmptag2, (String) imageView.getTag())) {
                                                    final Bitmap bitmap = VectorUtils.getAvatar(
                                                            imageView.getContext(),
                                                            VectorUtils.getAvatarColor(userId),
                                                            TextUtils.isEmpty(displayName) ? userId
                                                                    : displayName,
                                                            false);
                                                    session.getMediasCache().loadAvatarThumbnail(
                                                            session.getHomeserverConfig(), imageView, avatarUrl,
                                                            context.getResources().getDimensionPixelSize(
                                                                    R.dimen.profile_avatar_size),
                                                            bitmap);
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }
    }
}

From source file:com.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * {@inheritDoc}//from   w  ww. j  a v  a  2s. c  o  m
 */
@Override
public void onCreate() {
    if (D)
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Initialize the favorites and recents databases
    mRecentsCache = RecentStore.getInstance(this);

    // gets the song play count cache
    mSongPlayCountCache = SongPlayCount.getInstance(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);

    // Initialize the image fetcher
    mImageFetcher = ImageFetcher.getInstance(this);
    // Initialize the image cache
    mImageFetcher.setImageCache(ImageCache.getInstance(this));

    // Start up the thread running the service. Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block. We also make it
    // background priority so CPU-intensive work will not disrupt the UI.
    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    // Initialize the audio manager and register any headset controls for
    // playback
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    // Use the remote control APIs to set the playback state
    setUpMediaSession();

    // Initialize the preferences
    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Get events when MediaStore content changes
    mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);

    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    // Listen for the idle state
    scheduleDelayedShutdown();

    // Bring the queue back
    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

private void createIdleHandler() {
    HandlerThread thread = new HandlerThread("IdleThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();//  w  ww.  ja v a  2s  . co  m
    int refCount = Kontalk.get(this).getReferenceCounter();
    mIdleHandler = new IdleConnectionHandler(this, refCount, thread.getLooper());
}

From source file:org.anhonesteffort.flock.MigrationService.java

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("MigrationService", HandlerThread.NORM_PRIORITY);
    thread.start();/* w  w w.  ja v  a  2s.  com*/

    Looper serviceLooper = thread.getLooper();

    serviceHandler = new ServiceHandler(serviceLooper);
    notifyManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
    notificationBuilder = new NotificationCompat.Builder(getBaseContext());

    try {

        Optional<DavAccount> account = DavAccountHelper.getAccount(getBaseContext());
        Optional<MasterCipher> masterCipher = KeyHelper.getMasterCipher(getBaseContext());

        if (account.isPresent() && masterCipher.isPresent()) {
            this.account = account.get();
            this.masterCipher = masterCipher.get();
        } else
            Log.e(TAG, "ACCOUNT NOT PRESENT xxx 0.O");

    } catch (IOException e) {
        Log.e(TAG, "exception while getting MasterCipher >> " + e);
    }
}

From source file:com.android.calendar.alerts.AlertService.java

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("AlertService", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*from  w  ww .  ja v  a2s . co  m*/

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // Flushes old fired alerts from internal storage, if needed.
    AlertUtils.flushOldAlertsFromInternalStorage(getApplication());
}

From source file:com.dzt.musicplay.player.AudioService.java

private void StartLoadFileThread() {
    loadMp3Thread = new HandlerThread("load_mp3_file_thread", Process.THREAD_PRIORITY_FOREGROUND);
    loadMp3Thread.start();//  w  w  w .  j a  v a  2 s  . c om
    mPlayFileHandler = new LoadFileHandler(loadMp3Thread.getLooper());
}

From source file:android_network.hetnet.vpn_service.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   w w w .  ja v a  2 s . c om*/
    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",
            Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log",
            Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats",
            Process.THREAD_PRIORITY_BACKGROUND);
    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 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);
        registeredPowerSave = true;
    }

    // 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);
        registeredUser = true;
    }

    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);
        registeredIdleState = true;
    }

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

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

    // 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:eu.faircode.netguard.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();//w  ww .ja v  a2s. 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",
            Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log",
            Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats",
            Process.THREAD_PRIORITY_BACKGROUND);
    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 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);
        registeredPowerSave = true;
    }

    // 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);
        registeredUser = true;
    }

    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);
        registeredIdleState = true;
    }

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

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

    // 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);
}