android.os.MessageQueue Java Examples

The following examples show how to use android.os.MessageQueue. 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: SampleLoadReporter.java    From HotFixDemo with MIT License 6 votes vote down vote up
/**
 * 这个是无论加载失败或者成功都会回调的接口。
 * 它返回了本次加载所用的时间、返回码等信息。
 * 默认我们只是简单的输出这个信息,你可以在这里加上监控上报逻辑。
 */
@Override
public void onLoadResult(File patchDirectory, int loadCode, long cost) {
    super.onLoadResult(patchDirectory, loadCode, cost);
    switch (loadCode) {
        case ShareConstants.ERROR_LOAD_OK:
            SampleTinkerReport.onLoaded(cost);
            break;
    }
    Looper.getMainLooper().myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            if (UpgradePatchRetry.getInstance(context).onPatchRetryLoad()) {
               SampleTinkerReport.onReportRetryPatch();
            }
            return false;
        }
    });
}
 
Example #2
Source File: ContentApplication.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Delay TracingControllerAndroid.registerReceiver() until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;

            try {
                getTracingController().registerReceiver(ContentApplication.this);
            } catch (SecurityException e) {
                // Happens if the process is isolated. Ignore.
            }
            // Remove the idle handler.
            return false;
        }
    });
}
 
Example #3
Source File: ContentApplication.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Delay TracingControllerAndroid.registerReceiver() until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;

            try {
                getTracingController().registerReceiver(ContentApplication.this);
            } catch (SecurityException e) {
                // Happens if the process is isolated. Ignore.
            }
            // Remove the idle handler.
            return false;
        }
    });
}
 
Example #4
Source File: ContentApplication.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Delay TracingControllerAndroid.registerReceiver() until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;

            try {
                getTracingController().registerReceiver(ContentApplication.this);
            } catch (SecurityException e) {
                // Happens if the process is isolated. Ignore.
            }
            // Remove the idle handler.
            return false;
        }
    });

    mLibraryDependenciesInitialized = true;
}
 
Example #5
Source File: DeferredStartupHandler.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Add the idle handler which will run deferred startup tasks in sequence when idle. This can
 * be called multiple times by different activities to schedule their own deferred startup
 * tasks.
 */
public void queueDeferredTasksOnIdleHandler() {
    mMaxTaskDuration = 0;
    mDeferredStartupDuration = 0;
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            Runnable currentTask = mDeferredTasks.poll();
            if (currentTask == null) {
                if (!mDeferredStartupCompletedForApp) {
                    mDeferredStartupCompletedForApp = true;
                    recordDeferredStartupStats();
                }
                return false;
            }

            long startTime = SystemClock.uptimeMillis();
            currentTask.run();
            long timeTaken = SystemClock.uptimeMillis() - startTime;

            mMaxTaskDuration = Math.max(mMaxTaskDuration, timeTaken);
            mDeferredStartupDuration += timeTaken;
            return true;
        }
    });
}
 
Example #6
Source File: DeferredStartupHandler.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Add the idle handler which will run deferred startup tasks in sequence when idle. This can
 * be called multiple times by different activities to schedule their own deferred startup
 * tasks.
 */
public void queueDeferredTasksOnIdleHandler() {
    mMaxTaskDuration = 0;
    mDeferredStartupDuration = 0;
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            Runnable currentTask = mDeferredTasks.poll();
            if (currentTask == null) {
                if (mDeferredStartupInitializedForApp) {
                    mDeferredStartupCompletedForApp = true;
                    recordDeferredStartupStats();
                }
                return false;
            }

            long startTime = SystemClock.uptimeMillis();
            currentTask.run();
            long timeTaken = SystemClock.uptimeMillis() - startTime;

            mMaxTaskDuration = Math.max(mMaxTaskDuration, timeTaken);
            mDeferredStartupDuration += timeTaken;
            return true;
        }
    });
}
 
Example #7
Source File: TinkerServerManager.java    From tinkerpatch-sdk with MIT License 6 votes vote down vote up
/**
 * 向服务器请求在线参数信息
 * @param configRequestCallback
 * @param immediately            是否立刻请求,忽略时间间隔限制
 */
public static void getDynamicConfig(final ConfigRequestCallback configRequestCallback, final boolean immediately) {
    if (sTinkerServerClient == null) {
        TinkerLog.e(TAG, "checkTinkerUpdate, sTinkerServerClient == null");
        return;
    }
    Tinker tinker = sTinkerServerClient.getTinker();
    //only check at the main process
    if (tinker.isMainProcess()) {
        Looper.getMainLooper().myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override public boolean queueIdle() {
                sTinkerServerClient.getDynamicConfig(configRequestCallback, immediately);
                return false;
            }
        });
    }
}
 
Example #8
Source File: TinkerServerManager.java    From tinkerpatch-sdk with MIT License 6 votes vote down vote up
/**
 * 检查服务器是否有补丁更新
 * @param immediately 是否立刻检查,忽略时间间隔限制
 */
public static void checkTinkerUpdate(final boolean immediately) {
    if (sTinkerServerClient == null) {
        TinkerLog.e(TAG, "checkTinkerUpdate, sTinkerServerClient == null");
        return;
    }
    Tinker tinker = sTinkerServerClient.getTinker();
    //only check at the main process
    if (tinker.isMainProcess()) {
        Looper.getMainLooper().myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override public boolean queueIdle() {
                sTinkerServerClient.checkTinkerUpdate(immediately);
                return false;
            }
        });
    }
}
 
Example #9
Source File: ChromeActivity.java    From delion with Apache License 2.0 6 votes vote down vote up
protected final void postDeferredStartupIfNeeded() {
    if (!mDeferredStartupNotified) {
        RecordHistogram.recordLongTimesHistogram(
                "UMA.Debug.EnableCrashUpload.PostDeferredStartUptime",
                SystemClock.uptimeMillis() - UmaUtils.getMainEntryPointTime(),
                TimeUnit.MILLISECONDS);

        // We want to perform deferred startup tasks a short time after the first page
        // load completes, but only when the main thread Looper has become idle.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!mDeferredStartupNotified && !isActivityDestroyed()) {
                    mDeferredStartupNotified = true;
                    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                        @Override
                        public boolean queueIdle() {
                            onDeferredStartup();
                            return false;  // Remove this idle handler.
                        }
                    });
                }
            }
        }, DEFERRED_STARTUP_DELAY_MS);
    }
}
 
Example #10
Source File: SampleLoadReporter.java    From tinker-manager with Apache License 2.0 6 votes vote down vote up
@Override
public void onLoadResult(File patchDirectory, int loadCode, long cost) {
    super.onLoadResult(patchDirectory, loadCode, cost);
    switch (loadCode) {
        case ShareConstants.ERROR_LOAD_OK:
            PatchManager.getInstance().onLoadSuccess();
            SampleTinkerReport.onLoaded(cost);
            break;

        default:
            break;
    }
    Looper.getMainLooper().myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            if (UpgradePatchRetry.getInstance(context).onPatchRetryLoad()) {
                SampleTinkerReport.onReportRetryPatch();
            }
            return false;
        }
    });
}
 
Example #11
Source File: DownloadFragment.java    From music_player with Open Software License 3.0 6 votes vote down vote up
@Override
    public void onResume() {
        super.onResume();
//        return true会重复执行,false只执行一次
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                SharedPreferences bundle = getActivity().getSharedPreferences("default_resource", MODE_PRIVATE);
                type = bundle.getString("default", "netease");
                for (int i = 0; i < 12; i++) {
                    if (type.equals(item_type[i])) {
                        setListListener(i);
                        break;
                    };
                }
                return false;
            }
        });
    }
 
Example #12
Source File: TimeCatApp.java    From timecat with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    instance = this;
    SPHelper.init(this);
    ThemeUtils.setSwitchColor(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // initialize SQLite engine
    initializeDatabase();

    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {

            KeepAliveWatcher.keepAlive(TimeCatApp.this);
            startService(new Intent(TimeCatApp.this, ListenClipboardService.class));
            startService(new Intent(TimeCatApp.this, TimeCatMonitorService.class));
            return false;
        }
    });
    AppManager.getInstance(this);
    mState = STATE_WAIT;
}
 
Example #13
Source File: AndroidHeapDumper.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
private void showToast(final FutureResult<Toast> waitingForToast) {
  mainHandler.post(new Runnable() {
    @Override
    public void run() {
      if (resumedActivity == null) {
        waitingForToast.set(null);
        return;
      }
      final Toast toast = new Toast(resumedActivity);
      toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
      toast.setDuration(Toast.LENGTH_LONG);
      LayoutInflater inflater = LayoutInflater.from(resumedActivity);
      toast.setView(inflater.inflate(R.layout.leak_canary_heap_dump_toast, null));
      toast.show();
      // Waiting for Idle to make sure Toast gets rendered.
      Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
          waitingForToast.set(toast);
          return false;
        }
      });
    }
  });
}
 
Example #14
Source File: PhotoModule.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
private void addIdleHandler()
{
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new MessageQueue.IdleHandler()
    {
        @Override
        public boolean queueIdle()
        {
            Storage.ensureOSXCompatible();
            return false;
        }
    });
}
 
Example #15
Source File: ChromeStrictMode.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Replace Android OS's StrictMode.violationsBeingTimed with a custom ArrayList acting as an
 * observer into violation stack traces. Set up an idle handler so StrictMode violations that
 * occur on startup are not ignored.
 */
@SuppressWarnings({"unchecked", "rawtypes" })
@UiThread
private static void initializeStrictModeWatch() {
    try {
        Field violationsBeingTimedField =
                StrictMode.class.getDeclaredField("violationsBeingTimed");
        violationsBeingTimedField.setAccessible(true);
        ThreadLocal<ArrayList> violationsBeingTimed =
                (ThreadLocal<ArrayList>) violationsBeingTimedField.get(null);
        ArrayList replacementList = new SnoopingArrayList();
        violationsBeingTimed.set(replacementList);
    } catch (Exception e) {
        // Terminate watch if any exceptions are raised.
        Log.w(TAG, "Could not initialize StrictMode watch.", e);
        return;
    }
    sNumUploads.set(0);
    // Delay handling StrictMode violations during initialization until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;
            // Check again next time if no more cached stack traces to upload, and we have not
            // reached the max number of uploads for this session.
            if (sCachedStackTraces.isEmpty()) {
                // TODO(wnwen): Add UMA count when this happens.
                // In case of races, continue checking an extra time (equal condition).
                return sNumUploads.get() <= MAX_UPLOADS_PER_SESSION;
            }
            // Since this is the only place we are removing elements, no need for additional
            // synchronization to ensure it is still non-empty.
            reportStrictModeViolation(sCachedStackTraces.remove(0));
            return true;
        }
    });
}
 
Example #16
Source File: ChromeStrictMode.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Replace Android OS's StrictMode.violationsBeingTimed with a custom ArrayList acting as an
 * observer into violation stack traces. Set up an idle handler so StrictMode violations that
 * occur on startup are not ignored.
 */
@SuppressWarnings({"unchecked", "rawtypes" })
@UiThread
private static void initializeStrictModeWatch() {
    try {
        Field violationsBeingTimedField =
                StrictMode.class.getDeclaredField("violationsBeingTimed");
        violationsBeingTimedField.setAccessible(true);
        ThreadLocal<ArrayList> violationsBeingTimed =
                (ThreadLocal<ArrayList>) violationsBeingTimedField.get(null);
        ArrayList replacementList = new SnoopingArrayList();
        violationsBeingTimed.set(replacementList);
    } catch (Exception e) {
        // Terminate watch if any exceptions are raised.
        Log.w(TAG, "Could not initialize StrictMode watch.", e);
        return;
    }
    sNumUploads.set(0);
    // Delay handling StrictMode violations during initialization until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;
            // Check again next time if no more cached stack traces to upload, and we have not
            // reached the max number of uploads for this session.
            if (sCachedStackTraces.isEmpty()) {
                // TODO(wnwen): Add UMA count when this happens.
                // In case of races, continue checking an extra time (equal condition).
                return sNumUploads.get() <= MAX_UPLOADS_PER_SESSION;
            }
            // Since this is the only place we are removing elements, no need for additional
            // synchronization to ensure it is still non-empty.
            reportStrictModeViolation(sCachedStackTraces.remove(0));
            return true;
        }
    });
}
 
Example #17
Source File: AndroidWatchExecutor.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
private void waitForIdle(final Retryable retryable, final int failedAttempts) {
    // This needs to be called from the main thread.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            postToBackgroundWithDelay(retryable, failedAttempts);
            return false;
        }
    });
}
 
Example #18
Source File: MainActivity.java    From DelayLoadSample with Apache License 2.0 5 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        zhihuImg = findViewById(R.id.zhihu_img);

        imageWidthTxt = findViewById(R.id.img_width_txt);
        imageHeightTxt = findViewById(R.id.img_height_txt);

//      第一种写法:直接Post
//      myHandler.post(mLoadingRunnable);

//      第二种写法:直接PostDelay 300ms.
//      myHandler.postDelayed(mLoadingRunnable, DELAY_TIME);

//      第三种写法:
//      优化的DelayLoad
//        getWindow().getDecorView().post(new Runnable() {
//            @Override
//            public void run() {
//                myHandler.post(mLoadingRunnable);
//            }
//        });


        //第四种写法
        // 利用 IdleHandler
        MessageQueue.IdleHandler idleHandler = new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                updateText();
                return false;
            }
        };
        Looper.myQueue().addIdleHandler(idleHandler);
    }
 
Example #19
Source File: AndroidWatchExecutor.java    From leakcanary-for-eclipse with MIT License 5 votes vote down vote up
private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {
  // This needs to be called from the main thread.
  Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
    @Override public boolean queueIdle() {
      backgroundHandler.postDelayed(runnable, DELAY_MILLIS);
      return false;
    }
  });
}
 
Example #20
Source File: ChromeStrictMode.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Replace Android OS's StrictMode.violationsBeingTimed with a custom ArrayList acting as an
 * observer into violation stack traces. Set up an idle handler so StrictMode violations that
 * occur on startup are not ignored.
 */
@SuppressWarnings({"unchecked", "rawtypes" })
@UiThread
private static void initializeStrictModeWatch() {
    try {
        Field violationsBeingTimedField =
                StrictMode.class.getDeclaredField("violationsBeingTimed");
        violationsBeingTimedField.setAccessible(true);
        ThreadLocal<ArrayList> violationsBeingTimed =
                (ThreadLocal<ArrayList>) violationsBeingTimedField.get(null);
        ArrayList replacementList = new SnoopingArrayList();
        violationsBeingTimed.set(replacementList);
    } catch (Exception e) {
        // Terminate watch if any exceptions are raised.
        Log.w(TAG, "Could not initialize StrictMode watch.", e);
        return;
    }
    sNumUploads.set(0);
    // Delay handling StrictMode violations during initialization until the main loop is idle.
    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            // Will retry if the native library has not been initialized.
            if (!LibraryLoader.isInitialized()) return true;
            // Check again next time if no more cached stack traces to upload, and we have not
            // reached the max number of uploads for this session.
            if (sCachedStackTraces.isEmpty()) {
                // TODO(wnwen): Add UMA count when this happens.
                // In case of races, continue checking an extra time (equal condition).
                return sNumUploads.get() <= MAX_UPLOADS_PER_SESSION;
            }
            // Since this is the only place we are removing elements, no need for additional
            // synchronization to ensure it is still non-empty.
            reportStrictModeViolation(sCachedStackTraces.remove(0));
            return true;
        }
    });
}
 
Example #21
Source File: AndroidWatchExecutor.java    From SimpleLeakCanary with Apache License 2.0 5 votes vote down vote up
private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {
  // This needs to be called from the main thread.
  Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
    @Override
    public boolean queueIdle() {
      backgroundHandler.postDelayed(runnable, DELAY_MILLIS);
      return false;
    }
  });
}
 
Example #22
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
private ReferenceQueue<EngineResource<?>> getReferenceQueue() {
    if (resourceReferenceQueue == null) {
        resourceReferenceQueue = new ReferenceQueue<EngineResource<?>>();
        MessageQueue queue = Looper.myQueue();
        queue.addIdleHandler(new RefQueueIdleHandler(activeResources, resourceReferenceQueue));
    }
    return resourceReferenceQueue;
}
 
Example #23
Source File: Loopers.java    From deagle with Apache License 2.0 5 votes vote down vote up
public static void addIdleTask(final Looper looper, final Runnable task) {
	getQueue(looper).addIdleHandler(new MessageQueue.IdleHandler() {
		@Override public boolean queueIdle() {
			task.run();
			return false;
		}

		@Override public String toString() {
			return "IdleTask[" + task.toString() + "]";
		}
	});
}
 
Example #24
Source File: RequestHandlerThread.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void waitUntilIdle() {
    Handler handler = waitAndGetHandler();
    MessageQueue queue = handler.getLooper().getQueue();
    if (queue.isIdle()) {
        return;
    }
    mIdle.close();
    queue.addIdleHandler(mIdleHandler);
    // Ensure that the idle handler gets run even if the looper already went idle
    handler.sendEmptyMessage(MSG_POKE_IDLE_HANDLER);
    if (queue.isIdle()) {
        return;
    }
    mIdle.block();
}
 
Example #25
Source File: SettingsProxyProvider.java    From deagle with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")/* getQueue() is hidden but accessible before M */
@Override public boolean onCreate() {
	new Handler().getLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() {
		final int result = SettingsProxyProvider.this.context().checkPermission(WRITE_SECURE_SETTINGS, Process.myPid(), Process.myUid());
		context().getPackageManager().setComponentEnabledSetting(new ComponentName(context(), SettingsProxyProvider.this.getClass()),
				result == PERMISSION_GRANTED ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT, DONT_KILL_APP);
		return false;
	}});
	return true;
}
 
Example #26
Source File: AndroidReachabilityInspectors.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
public @NonNull
Reachability expectedReachability(@NonNull LeakTraceElement element) {
  if (!element.isInstanceOf(MessageQueue.class)) {
    return Reachability.UNKNOWN;
  }
  String mQuitting = element.getFieldReferenceValue("mQuitting");
  // If the queue is not quitting, maybe it should actually have been, we don't know.
  // However, if it's quitting, it is very likely that's not a bug.
  if ("true".equals(mQuitting)) {
    return Reachability.UNREACHABLE;
  }
  return Reachability.UNKNOWN;
}
 
Example #27
Source File: UiUtils.java    From Awesome-WanAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 实现将子线程Looper中的MessageQueue替换为主线程中Looper的
 * MessageQueue,这样就能够在子线程中异步创建UI。
 *
 * 注意:需要在子线程中调用。
 *
 * @param reset 是否将子线程中的MessageQueue重置为原来的,false则表示需要进行替换
 * @return 替换是否成功
 */
public static boolean replaceLooperWithMainThreadQueue(boolean reset) {
    if (CommonUtils.isMainThread()) {
        return true;
    } else {
        // 1、获取子线程的ThreadLocal实例
        ThreadLocal<Looper> threadLocal = ReflectUtils.reflect(Looper.class).field("sThreadLocal").get();
        if (threadLocal == null) {
            return false;
        } else {
            Looper looper = null;
            if (!reset) {
                Looper.prepare();
                looper = Looper.myLooper();
                // 2、通过调用MainLooper的getQueue方法区获取主线程Looper中的MessageQueue实例
                Object queue = ReflectUtils.reflect(Looper.getMainLooper()).method("getQueue").get();
                if (!(queue instanceof MessageQueue)) {
                    return false;
                }
                // 3、将子线程中的MessageQueue字段的值设置为主线的MessageQueue实例
                ReflectUtils.reflect(looper).field("mQueue", queue);
            }

            // 4、reset为false,表示需要将子线程Looper中的MessageQueue重置为原来的。
            ReflectUtils.reflect(threadLocal).method("set", looper);
            return true;
        }
    }
}
 
Example #28
Source File: Interrogator.java    From android-test with Apache License 2.0 4 votes vote down vote up
/**
 * Loops the main thread and informs the interrogation handler at interesting points in the exec
 * state.
 *
 * @param handler an interrogation handler that controls whether to continue looping or not.
 */
static <R> R loopAndInterrogate(InterrogationHandler<R> handler) {
  checkSanity();
  interrogating.set(Boolean.TRUE);
  boolean stillInterested = true;
  MessageQueue q = Looper.myQueue();
  // We may have an identity when we're called - we want to restore it at the end of the fn.
  final long entryIdentity = Binder.clearCallingIdentity();
  try {
    // this identity should not get changed by dispatching the loop until the observer is happy.
    final long threadIdentity = Binder.clearCallingIdentity();
    while (stillInterested) {
      // run until the observer is no longer interested.
      stillInterested = interrogateQueueState(q, handler);
      if (stillInterested) {
        Message m = getNextMessage();

        // the observer cannot stop us from dispatching this message - but we need to let it know
        // that we're about to dispatch.
        if (null == m) {
          handler.quitting();
          return handler.get();
        }
        stillInterested = handler.beforeTaskDispatch();
        handler.setMessage(m);
        m.getTarget().dispatchMessage(m);

        // ensure looper invariants
        final long newIdentity = Binder.clearCallingIdentity();
        // Detect binder id corruption.
        if (newIdentity != threadIdentity) {
          Log.wtf(
              TAG,
              "Thread identity changed from 0x"
                  + Long.toHexString(threadIdentity)
                  + " to 0x"
                  + Long.toHexString(newIdentity)
                  + " while dispatching to "
                  + m.getTarget().getClass().getName()
                  + " "
                  + m.getCallback()
                  + " what="
                  + m.what);
        }
        recycle(m);
      }
    }
  } finally {
    Binder.restoreCallingIdentity(entryIdentity);
    interrogating.set(Boolean.FALSE);
  }
  return handler.get();
}
 
Example #29
Source File: Loopers.java    From deagle with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")	// Looper.getQueue is hidden before Android M.
private static MessageQueue getQueue(final Looper looper) {
	return looper.getQueue();
}
 
Example #30
Source File: InputManagerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static native long nativeInit(InputManagerService service,
Context context, MessageQueue messageQueue);