下面列出了android.os.Looper#myLooper ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean handleMessage(Message msg) {
BarCodeProcessor barCodeProcessor = weakReference.get();
if (barCodeProcessor == null) return true;
if (msg == null || !barCodeProcessor.running) return true;
switch (State.values()[msg.what]){
case DECODE:
barCodeProcessor.decodeFrame((byte[]) msg.obj, msg.arg1, msg.arg2);
break;
case QUIT:
barCodeProcessor.running = false;
Looper looper = Looper.myLooper();
if (looper != null) {
looper.quit();
}
break;
}
return true;
}
private void initPlayer(IjkLibLoader libLoader) {
loadLibrariesOnce(libLoader);
initNativeOnce();
Looper looper;
if ((looper = Looper.myLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else if ((looper = Looper.getMainLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else {
mEventHandler = null;
}
/*
* Native setup requires a weak reference to our object. It's easier to
* create it here than in C++.
*/
native_setup(new WeakReference<IjkMediaPlayer>(this));
}
public void setPreviewVisibility(final boolean show) {
b_ShowImg = show;
if(mUI_ContentImage != null) {
if(Looper.myLooper() == Looper.getMainLooper()) {
if (b_ShowImg) {
mUI_ContentImage.setVisibility(View.VISIBLE);
} else {
mUI_ContentImage.setVisibility(View.GONE);
}
}
else {
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
setPreviewVisibility(show);
}
});
}
}
}
@Override
public void run() {
Looper.prepare();
synchronized (this) {
/* Ideally, all devices are running Android O, and we can create a SurfaceTexture
* without an OpenGL context and we can specify the thread (Handler) where to run
* SurfaceTexture callbacks. But this is not the case. The SurfaceTexture has to be
* created from a new thread with a prepared looper in order to don't use the
* MainLooper one (and have deadlock when we stop VLC from the mainloop).
*/
mLooper = Looper.myLooper();
mSurfaceTexture = new SurfaceTexture(0);
/* The OpenGL texture will be attached from the OpenGL Thread */
mSurfaceTexture.detachFromGLContext();
mSurfaceTexture.setOnFrameAvailableListener(this);
notify();
}
Looper.loop();
}
@Override
public void setEnabled(boolean enabled) {
try {
ConfigManager mgr = ConfigManager.getDefaultConfig();
mgr.getAllConfig().put(bug_repeater, enabled);
mgr.save();
} catch (final Exception e) {
Utils.log(e);
if (Looper.myLooper() == Looper.getMainLooper()) {
Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT);
} else {
SyncUtils.post(new Runnable() {
@Override
public void run() {
Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT);
}
});
}
}
}
private void notifyListeners(final MemoryCommitResult mcr) {
if (mcr.listeners == null || mcr.keysModified == null ||
mcr.keysModified.size() == 0) {
return;
}
if (Looper.myLooper() == Looper.getMainLooper()) {
for (int i = mcr.keysModified.size() - 1; i >= 0; i--) {
final String key = mcr.keysModified.get(i);
for (OnSharedPreferenceChangeListener listener : mcr.listeners) {
if (listener != null) {
listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key);
}
}
}
} else {
// Run this function on the main thread.
ActivityThread.sMainThreadHandler.post(() -> notifyListeners(mcr));
}
}
@Override
public void ready(MarketingCloudSdk marketingCloudSdk) {
cloudSdk = marketingCloudSdk;
marketingCloudSdk.getAnalyticsManager().trackPageView("data://SettingsActivity", "Loading Settings activity", null, null);
progressDialogHandler.removeCallbacks(dialogRunnable);
try {
RegistrationManager registrationManager = marketingCloudSdk.getRegistrationManager();
for (String key : registrationManager.getAttributes().keySet()) {
if (key.equals("FirstName") || key.equals("LastName")) {
attributes.put(key, registrationManager.getAttributes().get(key));
}
}
attributes.putAll(registrationManager.getAttributes());
subscriberKey = registrationManager.getContactKey();
tags.addAll(registrationManager.getTags());
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
displaySubscriberKey(subscriberKey, marketingCloudSdk);
displayAttributes(attributes, marketingCloudSdk);
displayTags(tags, marketingCloudSdk);
// Hide the progress dialog
if (dialog != null) {
if (Looper.myLooper() == Looper.getMainLooper()) {
dialog.hide();
} else {
mainThread.post(new Runnable() {
@Override
public void run() {
dialog.hide();
}
});
}
dialog.dismiss();
}
}
public Looper getLooper() {
if (Looper.myLooper() == Looper.getMainLooper()) {
return Looper.myLooper();
} else {
return Looper.getMainLooper();
}
}
@Override
public boolean setImageDrawable(Drawable drawable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
View view = viewRef.get();
if (view != null) {
setImageDrawableInto(drawable, view);
return true;
}
} else {
L.w(WARN_CANT_SET_DRAWABLE);
}
return false;
}
private static boolean runningMainThread() {
return Looper.getMainLooper() == Looper.myLooper();
}
private boolean _isCurrentlyOnMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
/**
* Returns {@code true} if running on the initialization thread.
*/
private static boolean onInitThread() {
return sInitThread.getLooper() == Looper.myLooper();
}
/**
* Only call from main thread!
*/
public boolean execPendingActions() {
if (mExecutingActions) {
throw new IllegalStateException("Recursive entry to executePendingTransactions");
}
if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
throw new IllegalStateException("Must be called from main thread of process");
}
boolean didSomething = false;
while (true) {
int numActions;
synchronized (this) {
if (mPendingActions == null || mPendingActions.size() == 0) {
break;
}
numActions = mPendingActions.size();
if (mTmpActions == null || mTmpActions.length < numActions) {
mTmpActions = new Runnable[numActions];
}
mPendingActions.toArray(mTmpActions);
mPendingActions.clear();
mActivity.mHandler.removeCallbacks(mExecCommit);
}
mExecutingActions = true;
for (int i=0; i<numActions; i++) {
mTmpActions[i].run();
mTmpActions[i] = null;
}
mExecutingActions = false;
didSomething = true;
}
if (mHavePendingDeferredStart) {
boolean loadersRunning = false;
for (int i=0; i<mActive.size(); i++) {
Fragment f = mActive.get(i);
if (f != null && f.mLoaderManager != null) {
loadersRunning |= f.mLoaderManager.hasRunningLoaders();
}
}
if (!loadersRunning) {
mHavePendingDeferredStart = false;
startPendingDeferredFragments();
}
}
return didSomething;
}
private static Bitmap takeBitmapUnchecked(Activity activity) throws InterruptedException {
final List<ViewRootData> viewRoots = getRootViews(activity);
int statusBarHeight = ScreenShot.getStatusBarHeight1(activity);
int actionBarHeight = ScreenShot.getActionBarHeight(activity);
View main = activity.getWindow().getDecorView();
int mainWidth = main.getWidth();
int mainHeight = main.getHeight();
int baseWidth = 750;
float widthScale = ((float) baseWidth) / mainWidth;
// 新建立矩阵 按照宽度缩放因子自适应缩放
Matrix matrix = new Matrix();
matrix.postScale(widthScale, widthScale);
Bitmap bitmap1 = Bitmap.createBitmap(main.getWidth(), main.getHeight(), ARGB_8888);
final Bitmap bitmap = Bitmap.createBitmap(bitmap1, 0, statusBarHeight + actionBarHeight,
mainWidth, mainHeight - statusBarHeight - actionBarHeight, matrix, true);
// We need to do it in main thread
if (Looper.myLooper() == Looper.getMainLooper()) {
drawRootsToBitmap(viewRoots, bitmap);
} else {
final CountDownLatch latch = new CountDownLatch(1);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
drawRootsToBitmap(viewRoots, bitmap);
}
finally {
latch.countDown();
}
}
});
latch.await();
}
return bitmap;
}
/**
* Write the byte array into the serial port.
*
* @param b [] the array to write
* @param off the starting index
* @param len the length to write (will be from startingIndex + length)
* @throws IOException
*/
@Override
public void write(byte b[], int off, int len) throws IOException {
if (baudRate == 0) {
Log.i(Tag, "baudrate was 0 nothing will be done.");
return;
}
if (off + len > b.length) {
throw new IndexOutOfBoundsException(
"Invalid offset/length passed to read");
}
byte send[] = new byte[len];
System.arraycopy(b, off, send, 0, len);
if (monThreadisInterrupted == true) {
return;
}
monThread.Pause();
Log.i(Tag, "bytes.write:" + send.length + " length, ");
if (Looper.getMainLooper() == Looper.myLooper()) {
// if we are in here then we are on UIThread/MainThread.
// Will start a new one to work on for writing...
/**
* simple thread helper
*
* @author Jeremy.Mei-Garino
*
*/
class InternalWritingThread extends Thread {
InternalWritingThread(Runnable r) {
super(r);
setName("writingSerialThread");
}
}
/**
* Runnable logic for reading our SerialPort from another
* thread.
*
* @author Jeremy.Mei-Garino
*
*/
class InternalWritingLogik implements Runnable {
byte[] _fullData;
int _length;
InternalWritingLogik(byte[] dataHolder, int lengthToWrite) {
super();
_fullData = dataHolder;
_length = lengthToWrite;
}
/**
* Will run our logic and yield the thread when it's done.
*/
@Override
public void run() {
synchronized (self_ftdi) {
Log.i(Tag, "writing on " + Thread.currentThread().getName() + " thread");
if (self_ftdi != null) {
self_ftdi.write(_fullData, _length);
} else if (self_prolific != null) {
self_prolific.write(_fullData, _length);
}
}
Thread.yield();
}
}
InternalWritingThread d = new InternalWritingThread(
new InternalWritingLogik(send, len));
d.start();
while (d.isAlive()) {
}
} else {
if (Looper.myLooper() != null) {
Log.i(Tag, "writing on " + Looper.myLooper().getThread().getName());
} else {
Log.i(Tag, "writing on a null Looper Thread");
}
// we seems to already be on our own thread and should then be
// able to directly write...
if (self_ftdi != null) {
self_ftdi.write(send, len);
} else if (self_prolific != null) {
self_prolific.write(send, len);
}
}
monThread.Resume();
}
private void checkUiThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("run not on UI thread");
}
}
private boolean isRunningOnLooperThreadLocked() {
return Looper.myLooper() == mLooper;
}
private void checkMain() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("Wasp.Image.load() must be invoked from the main thread.");
}
}
private void processReplacements(final List<DrawableRecipientChip> recipients,
final List<DrawableRecipientChip> replacements) {
if (replacements != null && replacements.size() > 0) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
final Editable text = new SpannableStringBuilder(getText());
int i = 0;
for (final DrawableRecipientChip chip : recipients) {
final DrawableRecipientChip replacement = replacements.get(i);
if (replacement != null) {
final RecipientEntry oldEntry = chip.getEntry();
final RecipientEntry newEntry = replacement.getEntry();
final boolean isBetter =
RecipientAlternatesAdapter.getBetterRecipient(
oldEntry, newEntry) == newEntry;
if (isBetter) {
// Find the location of the chip in the text currently shown.
final int start = text.getSpanStart(chip);
if (start != -1) {
// Replacing the entirety of what the chip represented,
// including the extra space dividing it from other chips.
final int end =
Math.min(text.getSpanEnd(chip) + 1, text.length());
text.removeSpan(chip);
// Make sure we always have just 1 space at the end to
// separate this chip from the next chip.
final SpannableString displayText =
new SpannableString(createAddressText(
replacement.getEntry()).trim() + " ");
displayText.setSpan(replacement, 0,
displayText.length() - 1,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// Replace the old text we found with with the new display
// text, which now may also contain the display name of the
// recipient.
text.replace(start, end, displayText);
replacement.setOriginalText(displayText.toString());
replacements.set(i, null);
recipients.set(i, replacement);
}
}
}
i++;
}
setText(text);
}
};
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
} else {
mHandler.post(runnable);
}
}
}
public static boolean isInUiThread() {
return Looper.getMainLooper() == Looper.myLooper();
}