android.os.HandlerThread Java Examples

The following examples show how to use android.os.HandlerThread. 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: PDFView.java    From AndroidPdfViewerV2 with Apache License 2.0 7 votes vote down vote up
/**
 * Construct the initial view
 */
public PDFView(Context context, AttributeSet set) {
    super(context, set);

    renderingHandlerThread = new HandlerThread("PDF renderer");

    if (isInEditMode()) {
        return;
    }

    cacheManager = new CacheManager();
    animationManager = new AnimationManager(this);
    dragPinchManager = new DragPinchManager(this, animationManager);

    paint = new Paint();
    debugPaint = new Paint();
    debugPaint.setStyle(Style.STROKE);

    pdfiumCore = new PdfiumCore(context);
    setWillNotDraw(false);
}
 
Example #2
Source File: AndroidImmediateDispatcher.java    From actor-platform with GNU Affero General Public License v3.0 7 votes vote down vote up
public AndroidImmediateDispatcher(String name, ThreadPriority priority) {

        handlerThread = new HandlerThread(name);
        switch (priority) {
            case HIGH:
                handlerThread.setPriority(Thread.MAX_PRIORITY);
            case LOW:
                handlerThread.setPriority(Thread.MIN_PRIORITY);
            default:
            case NORMAL:
                handlerThread.setPriority(Thread.NORM_PRIORITY);
        }
        handlerThread.start();

        // Wait for Looper ready
        while (handlerThread.getLooper() == null) {

        }

        handler = new Handler(handlerThread.getLooper());
    }
 
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: RtspClient.java    From VideoMeeting with Apache License 2.0 6 votes vote down vote up
public RtspClient() {
        mCSeq = 0;
        mTmpParameters = new Parameters();
        mTmpParameters.port = 1935;
        mTmpParameters.path = "/";
//        mAuthorization = null;
        mCallback = null;
        mMainHandler = new Handler(Looper.getMainLooper());
        mState = STATE_STOPPED;

        final Semaphore signal = new Semaphore(0);
        // 异步线程的Handler
        new HandlerThread("com.jb.streaming.RtspClient"){
            @Override
            protected void onLooperPrepared() {
                mAsyncHandler = new Handler();
                signal.release();
            }
        }.start();
        signal.acquireUninterruptibly();
    }
 
Example #5
Source File: ExplorerActivity.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initializes an interactive shell, which will stay throughout the app lifecycle
 * The shell is associated with a handler thread which maintain the message queue from the
 * callbacks of shell as we certainly cannot allow the callbacks to run on same thread because
 * of possible deadlock situation and the asynchronous behaviour of LibSuperSU
 */
private void initializeInteractiveShell() {
    // only one looper can be associated to a thread. So we're making sure not to create new
    // handler threads every time the code relaunch.
    if (rootMode) {
        handlerThread = new HandlerThread("handler");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
        shellInteractive = (new Shell.Builder()).useSU().setHandler(handler).open();

        // TODO: check for busybox
        /*try {
if (!RootUtils.isBusyboxAvailable()) {
Toast.makeText(this, getString(R.string.error_busybox), Toast.LENGTH_LONG).show();
closeInteractiveShell();
sharedPref.edit().putBoolean(PreferenceUtils.KEY_ROOT, false).apply();
}
} catch (RootNotPermittedException e) {
e.printStackTrace();
sharedPref.edit().putBoolean(PreferenceUtils.KEY_ROOT, false).apply();
}*/
    }
}
 
Example #6
Source File: PackageInstallerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public PackageInstallerService(Context context, PackageManagerService pm) {
    mContext = context;
    mPm = pm;
    mPermissionManager = LocalServices.getService(PermissionManagerInternal.class);

    mInstallThread = new HandlerThread(TAG);
    mInstallThread.start();

    mInstallHandler = new Handler(mInstallThread.getLooper());

    mCallbacks = new Callbacks(mInstallThread.getLooper());

    mSessionsFile = new AtomicFile(
            new File(Environment.getDataSystemDirectory(), "install_sessions.xml"),
            "package-session");
    mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions");
    mSessionsDir.mkdirs();
}
 
Example #7
Source File: DelayedDiskWrite.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void write(final String filePath, final Writer w, final boolean open) {
    if (TextUtils.isEmpty(filePath)) {
        throw new IllegalArgumentException("empty file path");
    }

    /* Do a delayed write to disk on a separate handler thread */
    synchronized (this) {
        if (++mWriteSequence == 1) {
            mDiskWriteHandlerThread = new HandlerThread("DelayedDiskWriteThread");
            mDiskWriteHandlerThread.start();
            mDiskWriteHandler = new Handler(mDiskWriteHandlerThread.getLooper());
        }
    }

    mDiskWriteHandler.post(new Runnable() {
        @Override
        public void run() {
            doWrite(filePath, w, open);
        }
    });
}
 
Example #8
Source File: PropUpdatingActivity.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(
              SelectedItemRootComponent.create(mComponentContext)
                  .dataModels(mDataModels)
                  .selectedItem(1)
                  .build());
          Toast.makeText(
              mComponentContext.getAndroidContext(),
              "Updated selected item prop",
              Toast.LENGTH_SHORT);
        }
      },
      4000);
}
 
Example #9
Source File: CameraStreamer.java    From peepers with Apache License 2.0 6 votes vote down vote up
void start()
{
    synchronized (mLock)
    {
        if (mRunning)
        {
            throw new IllegalStateException("CameraStreamer is already running");
        } // if
        mRunning = true;
    } // synchronized

    final HandlerThread worker = new HandlerThread(TAG, Process.THREAD_PRIORITY_MORE_FAVORABLE);
    worker.setDaemon(true);
    worker.start();
    mLooper = worker.getLooper();
    mWorkHandler = new WorkHandler(mLooper);
    mWorkHandler.obtainMessage(MESSAGE_TRY_START_STREAMING).sendToTarget();
}
 
Example #10
Source File: SerialPortHelper.java    From Android-SerialPort with Apache License 2.0 6 votes vote down vote up
/**
 * 开启发送消息线程
 */
private void startSendThread() {
    mSendingHandlerThread = new HandlerThread("mSendingHandlerThread");
    mSendingHandlerThread.start();

    mSendingHandler = new Handler(mSendingHandlerThread.getLooper()) {
        @Override
        public void handleMessage(Message msg) {
            byte[] sendBytes = (byte[]) msg.obj;
            if (null != mFileOutputStream && null != sendBytes && sendBytes.length > 0) {
                try {
                    mFileOutputStream.write(sendBytes);
                    if (null != mISerialPortDataListener) {
                        mISerialPortDataListener.onDataSend(sendBytes);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}
 
Example #11
Source File: GosMessageHandler.java    From gokit-android with MIT License 5 votes vote down vote up
public void StartLooperWifi(Context context) {
	this.mcContext = context;
	HandlerThread looperwifi = new HandlerThread("looperwifi");
	looperwifi.start();
	looper = new MyLooperHandler(looperwifi.getLooper());
	looper.post(mRunnable);
}
 
Example #12
Source File: CameraThread.java    From Viewer with Apache License 2.0 5 votes vote down vote up
/**
 * Call from main thread.
 *
 * Enqueues a task on the camera thread.
 *
 * @param runnable the task to enqueue
 */
protected void enqueue(Runnable runnable) {
    synchronized (LOCK) {
        if (this.handler == null) {
            if (openCount <= 0) {
                throw new IllegalStateException("CameraThread is not open");
            }
            this.thread = new HandlerThread("CameraThread");
            this.thread.start();
            this.handler = new Handler(thread.getLooper());
        }
        this.handler.post(runnable);
    }
}
 
Example #13
Source File: VideoFrameReleaseTimeHelper.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
private VSyncSampler() {
  sampledVsyncTimeNs = C.TIME_UNSET;
  choreographerOwnerThread = new HandlerThread("ChoreographerOwner:Handler");
  choreographerOwnerThread.start();
  handler = Util.createHandler(choreographerOwnerThread.getLooper(), /* callback= */ this);
  handler.sendEmptyMessage(CREATE_CHOREOGRAPHER);
}
 
Example #14
Source File: WXOkHttpDispatcher.java    From incubator-weex-playground with Apache License 2.0 5 votes vote down vote up
public WXOkHttpDispatcher(Handler handler) {
  mUiHandler = handler;
  mOkHttpClient = defaultOkHttpClient();
  mDispatcherThread = new HandlerThread("dispatcherThread");
  mDispatcherThread.start();
  mDispatcherHandler = new DispatcherHandler(mDispatcherThread.getLooper(), mOkHttpClient, mUiHandler);
}
 
Example #15
Source File: MediaRecorderCustom.java    From VideoRecord with MIT License 5 votes vote down vote up
@Override
public void prepare() {
	if (!mPrepared) {
		mHandlerThread = new HandlerThread("handler_thread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
		mHandlerThread.start();

		mHandler = new YuvHandler(mHandlerThread.getLooper());
		mPrepared = true;
	}

	if (mSurfaceCreated)
		startPreview();
}
 
Example #16
Source File: Camera.java    From habpanelviewer with GNU General Public License v3.0 5 votes vote down vote up
public Camera(Activity ctx, TextureView tv, SharedPreferences prefs) {
    mContext = ctx;
    mPreviewView = tv;

    HandlerThread mWorker = new HandlerThread("CameraWorker");
    mWorker.start();
    mWorkHandler = new Handler(mWorker.getLooper());

    EventBus.getDefault().register(this);

    mCameraFallback = prefs.getBoolean(Constants.PREF_CAMERA_FALLBACK, false);

    mVersion = getCameraVersion(prefs);
    mImplementation = createCamera(mVersion);
}
 
Example #17
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 #18
Source File: CustomIntentService.java    From travelguide with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    HandlerThread localHandlerThread = new HandlerThread("IntentService["
            + this.mName + "]");
    localHandlerThread.start();
    this.mServiceLooper = localHandlerThread.getLooper();
    this.mServiceHandler = new ServiceHandler(this.mServiceLooper);
}
 
Example #19
Source File: JavaCamera2View.java    From OpenCvFaceDetect with Apache License 2.0 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 #20
Source File: CycledLeScanner.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
protected CycledLeScanner(Context context, long scanPeriod, long betweenScanPeriod, boolean backgroundFlag, CycledLeScanCallback cycledLeScanCallback, BluetoothCrashResolver crashResolver) {
    mScanPeriod = scanPeriod;
    mBetweenScanPeriod = betweenScanPeriod;
    mContext = context;
    mCycledLeScanCallback = cycledLeScanCallback;
    mBluetoothCrashResolver = crashResolver;
    mBackgroundFlag = backgroundFlag;

    mScanThread = new HandlerThread("CycledLeScannerThread");
    mScanThread.start();
    mScanHandler = new Handler(mScanThread.getLooper());
}
 
Example #21
Source File: Stats.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
Stats(Cache cache) {
  this.cache = cache;
  this.statsThread = new HandlerThread(STATS_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);
  this.statsThread.start();
  Utils.flushStackLocalLeaks(statsThread.getLooper());
  this.handler = new StatsHandler(statsThread.getLooper(), this);
}
 
Example #22
Source File: NotificationService.java    From Klyph with MIT License 5 votes vote down vote up
@Override
public void onCreate()
{
	// Why initialize device values ?
	// Because we need the density to calculate image size
	// In notification request
	KlyphDevice.initDeviceValues(this);
	
	HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND);
	thread.start();

	mServiceLooper = thread.getLooper();
	mServiceHandler = new ServiceHandler(mServiceLooper, new WeakReference<Service>(this));
}
 
Example #23
Source File: TxConcurrencyTests.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    handlerThread = new HandlerThread("Test Handler Thread");
    handlerThread.start();
    HandlerThread secondThread = new HandlerThread("Second Handler Thread");
    secondThread.start();
}
 
Example #24
Source File: EspressoRemote.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Must be called prior to using any functionality of this class.
 *
 * <p>During initialization the instance of this class will be registered with {@link
 * InstrumentationConnection}.
 */
public synchronized void init() {
  logDebugWithProcess(TAG, "init called");

  if (null == incomingHandler) {
    Log.i(TAG, "Initializing Espresso Remote of type: " + TYPE);
    RemoteInteractionRegistry.registerInstance(DEFAULT_INSTANCE);
    initRemoteRegistry();
    HandlerThread handlerThread = new HandlerThread("EspressoRemoteThread");
    handlerThread.start();
    incomingHandler = new IncomingHandler(handlerThread.getLooper());
    instrumentationConnection.registerClient(TYPE, incomingHandler.messengerHandler);
  }
}
 
Example #25
Source File: BJWebSocketClient.java    From bjnetwork with Apache License 2.0 5 votes vote down vote up
public void connect() {
    logInfo("connect() while environment is " +
            "(state="+mState+", address="+address+", " +
            "SendMsgQueueSize="+mSendMessageThread.mMessageQueue.size()+")");

    if (mState != State.Offline) return;

    if (TextUtils.isEmpty(address)) {
        throw new NullPointerException("address is empty!");
    }

    if (mReconnectSignalHandler == null) {
        HandlerThread handlerThread = new HandlerThread("ReconnectSignalHandlerThread");
        handlerThread.start();
        mReconnectSignalHandler = new ReconnectSignalHandler(this, handlerThread);
    }

    setAndNotifyStateChanged(State.Connecting);

    Request request = new Request.Builder().url(getAddress())
            .build();
    mWebSocketCall = WebSocketCall.create(mNetworkClient.getOkHttpClient(),
            request);
    mWSListener = new WSListener();
    mWebSocketCall.enqueue(mWSListener);

    if (mSendMessageThread.getState() != Thread.State.NEW) {
        mSendMessageThread = mSendMessageThread.clone();
    }
}
 
Example #26
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public ServicePlayerController(Context context, PreferenceStore preferenceStore,
            PlaybackPersistenceManager persistenceManager) {
    mContext = context;
    mPreferenceStore = preferenceStore;
    mPersistenceManager = persistenceManager;
    mConnection = new PlayerServiceConnection();
    mRequestThread = new HandlerThread("ServiceExecutor");
    mMediaSessionToken = BehaviorSubject.create();
    mRequestQueue = new ObservableQueue<>();
    mActiveBindings = new HashSet<>();

    mShuffleMode.setValue(preferenceStore.isShuffled());
    mRepeatMode.setValue(preferenceStore.getRepeatMode());

    mShuffleSeedGenerator = new Random();
    mMainHandler = new Handler(Looper.getMainLooper());
    mRequestThread.start();

    isPlaying().subscribe(
            isPlaying -> {
                if (isPlaying) {
                    startCurrentPositionClock();
                } else {
                    stopCurrentPositionClock();
                }
            }, throwable -> {
                Timber.e(throwable, "Failed to update current position clock");
            });
}
 
Example #27
Source File: JZMediaSystem.java    From imsdk-android with MIT License 5 votes vote down vote up
@Override
public void prepare() {
    release();
    mMediaHandlerThread = new HandlerThread("JZVD");
    mMediaHandlerThread.start();
    mMediaHandler = new Handler(mMediaHandlerThread.getLooper());//主线程还是非主线程,就在这里
    handler = new Handler();

    mMediaHandler.post(() -> {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setLooping(jzvd.jzDataSource.looping);
            mediaPlayer.setOnPreparedListener(JZMediaSystem.this);
            mediaPlayer.setOnCompletionListener(JZMediaSystem.this);
            mediaPlayer.setOnBufferingUpdateListener(JZMediaSystem.this);
            mediaPlayer.setScreenOnWhilePlaying(true);
            mediaPlayer.setOnSeekCompleteListener(JZMediaSystem.this);
            mediaPlayer.setOnErrorListener(JZMediaSystem.this);
            mediaPlayer.setOnInfoListener(JZMediaSystem.this);
            mediaPlayer.setOnVideoSizeChangedListener(JZMediaSystem.this);
            Class<MediaPlayer> clazz = MediaPlayer.class;
            Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class);
            method.invoke(mediaPlayer, jzvd.jzDataSource.getCurrentUrl().toString(), jzvd.jzDataSource.headerMap);
            mediaPlayer.prepareAsync();
            mediaPlayer.setSurface(new Surface(SAVED_SURFACE));
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
 
Example #28
Source File: Camera2Renderer.java    From OpenCV-android 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 #29
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 #30
Source File: MediaScreenEncoder.java    From ScreenRecordingSample with Apache License 2.0 5 votes vote down vote up
public MediaScreenEncoder(final MediaMuxerWrapper muxer, final MediaEncoderListener listener,
	final MediaProjection projection, final int width, final int height, final int density,
	final int _bitrate, final int _fps) {

	super(muxer, listener, width, height);
	mMediaProjection = projection;
	mDensity = density;
	fps = (_fps > 0 && _fps <= 30) ? _fps : FRAME_RATE;
	bitrate = (_bitrate > 0) ? _bitrate : calcBitRate(_fps);
	final HandlerThread thread = new HandlerThread(TAG);
	thread.start();
	mHandler = new Handler(thread.getLooper());
}