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:MainActivity.java

protected void takePicture(View view) {
    if (null == mCameraDevice) {
        return;/*from  www  . j  a  v  a  2  s.  c  o  m*/
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
        StreamConfigurationMap configurationMap = characteristics
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (configurationMap == null)
            return;
        Size largest = Collections.max(Arrays.asList(configurationMap.getOutputSizes(ImageFormat.JPEG)),
                new CompareSizesByArea());
        ImageReader reader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG,
                1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    OutputStream output = new FileOutputStream(getPictureFile());
                    output.write(bytes);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }
        };
        HandlerThread thread = new HandlerThread("CameraPicture");
        thread.start();
        final Handler backgroudHandler = new Handler(thread.getLooper());
        reader.setOnImageAvailableListener(readerListener, backgroudHandler);
        final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                    TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(MainActivity.this, "Picture Saved", Toast.LENGTH_SHORT).show();
                startPreview(session);
            }
        };
        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureCallback, backgroudHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {
            }
        }, backgroudHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:nl.dobots.presence.PresenceDetectionApp.java

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    // load settings from persistent storage
    _settings = Settings.getInstance();/*from  w  ww  .  j a v a 2s.  c om*/
    _settings.readPersistentStorage(getApplicationContext());

    _settings.readPersistentLocations(getApplicationContext());

    // get localization algo
    _localization = new SimpleLocalization(_settings.getLocationsList(), _settings.getDetectionDistance());

    // get ask wrapper (wraps login and presence functions)
    _ask = AskWrapper.getInstance();

    _notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // watchdog handler checks for non-presence and handles manual override
    HandlerThread watchdogThread = new HandlerThread("Watchdog");
    watchdogThread.start();
    _watchdogHandler = new Handler(watchdogThread.getLooper());
    _watchdogHandler.postDelayed(_watchdogRunner, Config.WATCHDOG_INTERVAL);

    // network handler used for network operations (login, updatePresence, etc.)
    HandlerThread networkThread = new HandlerThread("NetworkHandler");
    networkThread.start();
    _networkHandler = new Handler(networkThread.getLooper());

    // filter for connectivity broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(_receiver, filter);

    //      Intent startServiceIntent = new Intent(this, BleScanService.class);
    //      this.startService(startServiceIntent);

    Intent intent = new Intent(this, BleScanService.class);
    bindService(intent, _connection, Context.BIND_AUTO_CREATE);

    // set expiration time for RSSI measurements. keeps measurements of 5 scan intervals
    // before throwing them out. i.e. averages over all measurements received in the last 5
    // scan intervals
    BleDevice.setExpirationTime(5 * (Config.LOW_SCAN_PAUSE + Config.LOW_SCAN_INTERVAL));

}

From source file:com.bitants.wally.fragments.LatestFragment.java

private void setupHandlers() {
    HandlerThread handlerThread = new HandlerThread("Toplist.background");
    handlerThread.start();//from  ww w  . j  a  v  a  2 s  .com
    backgroundHandler = new Handler(handlerThread.getLooper(), this);
    uiHandler = new Handler(getActivity().getMainLooper(), this);
}

From source file:com.example.android.downloadablefonts.MainActivity.java

private Handler getHandlerThreadHandler() {
    if (mHandler == null) {
        HandlerThread handlerThread = new HandlerThread("fonts");
        handlerThread.start();/*from  w ww  .  j  ava  2 s .c o  m*/
        mHandler = new Handler(handlerThread.getLooper());
    }
    return mHandler;
}

From source file:com.nbplus.iotlib.IoTInterface.java

private IoTInterface() {
    handlerThread = new HandlerThread("IPChandlerThread");
    handlerThread.start();/*from www.ja v a 2 s  . c  o  m*/
    mHandler = new IoTInterfaceHandler(handlerThread);
    mClientMessenger = new Messenger(mHandler);
}

From source file:com.android.camera2.its.ItsService.java

@Override
public void onCreate() {
    try {/* w ww . j ava 2 s. c o  m*/
        mThreadExitFlag = false;

        // Get handle to camera manager.
        mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
        if (mCameraManager == null) {
            throw new ItsException("Failed to connect to camera manager");
        }
        mBlockingCameraManager = new BlockingCameraManager(mCameraManager);
        mCameraListener = new BlockingStateCallback();

        // Register for motion events.
        mEvents = new LinkedList<MySensorEvent>();
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        mSensorManager.registerListener(this, mAccelSensor, SensorManager.SENSOR_DELAY_FASTEST);
        mSensorManager.registerListener(this, mMagSensor, SensorManager.SENSOR_DELAY_FASTEST);
        mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_FASTEST);

        // Get a handle to the system vibrator.
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        // Create threads to receive images and save them.
        for (int i = 0; i < MAX_NUM_OUTPUT_SURFACES; i++) {
            mSaveThreads[i] = new HandlerThread("SaveThread" + i);
            mSaveThreads[i].start();
            mSaveHandlers[i] = new Handler(mSaveThreads[i].getLooper());
        }

        // Create a thread to handle object serialization.
        (new Thread(new SerializerRunnable())).start();
        ;

        // Create a thread to receive capture results and process them.
        mResultThread = new HandlerThread("ResultThread");
        mResultThread.start();
        mResultHandler = new Handler(mResultThread.getLooper());

        // Create a thread for the camera device.
        mCameraThread = new HandlerThread("ItsCameraThread");
        mCameraThread.start();
        mCameraHandler = new Handler(mCameraThread.getLooper());

        // Create a thread to process commands, listening on a TCP socket.
        mSocketRunnableObj = new SocketRunnable();
        (new Thread(mSocketRunnableObj)).start();
    } catch (ItsException e) {
        Logt.e(TAG, "Service failed to start: ", e);
    }
}

From source file:mobisocial.musubi.service.AppUpdaterService.java

@Override
public void onCreate() {
    mDatabaseSource = App.getDatabaseSource(this);
    mThread = new HandlerThread("AppManifests");
    mThread.setPriority(Thread.MIN_PRIORITY);
    mThread.start();/*from www. j a  v  a 2 s  .c o m*/
    mAppManager = new AppManager(mDatabaseSource);
    mUpdateHandler = new Handler(mThread.getLooper());
    ContentResolver resolver = getContentResolver();
    resolver.registerContentObserver(MusubiService.UPDATE_APP_MANIFESTS, false, new UpdateApps(mUpdateHandler));

    //kick it off once per boot
    resolver.notifyChange(MusubiService.UPDATE_APP_MANIFESTS, null);
    Log.w(TAG, "service is now running");
}

From source file:com.bitants.wally.fragments.RandomImagesFragment.java

private void setupHandlers() {
    HandlerThread handlerThread = new HandlerThread("RandomImages.background");
    handlerThread.start();/*from www.j  a  va  2  s  .c  o m*/
    backgroundHandler = new Handler(handlerThread.getLooper(), this);
    uiHandler = new Handler(getActivity().getMainLooper(), this);
}

From source file:eu.chainfire.opendelta.UpdateService.java

@SuppressWarnings("deprecation")
@Override//from  w w  w . j  av a  2s .c  om
public void onCreate() {
    super.onCreate();

    config = Config.getInstance(this);

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

    handlerThread = new HandlerThread("OpenDelta 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:zuo.biao.library.base.BaseFragmentActivity.java

/**?
 * @param threadName//from  www  .  j av  a  2s.  c om
 * @param runnable
 * @return
 */
public Handler runThread(String threadName, Runnable runnable) {
    if (runnable == null) {
        Log.e(TAG, "runThread  runnable == null >> return");
        return null;
    }
    HandlerThread handlerThread = new HandlerThread("" + threadName);
    handlerThread.start();//HandlerThread?
    Handler handler = new Handler(handlerThread.getLooper());//HandlerThreadlooperHandler
    handler.post(runnable);//postHandler

    handlerList.add(handler);
    runnableList.add(runnable);

    return handler;
}