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: 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 #4
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 #5
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 #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: 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 #9
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 #10
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 #11
Source File: OfflineLicenseHelper.java    From TelePlus-Android with GNU General Public License v2.0 5 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 mediaDrm An underlying {@link ExoMediaDrm} for use by the manager.
 * @param callback Performs key and provisioning requests.
 * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
 *     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
 * @see DefaultDrmSessionManager#DefaultDrmSessionManager(java.util.UUID, ExoMediaDrm,
 *     MediaDrmCallback, HashMap, Handler, DefaultDrmSessionEventListener)
 */
public OfflineLicenseHelper(
    UUID uuid,
    ExoMediaDrm<T> mediaDrm,
    MediaDrmCallback callback,
    HashMap<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();
        }
      };
  drmSessionManager =
      new DefaultDrmSessionManager<>(uuid, mediaDrm, callback, optionalKeyRequestParameters);
  drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
 
Example #12
Source File: ViewCheckDokitView.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Context context) {
    mTraverHandlerThread = new HandlerThread(TAG);
    mTraverHandlerThread.start();
    mTraverHandler = new Handler(mTraverHandlerThread.getLooper());
    mFindCheckViewRunnable = new FindCheckViewRunnable();
    mResumedActivity = ActivityUtils.getTopActivity();
    LifecycleListenerUtil.registerListener(this);
}
 
Example #13
Source File: CameraConnectionFragment.java    From AndroidDemoProjects with Apache License 2.0 5 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());
  
  inferenceThread = new HandlerThread("InferenceThread");
  inferenceThread.start();
  inferenceHandler = new Handler(inferenceThread.getLooper());
}
 
Example #14
Source File: PDFView.java    From AndroidPdfViewerV1 with Apache License 2.0 5 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;
    }

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

    paint = new Paint();
    debugPaint = new Paint();
    debugPaint.setStyle(Style.STROKE);
    paintMinimapBack = new Paint();
    paintMinimapBack.setStyle(Style.FILL);
    paintMinimapBack.setColor(Color.BLACK);
    paintMinimapBack.setAlpha(50);
    paintMinimapFront = new Paint();
    paintMinimapFront.setStyle(Style.FILL);
    paintMinimapFront.setColor(Color.BLACK);
    paintMinimapFront.setAlpha(50);

    // A surface view does not call
    // onDraw() as a default but we need it.
    setWillNotDraw(false);

    pdfiumCore = new PdfiumCore(context);
}
 
Example #15
Source File: SensorsDataActivityLifecycleCallbacks.java    From sa-sdk-android with Apache License 2.0 5 votes vote down vote up
private void initHandler() {
    try {
        HandlerThread handlerThread = new HandlerThread("app_end_timer");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (messageReceiveTime != 0 && SystemClock.elapsedRealtime() - messageReceiveTime < sessionTime) {
                    SALog.i(TAG, "$AppEnd 事件已触发。");
                    return;
                }
                messageReceiveTime = SystemClock.elapsedRealtime();
                if (msg != null) {
                    Bundle bundle = msg.getData();
                    long startTime = bundle.getLong(APP_START_TIME);
                    long endTime = bundle.getLong(APP_END_TIME);
                    String endData = bundle.getString(APP_END_DATA);
                    boolean resetState = bundle.getBoolean(APP_RESET_STATE);
                    // 如果是正常的退到后台,需要重置标记位
                    if (resetState) {
                        resetState();
                    } else {// 如果是补发则需要添加打点间隔,防止 $AppEnd 在 AppCrash 事件序列之前
                        endTime = endTime + TIME_INTERVAL;
                    }
                    trackAppEnd(startTime, endTime, endData);
                }
            }
        };
        // 注册 Session 监听,防止多进程
        mContext.getContentResolver().registerContentObserver(DbParams.getInstance().getSessionTimeUri(),
                false, new SensorsActivityStateObserver(handler));
    } catch (Exception ex) {
        SALog.printStackTrace(ex);
    }
}
 
Example #16
Source File: IntentService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    // TODO: It would be nice to have an option to hold a partial wakelock
    // during processing, and to have a static startService(Context, Intent)
    // method that would launch the service & hand off a wakelock.

    super.onCreate();
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}
 
Example #17
Source File: WaltTcpConnection.java    From walt with Apache License 2.0 5 votes vote down vote up
public void connect() {
    connectionState = Utils.ListenerState.STARTING;
    networkThread = new HandlerThread("NetworkThread");
    networkThread.start();
    networkHandler = new Handler(networkThread.getLooper());
    logger.log("Started network thread for TCP bridge");
    networkHandler.post(new Runnable() {
        @Override
        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVER_PORT);
                socket.setSoTimeout(TCP_READ_TIMEOUT_MS);
                outputStream = socket.getOutputStream();
                inputStream = socket.getInputStream();
                logger.log("TCP connection established");
                connectionState = Utils.ListenerState.RUNNING;
            } catch (Exception e) {
                e.printStackTrace();
                logger.log("Can't connect to TCP bridge: " + e.getMessage());
                connectionState = Utils.ListenerState.STOPPED;
                return;
            }

            // Run the onConnect callback, but on main thread.
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    WaltTcpConnection.this.onConnect();
                }
            });
        }
    });

}
 
Example #18
Source File: HandlerThreadHandler.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * インスタンス生成用メルパーメソッド, API>=22
 * @param name
 * @param async Lopperの同期バリアの影響を受けずに非同期実行するかどうか
 * @return
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
public static final HandlerThreadHandler createHandler(
	final String name, final boolean async) {

	final HandlerThread thread = new HandlerThread(name);
	thread.start();
	return new HandlerThreadHandler(thread.getLooper(), async);
}
 
Example #19
Source File: VideoFrameReleaseTimeHelper.java    From TelePlus-Android with GNU General Public License v2.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 #20
Source File: MyApplication.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    INSTANCE = this;
    safetyNetLooper = new HandlerThread("SafetyNet task");
    safetyNetLooper.start();
    super.onCreate();
}
 
Example #21
Source File: ExportService.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();
  HandlerThread thread = new HandlerThread("ExportService");
  thread.start();
  serviceLooper = thread.getLooper();
  serviceHandler = new ServiceHandler(serviceLooper);
}
 
Example #22
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 #23
Source File: TextSearchFragment.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    mBackgroundThread = new HandlerThread("SearchThread");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    mUpdating = false;
}
 
Example #24
Source File: Camera2Renderer.java    From Image-Detection-Samples 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 #25
Source File: CameraSource.java    From Machine-Learning-Projects-for-Mobile-Applications with MIT License 5 votes vote down vote up
private void startBackgroundThread() {
    mBackgroundThread = new HandlerThread("CameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    synchronized (lock){
        runClassifier = true;
    }
    mBackgroundHandler.post(periodicClassify);
}
 
Example #26
Source File: LongLiveSocket.java    From Echo with Apache License 2.0 5 votes vote down vote up
public LongLiveSocket(String host, int port,
                      DataCallback dataCallback, ErrorCallback errorCallback) {
    mHost = host;
    mPort = port;
    mDataCallback = dataCallback;
    mErrorCallback = errorCallback;

    mWriterThread = new HandlerThread("socket-writer");
    mWriterThread.start();
    mWriterHandler = new Handler(mWriterThread.getLooper());
    mWriterHandler.post(this::initSocket);
}
 
Example #27
Source File: Camera2Renderer.java    From MOAAP with MIT License 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 #28
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 #29
Source File: DiscoveryManager.java    From zephyr with MIT License 5 votes vote down vote up
public DiscoveryManager(@NonNull Gson gson,
                        @NonNull ILogger logger,
                        @NonNull IPreferenceManager preferenceManager) {
    mGson = gson;
    mLogger = logger;
    mPreferenceManager = preferenceManager;

    HandlerThread mPacketHandlerThread = new HandlerThread(LOG_TAG);
    mPacketHandlerThread.start();
    mPacketHandler = new Handler(mPacketHandlerThread.getLooper());
    mDiscoveryRunnable = getDiscoveryRunnable();

    mDiscoveredServers = new ArrayMap<>();
    mDiscoveredServersLiveData = new MutableLiveData<>();
}
 
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());
}