Java Code Examples for android.os.Looper#myLooper()

The following examples show how to use android.os.Looper#myLooper() . 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: BarCodeProcessor.java    From StarBarcode with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: IjkMediaPlayer.java    From MKVideoPlayer with MIT License 6 votes vote down vote up
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));
}
 
Example 3
Source File: SeekbarPreference.java    From VIA-AI with MIT License 6 votes vote down vote up
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);
                }
            });
        }
    }
}
 
Example 4
Source File: AWindow.java    From OTTLivePlayer_vlc with MIT License 6 votes vote down vote up
@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();
}
 
Example 5
Source File: RepeaterHook.java    From QNotified with GNU General Public License v3.0 6 votes vote down vote up
@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);
                }
            });
        }
    }
}
 
Example 6
Source File: SharedPreferencesImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 7
Source File: SettingsFragment.java    From LearningAppAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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();
    }
}
 
Example 8
Source File: SuggestedUpdateViewImpl.java    From applivery-android-sdk with Apache License 2.0 5 votes vote down vote up
public Looper getLooper() {
  if (Looper.myLooper() == Looper.getMainLooper()) {
    return Looper.myLooper();
  } else {
    return Looper.getMainLooper();
  }
}
 
Example 9
Source File: ViewAware.java    From BigApp_WordPress_Android with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: SDKUtils.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 4 votes vote down vote up
public static boolean isInUiThread() {
    return Looper.getMainLooper() == Looper.myLooper();
}
 
Example 11
Source File: MainThread.java    From Dexter with Apache License 2.0 4 votes vote down vote up
private static boolean runningMainThread() {
  return Looper.getMainLooper() == Looper.myLooper();
}
 
Example 12
Source File: TextChipsEditView.java    From talk-android with MIT License 4 votes vote down vote up
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);
        }
    }
}
 
Example 13
Source File: InternalImageHandler.java    From wasp with Apache License 2.0 4 votes vote down vote up
private void checkMain() {
  if (Looper.myLooper() != Looper.getMainLooper()) {
    throw new IllegalStateException("Wasp.Image.load() must be invoked from the main thread.");
  }
}
 
Example 14
Source File: Choreographer.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private boolean isRunningOnLooperThreadLocked() {
    return Looper.myLooper() == mLooper;
}
 
Example 15
Source File: CustomLabelManager.java    From talkback with Apache License 2.0 4 votes vote down vote up
private void checkUiThread() {
  if (Looper.myLooper() != Looper.getMainLooper()) {
    throw new IllegalStateException("run not on UI thread");
  }
}
 
Example 16
Source File: SerialPort.java    From SerialPort_Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 17
Source File: Falcon.java    From weex with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 18
Source File: FragmentManager.java    From adt-leanback-support with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: CronetLibraryLoader.java    From cronet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Returns {@code true} if running on the initialization thread.
 */
private static boolean onInitThread() {
    return sInitThread.getLooper() == Looper.myLooper();
}
 
Example 20
Source File: PollingFragment.java    From RxJava-Android-Samples with Apache License 2.0 4 votes vote down vote up
private boolean _isCurrentlyOnMainThread() {
  return Looper.myLooper() == Looper.getMainLooper();
}