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.mobileglobe.android.customdialer.common.model.AccountTypeManager.java

/**
 * Internal constructor that only performs initial parsing.
 *//*w w  w.  j  av a2 s.  c  o m*/
public AccountTypeManagerImpl(Context context) {
    mContext = context;
    mFallbackAccountType = new FallbackAccountType(context);

    mAccountManager = AccountManager.get(mContext);

    mListenerThread = new HandlerThread("AccountChangeListener");
    mListenerThread.start();
    mListenerHandler = new Handler(mListenerThread.getLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_LOAD_DATA:
                loadAccountsInBackground();
                break;
            case MESSAGE_PROCESS_BROADCAST_INTENT:
                processBroadcastIntent((Intent) msg.obj);
                break;
            }
        }
    };

    mInvitableAccountTypeCache = new InvitableAccountTypeCache();

    // Request updates when packages or accounts change
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package");
    mContext.registerReceiver(mBroadcastReceiver, filter);
    IntentFilter sdFilter = new IntentFilter();
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mContext.registerReceiver(mBroadcastReceiver, sdFilter);

    // Request updates when locale is changed so that the order of each field will
    // be able to be changed on the locale change.
    filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
    mContext.registerReceiver(mBroadcastReceiver, filter);

    if (ActivityCompat.checkSelfPermission(mContext,
            Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mAccountManager.addOnAccountsUpdatedListener(this, mListenerHandler, false);

    ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, this);

    mListenerHandler.sendEmptyMessage(MESSAGE_LOAD_DATA);
}

From source file:com.horizondigital.delta.UpdateService.java

@SuppressWarnings("deprecation")
@Override/* w ww.j  ava  2  s.  c om*/
public void onCreate() {
    super.onCreate();

    Logger.setDebugLogging(getResources().getBoolean(R.bool.debug_output));

    property_version = getProperty(getString(R.string.property_version), "");
    property_device = getProperty(getString(R.string.property_device), "");
    filename_base = String.format(Locale.ENGLISH, getString(R.string.filename_base), property_version);
    path_base = String.format(Locale.ENGLISH, "%s%s%s%s",
            Environment.getExternalStorageDirectory().getAbsolutePath(), File.separator,
            getString(R.string.path_base), File.separator);
    path_flash_after_update = String.format(Locale.ENGLISH, "%s%s%s", path_base, "FlashAfterUpdate",
            File.separator);
    url_base_delta = String.format(Locale.ENGLISH, getString(R.string.url_base_delta), property_device);
    url_base_update = String.format(Locale.ENGLISH, getString(R.string.url_base_update), property_device);
    url_base_full = String.format(Locale.ENGLISH, getString(R.string.url_base_full), property_device);
    apply_signature = getResources().getBoolean(R.bool.apply_signature);

    Logger.d("property_version: %s", property_version);
    Logger.d("property_device: %s", property_device);
    Logger.d("filename_base: %s", filename_base);
    Logger.d("path_base: %s", path_base);
    Logger.d("path_flash_after_update: %s", path_flash_after_update);
    Logger.d("url_base_delta: %s", url_base_delta);
    Logger.d("url_base_update: %s", url_base_update);
    Logger.d("url_base_full: %s", url_base_full);

    config = Config.getInstance(this);

    wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
            config.getKeepScreenOn() ? PowerManager.SCREEN_DIM_WAKE_LOCK : PowerManager.PARTIAL_WAKE_LOCK,
            "CarbonDelta WakeLock");
    wifiLock = ((WifiManager) getSystemService(WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
            "CarbonDelta WifiLock");

    handlerThread = new HandlerThread("CarbonDelta Service Thread");
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper());

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    scheduler = new Scheduler(this, this);

    networkState = new NetworkState();
    networkState.start(this, this,
            prefs.getInt(PREF_AUTO_UPDATE_NETWORKS_NAME, PREF_AUTO_UPDATE_NETWORKS_DEFAULT));

    batteryState = new BatteryState();
    batteryState.start(this, this, 50, true);

    screenState = new ScreenState();
    screenState.start(this, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    autoState();
}

From source file:com.googlecode.eyesfree.brailleback.DisplayManager.java

/**
 * Creates an instance of this class and starts the internal thread to
 * connect to the braille display service.  {@code context} is used to
 * connect to the display service.  {@code translator} is used for braille
 * translation.  The various listeners will be called as appropriate and
 * on the same thread that was used to create this object.  The current
 * thread must have a prepared looper.//from w w  w  .  j  a v a  2  s .co m
 */
public DisplayManager(TranslatorManager translatorManager, Context context,
        OnPanOverflowListener panOverflowListener,
        Display.OnConnectionStateChangeListener connectionStateChangeListener,
        OnMappedInputEventListener mappedInputEventListener) {
    mTranslatorManager = translatorManager;
    mTranslatorManager.addOnTablesChangedListener(this);
    mContext = context;
    mPanOverflowListener = panOverflowListener;
    mConnectionStateChangeListener = connectionStateChangeListener;
    mMappedInputEventListener = mappedInputEventListener;
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "BrailleBack");
    mHandlerThread = new HandlerThread("DisplayManager") {
        @Override
        public void onLooperPrepared() {
            mDisplay = new OverlayDisplay(mContext, new DisplayClient(mContext));
            mDisplay.setOnConnectionStateChangeListener(DisplayManager.this);
            mDisplay.setOnInputEventListener(DisplayManager.this);
        }
    };
    mHandlerThread.start();
    mDisplayHandler = new DisplayHandler(mHandlerThread.getLooper());
    mCallbackHandler = new CallbackHandler();
}

From source file:uk.ac.horizon.artcodes.camera.CameraView.java

private void startCamera() {
    if (cameraThread == null) {
        cameraThread = new HandlerThread(THREAD_NAME);
        cameraThread.start();// ww w.ja v a2s .  c  o m
        Handler cameraHandler = new Handler(cameraThread.getLooper());
        cameraHandler.post(new Runnable() {
            @Override
            public void run() {
                createCamera();
            }
        });
    } else {
        camera.startPreview();
    }
}

From source file:com.android.camera.one.v2.OneCameraZslImpl.java

/**
 * Instantiates a new camera based on Camera 2 API.
 *
 * @param device The underlying Camera 2 device.
 * @param characteristics The device's characteristics.
 * @param pictureSize the size of the final image to be taken.
 *///from w  w  w.  j av  a2s .c  o  m
OneCameraZslImpl(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) {
    Log.v(TAG, "Creating new OneCameraZslImpl");

    mDevice = device;
    mCharacteristics = characteristics;
    mLensRange = LensRangeCalculator.getDiopterToRatioCalculator(characteristics);
    mDirection = new CameraDirectionProvider(mCharacteristics);
    mFullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics);

    mCameraThread = new HandlerThread("OneCamera2");
    // If this thread stalls, it will delay viewfinder frames.
    mCameraThread.setPriority(Thread.MAX_PRIORITY);
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    mCameraListenerThread = new HandlerThread("OneCamera2-Listener");
    mCameraListenerThread.start();
    mCameraListenerHandler = new Handler(mCameraListenerThread.getLooper());

    // TODO: Encoding on multiple cores results in preview jank due to
    // excessive GC.
    int numEncodingCores = CameraUtil.getNumCpuCores();
    mImageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    mCaptureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, mCameraListenerHandler,
            mImageSaverThreadPool);
    mCaptureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() {
        @Override
        public void onReadyStateChange(boolean capturePossible) {
            mReadyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible);
        }
    });

    // Listen for changes to auto focus state and dispatch to
    // mFocusStateListener.
    mCaptureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE,
            new ImageCaptureManager.MetadataChangeListener() {
                @Override
                public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue,
                        CaptureResult result) {
                    FocusStateListener listener = mFocusStateListener;
                    if (listener != null) {
                        listener.onFocusStatusUpdate(AutoFocusHelper.stateFromCamera2State(
                                result.get(CaptureResult.CONTROL_AF_STATE)), result.getFrameNumber());
                    }
                }
            });

    // Allocate the image reader to store all images received from the
    // camera.
    if (pictureSize == null) {
        // TODO The default should be selected by the caller, and
        // pictureSize should never be null.
        pictureSize = getDefaultPictureSize();
    }
    mCaptureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(),
            sCaptureImageFormat, MAX_CAPTURE_IMAGES);

    mCaptureImageReader.setOnImageAvailableListener(mCaptureManager, mCameraHandler);
    mMediaActionSound.load(MediaActionSound.SHUTTER_CLICK);
}

From source file:net.zorgblub.typhon.fragment.ReadingFragment.java

/**
 * Called when the activity is first created.
 *//* w  w w  .  ja v  a 2 s  .  c o  m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Typhon.getComponent().inject(this);

    // Restore preferences
    this.uiHandler = new Handler();
    HandlerThread bgThread = new HandlerThread("background");
    bgThread.start();
    this.backgroundHandler = new Handler(bgThread.getLooper());
    dictionaryService = DictionaryServiceImpl.get();
    dictionaryLastUpdate = dictionaryService.getLastUpdateTimestamp();
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

/** Called when the activity is first created. */
@Override/*w ww  .  j ava  2s .  co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Restore preferences
    this.uiHandler = new Handler();
    HandlerThread bgThread = new HandlerThread("background");
    bgThread.start();
    this.backgroundHandler = new Handler(bgThread.getLooper());

}

From source file:ch.ethz.coss.nervousnet.vm.sensors.ConnectivitySensor.java

private ConnectivitySensor(Context context) {
    this.context = context;

    hthread = new HandlerThread("HandlerThread");
    hthread.start();
}

From source file:com.android.providers.downloads.DownloadService.java

/**
 * Enqueue an {@link #updateLocked()} pass to occur in future.
 *//*from  w  w w  .  j a  va  2s. co  m*/
private void enqueueUpdate() {
    synchronized (this) {
        if (mUpdateThread == null) {
            mUpdateThread = new HandlerThread(Constants.TAG + "-UpdateThread");
            mUpdateThread.start();
            mUpdateHandler = new Handler(mUpdateThread.getLooper(), mUpdateCallback);
        }
        mUpdateHandler.removeMessages(MSG_UPDATE);
        mUpdateHandler.obtainMessage(MSG_UPDATE, mLastStartId, -1).sendToTarget();
    }
}

From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java

public void startBackgroundThread() {
    backgroundThread = new HandlerThread("Camera Background");
    backgroundThread.start();
}