Java Code Examples for android.os.HandlerThread#start()

The following examples show how to use android.os.HandlerThread#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UgiRenderer.java    From UltraGpuImage with MIT License 6 votes vote down vote up
public UgiRenderer(String name, EGLContext sharedContext, int[] configAttributes) {
    mName = name;
    mTransformation = new UgiTransformation(480, 640, 480, 640);
    mNativeHandle = nativeCreate(mTransformation.mNativeHandle);

    logInfo("new UgiRenderer, handle " + mNativeHandle);

    HandlerThread renderThread = new HandlerThread("UgiRenderer-" + name);
    renderThread.start();
    mRenderHandler = new Handler(renderThread.getLooper());

    // Create EGL context on the newly created render thread. It should be possibly to create
    // the context on this thread and make it current on the render thread, but this causes
    // failure on some Marvel based JB devices.
    // https://bugs.chromium.org/p/webrtc/issues/detail?id=6350.
    ThreadUtils.invokeAtFrontUninterruptibly(mRenderHandler,
            () -> mEglBase = EglBase.create(
                    sharedContext == null ? null : new EglBase14.Context(sharedContext),
                    configAttributes));
    logInfo("new UgiRenderer success");
}
 
Example 2
Source File: ScrollingToBottomActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
private void fetchData() {
  final HandlerThread thread = new HandlerThread("bg");
  thread.start();

  final Handler handler = new Handler(thread.getLooper());
  handler.postDelayed(
      new Runnable() {
        @Override
        public void run() {
          mLithoView.setComponent(
              DelayedLoadingComponent.create(mComponentContext)
                  .headerDataModels(getData(0, 15))
                  .feedDataModels(mFeedData)
                  .build());
        }
      },
      4000);
}
 
Example 3
Source File: SmsCodeHandleService.java    From SmsCode with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    HandlerThread workerThread = new HandlerThread(SERVICE_NAME);
    workerThread.start();

    uiHandler = new WorkerHandler(Looper.getMainLooper());
    workerHandler = new WorkerHandler(workerThread.getLooper());

    mPreQuitQueueCount = new AtomicInteger(DEFAULT_QUIT_COUNT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Show a notification for the foreground service.
        Notification notification = new NotificationCompat.Builder(this, NotificationConst.CHANNEL_ID_FOREGROUND_SERVICE)
                .setSmallIcon(R.drawable.ic_app_icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_icon))
                .setWhen(System.currentTimeMillis())
                .setContentText(getString(R.string.foreground_notification_title))
                .setAutoCancel(true)
                .setColor(getColor(R.color.ic_launcher_background))
                .build();
        startForeground(NotificationConst.NOTIFICATION_ID_FOREGROUND_SVC, notification);
    }
}
 
Example 4
Source File: AndroidCamera2AgentImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
AndroidCamera2AgentImpl(Context context) {
    mCameraHandlerThread = new HandlerThread("Camera2 Handler Thread");
    mCameraHandlerThread.start();
    mCameraHandler = new Camera2Handler(mCameraHandlerThread.getLooper());
    mExceptionHandler = new CameraExceptionHandler(mCameraHandler);
    mCameraState = new AndroidCamera2StateHolder();
    mDispatchThread = new DispatchThread(mCameraHandler, mCameraHandlerThread);
    mDispatchThread.start();
    mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    mNoisemaker = new MediaActionSound();
    mNoisemaker.load(MediaActionSound.SHUTTER_CLICK);

    mNumCameraDevices = 0;
    mCameraDevices = new ArrayList<String>();
    updateCameraDevices();
}
 
Example 5
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
<T extends RealmModel> void startListening(@Nullable final LiveResults<T> liveResults) {
    // build Realm instance
    if(refCount.getAndIncrement() == 0) {
        synchronized(LOCK) {
            HandlerThread handlerThread = new HandlerThread("MONARCHY_REALM-#" + hashCode());
            handlerThread.start();
            Handler handler = new Handler(handlerThread.getLooper());
            this.handlerThread.set(handlerThread);
            this.handler.set(handler);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Realm realm = Realm.getInstance(getRealmConfiguration());
                    if(realmThreadLocal.get() == null) {
                        realmThreadLocal.set(realm);
                    }
                }
            });
        }
    }

    // build Realm query
    handler.get().post(new Runnable() {
        @Override
        public void run() {
            createAndObserveRealmQuery(liveResults);
        }
    });
}
 
Example 6
Source File: JavaCamera2View.java    From AndroidDocumentScanner with MIT License 5 votes vote down vote up
private void startBackgroundThread() {
    Log.i(LOGTAG, "startBackgroundThread");
    stopBackgroundThread();
    mBackgroundThread = new HandlerThread("OpenCVCameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
 
Example 7
Source File: BaseCameraActivity.java    From fritz-examples with MIT License 5 votes vote down vote up
@Override
public synchronized void onResume() {
    Log.d(TAG, "onResume " + this);
    super.onResume();

    handlerThread = new HandlerThread("inference");
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper());
}
 
Example 8
Source File: QueuedWork.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Lazily create a handler on a separate thread.
 *
 * @return the handler
 */
private static Handler getHandler() {
    synchronized (sLock) {
        if (sHandler == null) {
            HandlerThread handlerThread = new HandlerThread("queued-work-looper",
                    Process.THREAD_PRIORITY_FOREGROUND);
            handlerThread.start();

            sHandler = new QueuedWorkHandler(handlerThread.getLooper());
        }
        return sHandler;
    }
}
 
Example 9
Source File: CameraProxy.java    From LiveVideoBroadcaster with Apache License 2.0 5 votes vote down vote up
public CameraProxy(int cameraId) {
    ht = new HandlerThread("Camera Proxy Thread");
    ht.start();

    _handler = new CameraHandler(ht.getLooper());
    _signal.close();
    _handler.obtainMessage(OPEN_CAMERA, cameraId, 0).sendToTarget();
    _signal.block();
    if (_camera != null) {
        _handler.obtainMessage(SET_ERROR_CALLBACK, new ErrorCallback()).sendToTarget();
    }
}
 
Example 10
Source File: Camera2Renderer.java    From faceswap with Apache License 2.0 5 votes vote down vote up
private void startBackgroundThread() {
    Log.i(LOGTAG, "startBackgroundThread");
    stopBackgroundThread();
    mBackgroundThread = new HandlerThread("CameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
 
Example 11
Source File: AndroidCellularSignalStrength.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private AndroidCellularSignalStrength() {
    // {@link android.telephony.SignalStrength#getLevel} is only available on API Level
    // {@link Build.VERSION_CODES#M} and higher.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;

    HandlerThread handlerThread = new HandlerThread("AndroidCellularSignalStrength");
    handlerThread.start();

    new Handler(handlerThread.getLooper()).post(new Runnable() {
        @Override
        public void run() {
            new CellStateListener();
        }
    });
}
 
Example 12
Source File: CameraThread.java    From GPUVideo-android with MIT License 5 votes vote down vote up
private void updatePreview() {

        requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO);

        HandlerThread thread = new HandlerThread("CameraPreview");
        thread.start();
        Handler backgroundHandler = new Handler(thread.getLooper());

        try {
            cameraCaptureSession.setRepeatingRequest(requestBuilder.build(), null, backgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
 
Example 13
Source File: AndroidWatchExecutor.java    From SimpleLeakCanary with Apache License 2.0 4 votes vote down vote up
public AndroidWatchExecutor() {
  mainHandler = new Handler(Looper.getMainLooper());
  HandlerThread handlerThread = new HandlerThread(LEAK_CANARY_THREAD_NAME);
  handlerThread.start();
  backgroundHandler = new Handler(handlerThread.getLooper());
}
 
Example 14
Source File: CameraActivity.java    From CameraDemo with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
    private void initCamera2() {
        findViewById(R.id.btn_control).setClickable(true);

        HandlerThread handlerThread = new HandlerThread("Camera2");
        handlerThread.start();
        childHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());


        mCameraID = BACK_CAMERA;//后摄像头
        Log.d(TAG, "initCamera2: "+ CameraCharacteristics.LENS_FACING_BACK);
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG,1);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { //可以在这里处理拍照得到的临时照片 例如,写入本地
            @Override
            public void onImageAvailable(ImageReader reader) {
//                mCameraDevice.close();
//                mSurfaceView.setVisibility(View.INVISIBLE);
                // 拿到拍照照片数据
                Image image = reader.acquireNextImage();
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);//由缓冲区存入字节数组
                //保存

                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                if (bitmap != null) {
                    if(mCameraID == FRONT_CAMERA){
                        //前置摄像头拍的要先旋转180度
                        bitmap = adjustPhotoRotation(bitmap,180);
                    }
                    iv_thumb.setImageBitmap(bitmap);
                    writeToFile(bitmap);
                }

                image.close();
            }
        }, mainHandler);
        //获取摄像头管理
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            //打开摄像头
            mCameraManager.openCamera(mCameraID+"", stateCallback, mainHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
 
Example 15
Source File: CameraConnectionFragment.java    From fritz-examples with MIT License 4 votes vote down vote up
/**
 * Starts a background thread and its {@link Handler}.
 */
private void startBackgroundThread() {
    backgroundThread = new HandlerThread("ImageListener");
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
}
 
Example 16
Source File: ViewPagerSampleActivity.java    From ZoomImageView with Apache License 2.0 4 votes vote down vote up
public SamplePagerAdapter() {
    // Create a background thread and a handler for it
    final HandlerThread backgroundThread = new HandlerThread("backgroundThread");
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
}
 
Example 17
Source File: CameraConnectionFragment.java    From dbclf with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a background thread and its {@link Handler}.
 */
private void startBackgroundThread() {
    backgroundThread = new HandlerThread("ImageListener");
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
}
 
Example 18
Source File: OfflineLicenseHelper.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance. Call {@link #release()} when the instance is no longer required.
 *
 * @param uuid The UUID of the drm scheme.
 * @param mediaDrmProvider A {@link ExoMediaDrm.Provider}.
 * @param callback Performs key and provisioning requests.
 * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
 *     to {@link MediaDrm#getKeyRequest}. May be null.
 * @see DefaultDrmSessionManager.Builder
 */
@SuppressWarnings("unchecked")
public OfflineLicenseHelper(
    UUID uuid,
    ExoMediaDrm.Provider<T> mediaDrmProvider,
    MediaDrmCallback callback,
    @Nullable Map<String, String> optionalKeyRequestParameters) {
  handlerThread = new HandlerThread("OfflineLicenseHelper");
  handlerThread.start();
  conditionVariable = new ConditionVariable();
  DefaultDrmSessionEventListener eventListener =
      new DefaultDrmSessionEventListener() {
        @Override
        public void onDrmKeysLoaded() {
          conditionVariable.open();
        }

        @Override
        public void onDrmSessionManagerError(Exception e) {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRestored() {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRemoved() {
          conditionVariable.open();
        }
      };
  if (optionalKeyRequestParameters == null) {
    optionalKeyRequestParameters = Collections.emptyMap();
  }
  drmSessionManager =
      (DefaultDrmSessionManager<T>)
          new DefaultDrmSessionManager.Builder()
              .setUuidAndExoMediaDrmProvider(uuid, mediaDrmProvider)
              .setKeyRequestParameters(optionalKeyRequestParameters)
              .build(callback);
  drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
 
Example 19
Source File: ThreadPool.java    From IPCInvoker with Apache License 2.0 4 votes vote down vote up
private ThreadPool() {
    HandlerThread thread = new HandlerThread("IPCInvoker-Sample#WorkerThread");
    thread.start();
    mHandler = new Handler(thread.getLooper());
}
 
Example 20
Source File: MainActivity.java    From journaldev with MIT License 2 votes vote down vote up
private ImageAnalysis setImageAnalysis() {

        // Setup image analysis pipeline that computes average pixel luminance
        HandlerThread analyzerThread = new HandlerThread("OpenCVAnalysis");
        analyzerThread.start();


        ImageAnalysisConfig imageAnalysisConfig = new ImageAnalysisConfig.Builder()
                .setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
                .setCallbackHandler(new Handler(analyzerThread.getLooper()))
                .setImageQueueDepth(1).build();

        ImageAnalysis imageAnalysis = new ImageAnalysis(imageAnalysisConfig);

        imageAnalysis.setAnalyzer(
                new ImageAnalysis.Analyzer() {
                    @Override
                    public void analyze(ImageProxy image, int rotationDegrees) {
                        //Analyzing live camera feed begins.

                        final Bitmap bitmap = textureView.getBitmap();



                        if(bitmap==null)
                            return;

                        Mat mat = new Mat();
                        Utils.bitmapToMat(bitmap, mat);


                        Imgproc.cvtColor(mat, mat, currentImageType);
                        Utils.matToBitmap(mat, bitmap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ivBitmap.setImageBitmap(bitmap);
                            }
                        });

                    }
                });


        return imageAnalysis;

    }