Example usage for android.os Looper myLooper

List of usage examples for android.os Looper myLooper

Introduction

In this page you can find the example usage for android.os Looper myLooper.

Prototype

public static @Nullable Looper myLooper() 

Source Link

Document

Return the Looper object associated with the current thread.

Usage

From source file:com.android.volley.Request.java

/**
 * Notifies the request queue that this request has finished (successfully or with error).
 *
 * <p>Also dumps all events from this request's event log; for debugging.</p>
 *//* w w w.  java  2s  .c o m*/
void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
        final long threadId = Thread.currentThread().getId();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            // If we finish marking off of the main thread, we need to
            // actually do it on the main thread to ensure correct ordering.
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    mEventLog.add(tag, threadId);
                    mEventLog.finish(this.toString());
                }
            });
            return;
        }

        mEventLog.add(tag, threadId);
        mEventLog.finish(this.toString());
    }
}

From source file:com.wytiger.common.widget.SlideSwitch.java

private void invalidateView() {
    if (Looper.getMainLooper() == Looper.myLooper()) {
        invalidate();
    } else {
        postInvalidate();
    }
}

From source file:de.manumaticx.crouton.Manager.java

/**
 * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}.
 *
 * @param crouton// ww w.  j av  a2 s  .  co m
 *     The {@link Crouton} that should be added.
 */
private void addCroutonToView(final Crouton crouton) {
    // don't add if it is already showing
    if (crouton.isShowing()) {
        return;
    }

    final View croutonView = crouton.getView();
    if (null == croutonView.getParent()) {
        ViewGroup.LayoutParams params = croutonView.getLayoutParams();
        if (null == params) {
            params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        // display Crouton in ViewGroup is it has been supplied
        if (null != crouton.getViewGroup()) {
            // TODO implement add to last position feature (need to align with how this will be requested for activity)
            if (crouton.getViewGroup() instanceof FrameLayout) {
                crouton.getViewGroup().addView(croutonView, params);
            } else {
                crouton.getViewGroup().addView(croutonView, 0, params);
            }
        } else {
            Activity activity = crouton.getActivity();
            if (null == activity || activity.isFinishing()) {
                return;
            }
            handleTranslucentActionBar((ViewGroup.MarginLayoutParams) params, activity);

            if (Looper.myLooper() == Looper.getMainLooper()) {
                activity.addContentView(croutonView, params);
            } else {
                final Activity mActivity = activity;
                final ViewGroup.LayoutParams mParams = params;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.addContentView(croutonView, mParams);
                    }
                });
            }
        }
    }

    croutonView.requestLayout(); // This is needed so the animation can use the measured with/height
    ViewTreeObserver observer = croutonView.getViewTreeObserver();
    if (null != observer) {
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(16)
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    croutonView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    croutonView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                croutonView.startAnimation(crouton.getInAnimation());
                announceForAccessibilityCompat(crouton.getActivity(), crouton.getText());
                if (Configuration.DURATION_INFINITE != crouton.getConfiguration().durationInMilliseconds) {
                    sendMessageDelayed(crouton, Messages.REMOVE_CROUTON,
                            crouton.getConfiguration().durationInMilliseconds
                                    + crouton.getInAnimation().getDuration());
                }
            }
        });
    }
}

From source file:nuclei.task.TaskPool.java

/**
 * Execute the task on the current thread and without validation that it is unique.
 *
 * This is most useful if you need to execute a task from within a task.
 *///  ww  w.j  a  va 2 s.  co m
public <T> Result<T> executeNowResult(Task<T> task) {
    if (Looper.myLooper() == Looper.getMainLooper())
        throw new IllegalStateException("Cannot run on main thread");
    final String logKey = task.getLogKey();
    if (LOG.isLoggable(Log.INFO))
        LOG.i("Running task NOW (" + logKey + ")");
    long start = System.currentTimeMillis();
    Result<T> result = task.attach(this, null);
    task.run();
    if (LOG.isLoggable(Log.INFO)) {
        LOG.i("Took " + (System.currentTimeMillis() - start) + "ms to run NOW, "
                + (System.currentTimeMillis() - start) + "ms total to execute (" + logKey + ")");
    }
    task.deliverResult(EMPTY);
    return result;
}

From source file:org.solovyev.android.calculator.App.java

public static boolean isUiThread() {
    return Looper.myLooper() == Looper.getMainLooper();
}

From source file:com.jefftharris.passwdsafe.sync.onedrive.OnedriveProvider.java

/**
 * Get a OneDrive service for the client
 *///  w w w .j  ava  2 s .c  om
public IOneDriveService acquireOnedriveService() throws Exception {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new Exception("Can't invoke getOnedriveService in ui thread");
    }

    if (!itsServiceLock.tryLock(15, TimeUnit.MINUTES)) {
        throw new Exception("Timeout waiting for OneDrive service");
    }

    if (itsAuthClient.getSession().isExpired()) {
        PasswdSafeUtil.dbginfo(TAG, "sync refreshing auth token");
        itsAuthClient.getSession().refresh();
    }

    ODConnection conn = new ODConnection(itsAuthClient);
    conn.setVerboseLogcatOutput(false);
    return conn.getService();
}

From source file:com.mars.framework.volley.request.Request.java

/**
 * Notifies the request queue that this request has finished (successfully or with error).
 *
 * <p>Also dumps all events from this request's event log; for debugging.</p>
 *///  www.j a  v  a 2  s. c  o  m
public void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
        final long threadId = Thread.currentThread().getId();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            // If we finish marking off of the main thread, we need to
            // actually do it on the main thread to ensure correct ordering.
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    mEventLog.add(tag, threadId);
                    mEventLog.finish(this.toString());
                }
            });
            return;
        }

        mEventLog.add(tag, threadId);
        mEventLog.finish(this.toString());
    } else {
        long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;
        if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {
            VolleyLog.d("%d ms: %s", requestTime, this.toString());
        }
    }
}

From source file:nuclei.task.TaskPool.java

public <T> Result<T> execute(ContextHandle handle, Task<T> task) {
    Result<T> result = task.attach(this, handle);
    if (handler.getLooper() != Looper.myLooper()) {
        handler.obtainMessage(MESSAGE_QUEUE, task).sendToTarget();
        return result;
    }/*from  w  w w.  j ava2 s  . co  m*/
    TaskRunnable runnable = toRunnable(task);
    try {
        poolExecutor.execute(runnable);
    } catch (RejectedExecutionException err) {
        LOG.e("Error dispatching", err);
        task.onException(err);
        handler.obtainMessage(MESSAGE_QUEUE_FAILED, runnable).sendToTarget();
    }
    return result;
}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//  www .  j a  va  2 s .  c  o m

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    SharedPreferences prefs = Util.getPreferences(this);
    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:io.github.hidroh.materialistic.data.SyncDelegate.java

private void syncArticle(@NonNull HackerNewsItem item) {
    if (mJob.articleEnabled && item.isStoryType() && !TextUtils.isEmpty(item.getUrl())) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            loadArticle(item);//w  ww  . jav a2 s  .  c  o  m
        } else {
            mContext.startService(new Intent(mContext, WebCacheService.class)
                    .putExtra(WebCacheService.EXTRA_URL, item.getUrl()));
            notifyArticle(100);
        }
    }
}