public void run () { if (mIsConnected) return; try { mChannel = DatagramChannel.open(); mChannel.configureBlocking(false); mChannel.connect(new InetSocketAddress(mAddress, mPort)); if (mListenerThread == null) { mListenerThread = new ListenerThread(); mListenerThread.start(); mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECT, "")); mIsConnected = true; } Looper.prepare(); mSendHandler = new Handler(); Looper.loop(); } catch (Exception e) { mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECTION_FAIL, e.toString())); } }
public static void requestPermissions(@NonNull final Activity activity, @NonNull final String[] permissions, final int requestCode) { if (VERSION.SDK_INT >= 23) { ActivityCompatApi23.requestPermissions(activity, permissions, requestCode); } else if (activity instanceof OnRequestPermissionsResultCallback) { new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { int[] grantResults = new int[permissions.length]; PackageManager packageManager = activity.getPackageManager(); String packageName = activity.getPackageName(); int permissionCount = permissions.length; for (int i = 0; i < permissionCount; i++) { grantResults[i] = packageManager.checkPermission(permissions[i], packageName); } ((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(requestCode, permissions, grantResults); } }); } }
private void log(String logMsg){ if (isMainThread()){ mLogs.add(logMsg + "(主线程)"); mAdapter.notifyDataSetChanged(); }else { mLogs.add(logMsg + "(非主线程)"); //此处必须在UI线程更新(因为此时RecycelrView可能还在计算布局或者滚动) new Handler(Looper.getMainLooper()) .post(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } Log.d(TAG, "log: itemCount ->" + mAdapter.getItemCount()); }
private static void setupTime(final TextView timeView) { final Handler handler = new Handler(Looper.getMainLooper()); TimerTask task = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { mTime++; if (mTime >= 3600) { timeView.setText(String.format("%d:%02d:%02d", mTime / 3600, (mTime % 3600) / 60, (mTime % 60))); } else { timeView.setText(String.format("%02d:%02d", (mTime % 3600) / 60, (mTime % 60))); } } }); } }; timer = new Timer(); timer.schedule(task, 0, 1000); }
public void startSeek() { synchronized (mSync) { mPlayWhenDoneSeek = isPlaying(); if (!isPaused() && !isSeeking()) { Log.d(TAG, "start seeking with: request Seek"); mAudioDecoder.requestSeek(); mVideoDecoder.requestSeek(); } else if (!isSeeking()) { Log.d(TAG, "start seeking with: seeking"); try { mVideoDecoder.startSeeking(); mAudioDecoder.startSeeking(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(mOnStartSeekingRunnable); } catch (IOException e) { Log.d(TAG, "error when start seek"); } } mSync.notifyAll(); } }
private StaticDataCacheHelper(){ bnItemDoor = new HashMap<>(); mHandler = new Handler(Looper.getMainLooper()); String validEntries = SharePreferenceHandler.getInstance().getString("VALID_BN_ITEMS",null); if (validEntries == null){ bnValidEntries = new HashMap<>(); }else { try { Type type = new TypeToken<HashMap<String, Integer>>(){}.getType(); bnValidEntries = new Gson().fromJson(validEntries,type); }catch (Exception e){ NLog.i(TagUtil.makeTag(getClass()),"bnValidEntries init ",e); bnValidEntries = new HashMap<>(); } } }
@Override protected Class<?> findClass(String className) throws ClassNotFoundException { Class<?> clazz = null; if (Thread.currentThread().getId() != Looper.getMainLooper().getThread().getId()) { BundleUtil.checkBundleStateSyncOnChildThread(className); } else { BundleUtil.checkBundleStateSyncOnUIThread(className); } clazz = loadFromInstalledBundles(className, true); if (clazz != null) return clazz; ComponentName comp = new ComponentName(RuntimeVariables.androidApplication.getPackageName(),className); if (isProvider(comp)){ return Atlas.class.getClassLoader().loadClass("android.taobao.atlas.util.FakeProvider"); }else if(isReceiver(comp)){ return Atlas.class.getClassLoader().loadClass("android.taobao.atlas.util.FakeReceiver"); } throw new ClassNotFoundException("Can't find class " + className + printExceptionInfo()); }
public static synchronized void uninstall() { if (!sInstalled) { return; } sInstalled = false; sExceptionHandler = null; //卸载后恢复默认的异常处理逻辑,否则主线程再次抛出异常后将导致ANR,并且无法捕获到异常位置 Thread.setDefaultUncaughtExceptionHandler(sUncaughtExceptionHandler); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { throw new QuitCockroachException("Quit Cockroach.....");//主线程抛出异常,迫使 while (true) {}结束 } }); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void cancel() { if (Looper.myLooper() == null) { throw new AndroidRuntimeException("Animators may only be run on Looper threads"); } if ((mStarted || mRunning) && getListeners() != null) { if (!mRunning) { // If it's not yet running, then start listeners weren't called. Call them now. notifyStartListeners(); } ArrayList<AnimatorListener> tmpListeners = (ArrayList<AnimatorListener>) getListeners().clone(); for (AnimatorListener listener : tmpListeners) { listener.onAnimationCancel(this); } } endAnimation(); }
/** * Posts the given event to the event bus. */ public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (!postingState.isPosting) { postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { while (!eventQueue.isEmpty()) { postSingleEvent(null, eventQueue.remove(0), postingState); } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }
public void sendPacket(InetAddress address, int port, byte[] payload, int offset, int length) { if (address == null) return; if (Looper.myLooper() == Looper.getMainLooper()) { new Thread(() -> sendPacket(address, port, payload, offset, length)); return; } DatagramPacket packet = new DatagramPacket(payload, length); packet.setAddress(address); packet.setPort(port); try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); } }
private static void ensureNotOnMainThread(Context context) { Looper looper = Looper.myLooper(); if (looper != null && looper == context.getMainLooper()) { throw new IllegalStateException("calling this from your main thread can lead to " + "deadlock"); } }
/** * 加载网络图片缓存到磁盘中 * @param uri * @param reqWidth * @param reqHeight * @return */ private Bitmap loadBitmapFromHttp(String uri, int reqWidth, int reqHeight) { if (Looper.myLooper() == Looper.getMainLooper()) { throw new RuntimeException("can not visit network from UI thread."); } if (mDiskLruCache == null) { return null; } String key = hashKeyFromUri(uri); try { DiskLruCache.Editor editor = mDiskLruCache.edit(key); if (editor != null) { OutputStream outputStream = editor.newOutputStream(DISK_CACHE_INDEX); if (downloadBitmapToStream(uri, outputStream)){ editor.commit(); } else { editor.abort(); } mDiskLruCache.flush(); return loadBitmapFromDisCache(uri, reqWidth, reqHeight); } } catch (IOException e) { e.printStackTrace(); } return null; }
public void startup(Context context) throws Throwable { if (!isStartUp) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("VirtualCore.startup() must called in main thread."); } StubManifest.STUB_CP_AUTHORITY = context.getPackageName() + "." + StubManifest.STUB_DEF_AUTHORITY; ServiceManagerNative.SERVICE_CP_AUTH = context.getPackageName() + "." + ServiceManagerNative.SERVICE_DEF_AUTH; this.context = context; mainThread = ActivityThread.currentActivityThread.call(); unHookPackageManager = context.getPackageManager(); hostPkgInfo = unHookPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS); detectProcessType(); PatchManager patchManager = PatchManager.getInstance(); patchManager.init(); patchManager.injectAll(); ContextFixer.fixContext(context); isStartUp = true; if (initLock != null) { initLock.open(); initLock = null; } } }
@Override public void onCancelDetected() { if (DEBUG) { MyLog.i(CLS_NAME, "onCancelDetected"); } conditions.setCancelled(); new Handler(Looper.getMainLooper()).post( new Runnable() { @Override public void run() { if (Recognition.getState() == Recognition.State.LISTENING) { if (DEBUG) { MyLog.i(CLS_NAME, "onCancelDetected: stopping recognition: true"); } stopListening(false); } else { if (DEBUG) { MyLog.i(CLS_NAME, "onCancelDetected: stopping recognition: false"); } } } } ); }
public void startup(Context context) throws Throwable { if (!isStartUp) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("VirtualCore.startup() must called in main thread."); } StubManifest.STUB_CP_AUTHORITY = context.getPackageName() + "." + StubManifest.STUB_DEF_AUTHORITY; ServiceManagerNative.SERVICE_CP_AUTH = context.getPackageName() + "." + ServiceManagerNative.SERVICE_DEF_AUTH; this.context = context; mainThread = ActivityThread.currentActivityThread.call(); unHookPackageManager = context.getPackageManager(); hostPkgInfo = unHookPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS); detectProcessType(); InvocationStubManager invocationStubManager = InvocationStubManager.getInstance(); invocationStubManager.init(); invocationStubManager.injectAll(); ContextFixer.fixContext(context); isStartUp = true; if (initLock != null) { initLock.open(); initLock = null; } } }
/** * Recursively persist this object and all its children. * * @param modelClass the type to persist * @param jsonObject the json to process * @param <IdType> the ID type to return * @return the ID of the persisted object * @throws JSONException when something went wrong through parsing, this also fails the database transaction and results in no data changes */ public <IdType> IdType persistObject(Class<?> modelClass, JSONObject jsonObject) throws JSONException { if (Looper.myLooper() == Looper.getMainLooper()) { Log.w(getClass().getName(), "please call persistObject() on a background thread"); } try { enableWriteAheadLogging(); database.beginTransactionNonExclusive(); IdType id = persistObjectInternal(modelClass, jsonObject); database.setTransactionSuccessful(); return id; } finally { endTransaction(); } }
public void getAllUsers(View view) { RxAndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY) .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .getObjectListObservable(User.class) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<User>>() { @Override public void onCompleted() { Log.d(TAG, "onComplete Detail : getAllUsers completed"); } @Override public void onError(Throwable e) { Utils.logError(TAG, e); } @Override public void onNext(List<User> users) { Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } } }); }
public void init(Context context) { mDeviceListenerMap = new HashMap<>(); mIReaderListenerMap = new HashMap<>(); mINotificationListenerMap = new HashMap<>(); mUdooBluConnected = new HashMap<>(); mOnResultMap = new HashMap<>(); mIsBindService = context.bindService(new Intent(context, UdooBluService.class), mConnection, Context.BIND_AUTO_CREATE); context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); context.registerReceiver(mGattBoundReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); mHandler = new Handler(Looper.getMainLooper()); seqObserverQueue.run(); }
@Override public void dispatchMessage(Message msg) { switch (msg.what) { case MSG_REGISTOR: mUiThread = Thread.currentThread(); Looper.getMainLooper().setMessageLogging(this); break; } }
public static void runOnMainThreadSync(Runnable runnable) { if (Looper.myLooper() == Looper.getMainLooper()) { runnable.run(); return; } SyncPost poster = new SyncPost(runnable); getMainPoster().sync(poster); poster.waitRun(); }
private SnackbarManager() { mLock = new Object(); mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message message) { switch (message.what) { case MSG_TIMEOUT: handleTimeout((SnackbarRecord) message.obj); return true; } return false; } }); }
/** * 清除图片内存缓存 */ public void clearImageMemoryCache(Context context) { try { if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行 Glide.get(context).clearMemory(); } } catch (Exception e) { e.printStackTrace(); } }
public void set(Long value) { if (Looper.getMainLooper().equals(Looper.myLooper())) { // UI thread setValue(value); } else { // Non UI thread postValue(value); } }
@Override public void handleMessage(Message message) { if (!running) { return; } switch (message.what) { case IDecodeCallback.decode: decode((byte[]) message.obj, message.arg1, message.arg2); break; case IDecodeCallback.quit: running = false; Looper.myLooper().quit(); break; } }
@Test public void testThread() { threadTest(new Handler(Looper.getMainLooper())); HandlerThread handlerThread = new HandlerThread("Test Background Thread"); handlerThread.start(); threadTest(new Handler(handlerThread.getLooper())); }
public void resolveOnMain(final Result result) { this.mStatus = Status.SUCCESS; this.mResult = result; new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mCallback != null) { mCallback.onSuccess(mResult); } } }); }
public boolean setImageBitmap(Bitmap bitmap) { if (Looper.myLooper() == Looper.getMainLooper()) { View view = (View) this.viewRef.get(); if (view == null) { return false; } setImageBitmapInto(bitmap, view); return true; } L.w(WARN_CANT_SET_BITMAP, new Object[0]); return false; }
protected void configureForUIThread() { // Espresso support requires AndroidJUnitRunner, and that doesn't run tests on in the main // thread (and thus, not in a Looper). Adding a Looper allows normal unit tests to run // correctly. if (Looper.myLooper() == null) { Looper.prepare(); } // Set up the Handler for used by runAndSync() mTargetMainLooper = InstrumentationRegistry.getTargetContext().getMainLooper(); mHandler = new Handler(mTargetMainLooper); }
public static void runOnUiThread(Runnable runnable) { if (Looper.getMainLooper() == Looper.myLooper()) { //如果是主线程 runnable.run(); } else { handler.post(runnable); } }
private void initServantThread() { new ThreadCompat(new Runnable() { @Override public void run() { Looper.prepare(); final Object lock = Loopers.this; mServantLooper = Looper.myLooper(); synchronized (lock) { lock.notifyAll(); } Looper.loop(); } }).start(); }
private void addSystem(final SSystem sys) { systems.addSystem(sys); new Handler(Looper.getMainLooper()).post(new Runnable(){ public void run() { SystemView sv = new SystemView(getContext(), score, sys, SeeScoreView.this.assetManager, tapNotify); addView(sv); views.add(sv); } }); }
public void setPosition(int x, int y) { if (Looper.myLooper() == Looper.getMainLooper()) { mWindow.getWindowBridge().updatePosition(x, y); } else { mUiHandler.post(() -> mWindow.getWindowBridge().updatePosition(x, y)); } }
public OkHttpHelper() { mHttpClient = new OkHttpClient(); mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS); mHttpClient.setReadTimeout(10, TimeUnit.SECONDS); mHttpClient.setWriteTimeout(30, TimeUnit.SECONDS); mGson = new Gson(); mHandler = new Handler(Looper.getMainLooper()); }
/** * abort the layout and notify completion of abort on the main thread through the Runnable argument * * @param thenRunnable run() is executed when abort is complete on the main thread */ public void abortLayout(final Runnable thenRunnable) { if (isAbortingLayout) return; // already aborting - thenRunnable is DISCARDED! if (layoutThread != null) { isAbortingLayout = true; layoutThread.abort(); new Thread(new Runnable() { // start a thread to await completion of the abort public void run() { { try { layoutThread.join(); // await completion of abort } catch (InterruptedException e) { // don't care if interrupted during join } layoutThread = null; isAbortingLayout = false; new Handler(Looper.getMainLooper()).post(new Runnable(){ public void run() { thenRunnable.run(); } }); } } }, "AbortThread").start(); } else thenRunnable.run(); }
private void showMsg(final String msg) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } }); Log.e(TAG, msg); }
private ProtocolEventBus() { mainHandler = new Handler(Looper.getMainLooper()); BackgroundHandler backgroundHandler = new BackgroundHandler("bg-handler-thread", Process.THREAD_PRIORITY_BACKGROUND); backgroundHandler.start(); threadHandler = new Handler(backgroundHandler.getLooper()); }
public FindPresenter(Location location, LoaderManager loaderManager, LoaderProvider loaderProvider, Geocoder geocoder) { mLocation = location; mLoaderManager = loaderManager; mLoaderProvider = loaderProvider; mGeocoder = geocoder; mainHandler = new Handler(Looper.getMainLooper()); }
@Override public void handleMessage(Message message) { if (!running) { return; } switch (message.what) { case MESSAGE_DECODE: decode((byte[]) message.obj, message.arg1, message.arg2); break; case MESSAGE_QUIT: running = false; Looper.myLooper().quit(); break; } }
/** * Tries to communicate with Sensor to start or stop a connection */ public void handleMessage(Message message) { int type = message.arg1; if (type == START_CONNECTION) { connectToSensorAndReply((Intent) message.obj); } else if (type == STOP_CONNECTION) { stopSensorConnection((Looper) message.obj); } else if (type == SEND_MESSAGE) { MagpieEvent ev = processSensorMessage(message); mSensorService.sendEvent(ev); } }