下面列出了怎么用android.os.HandlerThread的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
@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);
}
}
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();
}
/**
* 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();
}*/
}
}
/**
* 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);
}
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();
}
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);
}
});
}
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);
}
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();
}
/**
* 开启发送消息线程
*/
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();
}
}
}
};
}
public void StartLooperWifi(Context context) {
this.mcContext = context;
HandlerThread looperwifi = new HandlerThread("looperwifi");
looperwifi.start();
looper = new MyLooperHandler(looperwifi.getLooper());
looper.post(mRunnable);
}
/**
* 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);
}
}
private VSyncSampler() {
sampledVsyncTimeNs = C.TIME_UNSET;
choreographerOwnerThread = new HandlerThread("ChoreographerOwner:Handler");
choreographerOwnerThread.start();
handler = Util.createHandler(choreographerOwnerThread.getLooper(), /* callback= */ this);
handler.sendEmptyMessage(CREATE_CHOREOGRAPHER);
}
public WXOkHttpDispatcher(Handler handler) {
mUiHandler = handler;
mOkHttpClient = defaultOkHttpClient();
mDispatcherThread = new HandlerThread("dispatcherThread");
mDispatcherThread.start();
mDispatcherHandler = new DispatcherHandler(mDispatcherThread.getLooper(), mOkHttpClient, mUiHandler);
}
@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();
}
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);
}
@Override
public synchronized void onResume() {
Log.d(TAG, "onResume " + this);
super.onResume();
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@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);
}
private void startBackgroundThread() {
Log.i(LOGTAG, "startBackgroundThread");
stopBackgroundThread();
mBackgroundThread = new HandlerThread("OpenCVCameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
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());
}
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);
}
@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));
}
@BeforeClass
public static void beforeClass() {
handlerThread = new HandlerThread("Test Handler Thread");
handlerThread.start();
HandlerThread secondThread = new HandlerThread("Second Handler Thread");
secondThread.start();
}
/**
* 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);
}
}
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();
}
}
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");
});
}
@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();
}
});
}
private void startBackgroundThread() {
Log.i(LOGTAG, "startBackgroundThread");
stopBackgroundThread();
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
@Override
public synchronized void onResume() {
Log.d(TAG, "onResume " + this);
super.onResume();
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
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());
}