Example usage for android.os Looper getMainLooper

List of usage examples for android.os Looper getMainLooper

Introduction

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

Prototype

public static Looper getMainLooper() 

Source Link

Document

Returns the application's main looper, which lives in the main thread of the application.

Usage

From source file:com.scvngr.levelup.core.ui.view.LevelUpCodeView.java

/**
 * <p>/*from w  w  w.ja  v  a2s  .  c om*/
 * Sets the code that will be displayed.
 * </p>
 * <p>
 * This must be called on the UI thread.
 * </p>
 *
 * @param codeData the raw content to be displayed in the QR code.
 * @param codeLoader the loader by which to load the QR code.
 */
public void setLevelUpCode(@NonNull final String codeData, @NonNull final LevelUpCodeLoader codeLoader) {

    if (Looper.getMainLooper() != Looper.myLooper()) {
        throw new AssertionError("Must be called from the main thread.");
    }

    if (null == mCurrentData && mIsFadeColorsSet) {
        animateFadeColorsDelayed();
    }

    if (codeData.equals(mCurrentData)) {
        final OnCodeLoadListener codeLoadListener = mOnCodeLoadListener;

        if (null != codeLoadListener) {
            if (null != mPendingImage && mPendingImage.isLoaded()) {
                codeLoadListener.onCodeLoad(false);
            }
        }
        return;
    }

    if (mPendingImage != null) {
        mPendingImage.cancelLoad();
    }

    mCurrentData = codeData;

    /*
     * The current code needs to be cleared so that it isn't displayed while the new code is
     * loading.
     */
    mCurrentCode = null;

    // Fake the loading flag so that cached results get a single isLoading(false) call.
    mPreviousIsCodeLoading = true;
    final PendingImage<LevelUpQrCodeImage> pendingImage = codeLoader.getLevelUpCode(codeData, mOnImageLoaded);
    mPendingImage = pendingImage;
    mPreviousIsCodeLoading = false;

    if (!pendingImage.isLoaded()) {
        callOnCodeLoadListener(true);

        // If the image is cached, invalidate() will be called from there.
        invalidate();
    }
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void checkForHeaderPost(View view) {

    ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking
            .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);

    postRequestBuilder.addHeaders("token", "1234");

    ANRequest anRequest = postRequestBuilder.setTag(this).setPriority(Priority.LOW)
            .setExecutor(Executors.newSingleThreadExecutor()).build();

    anRequest.setAnalyticsListener(new AnalyticsListener() {
        @Override/*from w  ww .  ja  v  a 2s .  c  o m*/
        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);
        }
    });

    anRequest.getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() {
        @Override
        public void onResponse(Response okHttpResponse, JSONObject response) {
            Log.d(TAG, "onResponse object : " + response.toString());
            Log.d(TAG,
                    "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
            if (okHttpResponse.isSuccessful()) {
                Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString());
            } else {
                Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString());
            }
        }

        @Override
        public void onError(ANError anError) {
            Utils.logError(TAG, anError);
        }
    });
}

From source file:com.facebook.Session.java

/**
 * Used by version 1 of the serialization proxy, do not modify.
 *//*from ww  w  . j ava  2s.  co m*/
private Session(String applicationId, SessionState state, AccessToken tokenInfo,
        Date lastAttemptedTokenExtendDate, boolean shouldAutoPublish,
        AuthorizationRequest pendingAuthorizationRequest) {
    this.applicationId = applicationId;
    this.state = state;
    this.tokenInfo = tokenInfo;
    this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate;
    this.pendingAuthorizationRequest = pendingAuthorizationRequest;
    handler = new Handler(Looper.getMainLooper());
    currentTokenRefreshRequest = null;
    tokenCachingStrategy = null;
    callbacks = new ArrayList<StatusCallback>();
}

From source file:com.nbarraille.loom.TaskManager.java

/**
 * Registers a listener with Loom.// w  ww  .  j  a v  a2 s .c  om
 * The listener will receive all the events sent by tasks with a {@link Task#name()} matching
 * their {@link LoomListener#taskName()}
 *
 * If the task with the given ID has already finished (and hasn't been cleared from the backlog
 * yet), the listener's {@link LoomListener#onSuccess} or {@link LoomListener#onFailure}
 * callback be called immediately, in the UI thread.
 *
 * It is recommended to use this version of registerListener when task completion events could
 * have been missed (Activity/Fragment re-creation after configuration change, for example)
 *
 * @param listener the listener to register, cannot be null
 * @param taskId   the ID of the task to receive past Success/Failure events for. If that task ID
 *                 refers to a task that has a different {@link Task#name}
 */
public void registerListener(@NonNull final LoomListener listener, int taskId) {
    mEventBus.register(listener);
    TaskStatus status = getTaskStatus(taskId);
    if (status != null) {
        if (status.isFinished()) {
            final SuccessEvent success = status.getSuccessEvent();
            final FailureEvent failure = status.getFailureEvent();
            if (success != null) {
                if (!TextUtils.equals(success.getTaskName(), listener.taskName()) && mIsLoggingEnabled) {
                    Log.e(Loom.LOG_TAG,
                            "The task with id " + taskId + " is not of type " + listener.taskName());
                    return;
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        //noinspection unchecked
                        listener.onSuccess(success);
                    }
                });
            } else if (failure != null) {
                if (!TextUtils.equals(failure.getTaskName(), listener.taskName()) && mIsLoggingEnabled) {
                    Log.e(Loom.LOG_TAG,
                            "The task with id " + taskId + " is not of type " + listener.taskName());
                    return;
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        //noinspection unchecked
                        listener.onFailure(failure);
                    }
                });
            }
        }
    }
}

From source file:it.mb.whatshare.Dialogs.java

/**
 * Shows a dialog to get a name for the inbound device being paired and
 * starts a new {@link CallGooGlInbound} action if the chosen name is valid.
 * /* w  w  w .j a  v  a  2s .c om*/
 * @param deviceType
 *            the model of the device being paired as suggested by the
 *            device itself
 * @param sharedSecret
 *            the keys used when encrypting the message between devices
 * @param activity
 *            the caller activity
 */
public static void promptForInboundName(final String deviceType, final int[] sharedSecret,
        final MainActivity activity) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {

        @Override
        public void run() {
            DialogFragment prompt = new PatchedDialogFragment() {
                public Dialog onCreateDialog(Bundle savedInstanceState) {
                    AlertDialog.Builder builder = getBuilder(activity);
                    final EditText input = new EditText(getContext());
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                    input.setText(deviceType);
                    input.setSelection(deviceType.length());
                    // @formatter:off
                    builder.setTitle(R.string.device_name_chooser_title).setView(input)
                            .setPositiveButton(android.R.string.ok, null);
                    // @formatter:on
                    final AlertDialog alertDialog = builder.create();
                    alertDialog.setOnShowListener(
                            new DeviceNameChooserPrompt(alertDialog, input, activity, new Callback<String>() {

                                @Override
                                public void run() {
                                    // @formatter:off
                                    new CallGooGlInbound(activity, getParam(), deviceType)
                                            .execute(sharedSecret);

                                    ((InputMethodManager) activity
                                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                                                    .hideSoftInputFromWindow(input.getWindowToken(), 0);
                                    // @formatter:on
                                }
                            }));
                    return alertDialog;
                }
            };
            prompt.show(activity.getSupportFragmentManager(), "chooseName");
        }
    });
}

From source file:sol.demo.seegeek.websocket.WebSocketConnection.java

/**
 * Create master message handler.//www  . j  a v  a2s.  c om
 */
protected void createHandler() {

    mMasterHandler = new Handler(Looper.getMainLooper()) {

        public void handleMessage(Message msg) {

            if (msg.obj instanceof WebSocketMessage.TextMessage) {

                WebSocketMessage.TextMessage textMessage = (WebSocketMessage.TextMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onTextMessage(textMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onTextMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.RawTextMessage) {

                WebSocketMessage.RawTextMessage rawTextMessage = (WebSocketMessage.RawTextMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onRawTextMessage(rawTextMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onRawTextMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.BinaryMessage) {

                WebSocketMessage.BinaryMessage binaryMessage = (WebSocketMessage.BinaryMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onBinaryMessage(binaryMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onBinaryMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.Ping) {

                WebSocketMessage.Ping ping = (WebSocketMessage.Ping) msg.obj;
                if (DEBUG)
                    Log.d(TAG, "WebSockets Ping received");

                // reply with Pong
                WebSocketMessage.Pong pong = new WebSocketMessage.Pong();
                pong.mPayload = ping.mPayload;
                mWriter.forward(pong);

            } else if (msg.obj instanceof WebSocketMessage.Pong) {

                @SuppressWarnings("unused")
                WebSocketMessage.Pong pong = (WebSocketMessage.Pong) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "WebSockets Pong received");

            } else if (msg.obj instanceof WebSocketMessage.Close) {

                WebSocketMessage.Close close = (WebSocketMessage.Close) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")");

                final int tavendoCloseCode = (close.mCode == 1000) ? ConnectionHandler.CLOSE_NORMAL
                        : ConnectionHandler.CLOSE_CONNECTION_LOST;

                if (mActive) {
                    mWriter.forward(new WebSocketMessage.Close(1000));
                } else {
                    // we've initiated disconnect, so ready to close the channel
                    try {
                        mTransportChannel.close();
                    } catch (IOException e) {
                        if (DEBUG)
                            e.printStackTrace();
                    }
                }

                onClose(tavendoCloseCode, close.mReason);

            } else if (msg.obj instanceof WebSocketMessage.ServerHandshake) {

                WebSocketMessage.ServerHandshake serverHandshake = (WebSocketMessage.ServerHandshake) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "opening handshake received");

                if (serverHandshake.mSuccess) {
                    if (mWsHandler != null) {
                        mWsHandler.onOpen();
                    } else {
                        if (DEBUG)
                            Log.d(TAG, "could not call onOpen() .. handler already NULL");
                    }
                }

            } else if (msg.obj instanceof WebSocketMessage.ConnectionLost) {

                @SuppressWarnings("unused")
                WebSocketMessage.ConnectionLost connnectionLost = (WebSocketMessage.ConnectionLost) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_CONNECTION_LOST, "WebSockets connection lost");

            } else if (msg.obj instanceof WebSocketMessage.ProtocolViolation) {

                @SuppressWarnings("unused")
                WebSocketMessage.ProtocolViolation protocolViolation = (WebSocketMessage.ProtocolViolation) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_PROTOCOL_ERROR,
                        "WebSockets protocol violation");

            } else if (msg.obj instanceof WebSocketMessage.Error) {

                WebSocketMessage.Error error = (WebSocketMessage.Error) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_INTERNAL_ERROR,
                        "WebSockets internal error (" + error.mException.toString() + ")");

            } else if (msg.obj instanceof WebSocketMessage.ServerError) {

                WebSocketMessage.ServerError error = (WebSocketMessage.ServerError) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_SERVER_ERROR,
                        "Server error " + error.mStatusCode + " (" + error.mStatusMessage + ")");

            } else {

                processAppMessage(msg.obj);

            }
        }
    };
}

From source file:com.github.michalbednarski.intentslab.browser.ExtendedPackageInfo.java

public static void getExtendedPackageInfo(Context context, String packageName, final Callback callback) {
    // Ensure this is called from main thread
    if (BuildConfig.DEBUG && Looper.myLooper() != Looper.getMainLooper()) {
        throw new AssertionError("getExtendedPackageInfo called off main thread");
    }/*  w w w . j  av  a 2s.c  o  m*/

    // Prepare cache purging
    PurgeCacheReceiver.registerIfNeeded(context);

    // Get from cache
    ExtendedPackageInfo info;
    info = sPackageCache.get(packageName);

    // Create new if not ready
    boolean createNew = info == null;
    if (createNew) {
        info = new ExtendedPackageInfo(packageName);
        sPackageCache.put(packageName, info);
    }

    // Invoke or schedule callback
    if (info.isReady()) {
        // Info is ready, invoke callback immediately
        callback.onPackageInfoAvailable(info);
    } else {
        // Schedule our callback to be invoked when scan is ready
        info.mRunWhenReadyList.add(callback);

        // If we just created object, initialize it's scan
        if (createNew) {
            (info.new ScanManifestTask(context)).execute();
        }
    }
}

From source file:autobahn.WebSocketConnection.java

/**
 * Create master message handler.//from   w  w w . j  ava2  s.  c o  m
 */
protected void createHandler() {

    mMasterHandler = new Handler(Looper.getMainLooper()) {

        public void handleMessage(Message msg) {

            if (msg.obj instanceof WebSocketMessage.TextMessage) {

                WebSocketMessage.TextMessage textMessage = (WebSocketMessage.TextMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onTextMessage(textMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onTextMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.RawTextMessage) {

                WebSocketMessage.RawTextMessage rawTextMessage = (WebSocketMessage.RawTextMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onRawTextMessage(rawTextMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onRawTextMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.BinaryMessage) {

                WebSocketMessage.BinaryMessage binaryMessage = (WebSocketMessage.BinaryMessage) msg.obj;

                if (mWsHandler != null) {
                    mWsHandler.onBinaryMessage(binaryMessage.mPayload);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "could not call onBinaryMessage() .. handler already NULL");
                }

            } else if (msg.obj instanceof WebSocketMessage.Ping) {

                WebSocketMessage.Ping ping = (WebSocketMessage.Ping) msg.obj;
                if (DEBUG)
                    Log.d(TAG, "WebSockets Ping received");

                // reply with Pong
                WebSocketMessage.Pong pong = new WebSocketMessage.Pong();
                pong.mPayload = ping.mPayload;
                mWriter.forward(pong);

            } else if (msg.obj instanceof WebSocketMessage.Pong) {

                @SuppressWarnings("unused")
                WebSocketMessage.Pong pong = (WebSocketMessage.Pong) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "WebSockets Pong received");

            } else if (msg.obj instanceof WebSocketMessage.Close) {
                System.out.println("Cierra el socket desde el movil");
                WebSocketMessage.Close close = (WebSocketMessage.Close) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")");

                final int tavendoCloseCode = (close.mCode == 1000) ? ConnectionHandler.CLOSE_NORMAL
                        : ConnectionHandler.CLOSE_CONNECTION_LOST;

                if (mActive) {
                    mWriter.forward(new WebSocketMessage.Close(1000));
                    System.out.println("Cierra el socket desde el movil");
                } else {
                    // we've initiated disconnect, so ready to close the channel
                    try {
                        mTransportChannel.close();
                    } catch (IOException e) {
                        if (DEBUG)
                            e.printStackTrace();
                    }
                }

                onClose(tavendoCloseCode, close.mReason);

            } else if (msg.obj instanceof WebSocketMessage.ServerHandshake) {

                WebSocketMessage.ServerHandshake serverHandshake = (WebSocketMessage.ServerHandshake) msg.obj;

                if (DEBUG)
                    Log.d(TAG, "opening handshake received");

                if (serverHandshake.mSuccess) {
                    if (mWsHandler != null) {
                        mWsHandler.onOpen();
                    } else {
                        if (DEBUG)
                            Log.d(TAG, "could not call onOpen() .. handler already NULL");
                    }
                }

            } else if (msg.obj instanceof WebSocketMessage.ConnectionLost) {

                @SuppressWarnings("unused")
                WebSocketMessage.ConnectionLost connnectionLost = (WebSocketMessage.ConnectionLost) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_CONNECTION_LOST, "WebSockets connection lost");

            } else if (msg.obj instanceof WebSocketMessage.ProtocolViolation) {

                @SuppressWarnings("unused")
                WebSocketMessage.ProtocolViolation protocolViolation = (WebSocketMessage.ProtocolViolation) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_PROTOCOL_ERROR,
                        "WebSockets protocol violation");

            } else if (msg.obj instanceof WebSocketMessage.Error) {

                WebSocketMessage.Error error = (WebSocketMessage.Error) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_INTERNAL_ERROR,
                        "WebSockets internal error (" + error.mException.toString() + ")");

            } else if (msg.obj instanceof WebSocketMessage.ServerError) {

                WebSocketMessage.ServerError error = (WebSocketMessage.ServerError) msg.obj;
                failConnection(WebSocketConnectionHandler.CLOSE_SERVER_ERROR,
                        "Server error " + error.mStatusCode + " (" + error.mStatusMessage + ")");

            } else {

                processAppMessage(msg.obj);

            }
        }
    };
}

From source file:android.bus.EventBus.java

/** 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);/*from  w  w w  .ja  va 2 s .c  o m*/

    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(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

From source file:com.facebook.share.internal.LikeActionController.java

private synchronized static void performFirstInitialize() {
    if (isInitialized) {
        return;//from   w w w  . j a  va2 s  . com
    }

    handler = new Handler(Looper.getMainLooper());

    Context appContext = FacebookSdk.getApplicationContext();
    SharedPreferences sharedPreferences = appContext.getSharedPreferences(LIKE_ACTION_CONTROLLER_STORE,
            Context.MODE_PRIVATE);

    objectSuffix = sharedPreferences.getInt(LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY, 1);
    controllerDiskCache = new FileLruCache(TAG, new FileLruCache.Limits());

    registerAccessTokenTracker();

    CallbackManagerImpl.registerStaticCallback(CallbackManagerImpl.RequestCodeOffset.Like.toRequestCode(),
            new CallbackManagerImpl.Callback() {
                @Override
                public boolean onActivityResult(int resultCode, Intent data) {
                    return handleOnActivityResult(CallbackManagerImpl.RequestCodeOffset.Like.toRequestCode(),
                            resultCode, data);
                }
            });

    isInitialized = true;
}