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.digium.respokesdk.RespokeEndpoint.java

/**
 *  Find the presence out of all known connections with the highest priority (most availability)
 *  and set it as the endpoint's resolved presence.
 *///from w  w w . jav  a  2 s. c o m
public void resolvePresence() {
    ArrayList<Object> list = new ArrayList<Object>();

    for (RespokeConnection eachConnection : connections) {
        Object connectionPresence = eachConnection.presence;

        if (null != connectionPresence) {
            list.add(connectionPresence);
        }
    }

    RespokeClient client = null;
    RespokeClient.ResolvePresenceListener resolveListener = null;
    if (null != clientReference) {
        client = clientReference.get();

        if (client != null) {
            resolveListener = client.getResolvePresenceListener();
        }
    }

    if (null != resolveListener) {
        presence = resolveListener.resolvePresence(list);
    } else {
        ArrayList<String> options = new ArrayList<String>();
        options.add("chat");
        options.add("available");
        options.add("away");
        options.add("dnd");
        options.add("xa");
        options.add("unavailable");

        String newPresence = null;
        for (String eachOption : options) {
            for (Object eachObject : list) {
                if (eachObject instanceof String) {
                    String eachObjectString = (String) eachObject;

                    if (eachObjectString.toLowerCase().equals(eachOption)) {
                        newPresence = eachOption;
                    }
                }
            }

            if (null != newPresence) {
                break;
            }
        }

        if (null == newPresence) {
            newPresence = "unavailable";
        }

        presence = newPresence;
    }

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            if (null != listenerReference) {
                Listener listener = listenerReference.get();
                if (null != listener) {
                    listener.onPresence(presence, RespokeEndpoint.this);
                }
            }
        }
    });
}

From source file:Main.java

/**
 * Tell whether current thread is UI(main) thread.
 * @return true for UI(main) thread//from   w w  w.ja v a2s  .c o m
 */
public static boolean isUiThread() {
    return Thread.currentThread().getId() == Looper.getMainLooper().getThread().getId();
}

From source file:com.userhook.util.UHOperation.java

public void registerPushToken(final String deviceToken, int retryCount) {

    Map<String, Object> params = new HashMap<>();
    if (UHUser.getUserId() != null) {
        params.put("user", UHUser.getUserId());
    } else {// ww w  . jav a 2 s  .  c  om

        // we need a userId to register for push messages
        if (retryCount < 2) {

            final int newRetryCount = retryCount++;

            // wait 5 seconds and then try to register
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    registerPushToken(deviceToken, newRetryCount);
                }
            }, 5000);

        }

        return;
    }

    params.put("os", "android");
    params.put("sdk", UserHook.UH_SDK_VERSION);
    params.put("token", deviceToken);
    params.put("timezone_offset", UHDeviceInfo.getTimezoneOffset());

    if (UHUser.getUserId() == null) {
        Log.e(UserHook.TAG, "cannot register push token if user is null");
        return;
    }

    UHPostAsyncTask task = new UHPostAsyncTask(params, new UHAsyncTask.UHAsyncTaskListener() {
        @Override
        public void onSuccess(String result) {

            if (result == null) {
                Log.e("uh", "error registering push token, response was null");
                return;
            }

            try {

                JSONObject json = new JSONObject(result);

                if (json.has("status") && json.getString("status").equalsIgnoreCase("success")
                        && json.getJSONObject("data") != null
                        && json.getJSONObject("data").getBoolean("registered")) {

                    Log.i("uh", "push token registered");

                } else {
                    Log.e("uh", "userhook response status was error for register push token");

                }

            } catch (Exception e) {
                Log.e("uh", "error registering push token", e);

            }

        }
    });

    task.execute(UserHook.UH_API_URL + UH_PATH_PUSH_REGISTER);

}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedComment.java

public void action(final Activity activity, final RedditAPI.RedditAction action) {

    final RedditAccount user = RedditAccountManager.getInstance(activity).getDefaultAccount();

    if (user.isAnonymous()) {
        General.quickToast(activity, "You must be logged in to do that.");
        return;/*from www .ja v a  2 s  . co m*/
    }

    final int lastVoteDirection = voteDirection;

    switch (action) {
    case DOWNVOTE:
        voteDirection = -1;
        break;
    case UNVOTE:
        voteDirection = 0;
        break;
    case UPVOTE:
        voteDirection = 1;
        break;
    }

    refreshView(activity);

    RedditAPI.action(CacheManager.getInstance(activity),
            new APIResponseHandler.ActionResponseHandler(activity) {
                @Override
                protected void onCallbackException(final Throwable t) {
                    throw new RuntimeException(t);
                }

                @Override
                protected void onFailure(final RequestFailureType type, final Throwable t,
                        final StatusLine status, final String readableMessage) {
                    revertOnFailure();
                    if (t != null)
                        t.printStackTrace();

                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            General.showResultDialog(activity, error);
                        }
                    });
                }

                @Override
                protected void onFailure(final APIFailureType type) {
                    revertOnFailure();

                    final RRError error = General.getGeneralErrorForFailure(context, type);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            General.showResultDialog(activity, error);
                        }
                    });
                }

                @Override
                protected void onSuccess() {
                    lastChange = RRTime.utcCurrentTimeMillis();
                    RedditChangeDataManager.getInstance(context).update(src.link_id, user,
                            RedditPreparedComment.this, true);
                    refreshView(activity);
                }

                private void revertOnFailure() {

                    switch (action) {
                    case DOWNVOTE:
                    case UNVOTE:
                    case UPVOTE:
                        voteDirection = lastVoteDirection;
                        break;
                    }
                }

            }, user, idAndType, action, activity);
}

From source file:com.eleybourn.bookcatalogue.utils.SimpleTaskQueueProgressFragment.java

/**
 * Utility routine to display a Toast message or queue it as appropriate.
 * @param id/*from   w  w w .j a  v  a  2s.co m*/
 */
public void showToast(final String message) {
    // Can only display in main thread.
    if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
        synchronized (this) {
            if (this.getActivity() != null) {
                Toast.makeText(this.getActivity(), message, Toast.LENGTH_LONG).show();
            } else {
                // Assume the toast message was sent before the fragment was displayed; this
                // list will be read in onAttach
                if (mMessages == null)
                    mMessages = new ArrayList<String>();
                mMessages.add(message);
            }
        }
    } else {
        // Post() it to main thread.
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                showToast(message);
            }
        });
    }
}

From source file:com.facebook.Settings.java

static void publishInstallAsync(final Context context, final String applicationId,
        final Request.Callback callback) {
    // grab the application context ahead of time, since we will return to the caller immediately.
    final Context applicationContext = context.getApplicationContext();
    Settings.getExecutor().execute(new Runnable() {
        @Override//from  w  w  w.  j a v  a 2  s.  c  o m
        public void run() {
            final Response response = Settings.publishInstallAndWaitForResponse(applicationContext,
                    applicationId);
            if (callback != null) {
                // invoke the callback on the main thread.
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCompleted(response);
                    }
                });
            }
        }
    });
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void checkForHeaderPost(View view) {

    RxANRequest.PostRequestBuilder postRequestBuilder = RxAndroidNetworking
            .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);

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

    RxANRequest rxAnRequest = postRequestBuilder.setTag(this).build();

    rxAnRequest.setAnalyticsListener(new AnalyticsListener() {
        @Override//  www . j a v a 2s.  com
        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);
        }
    });

    rxAnRequest.getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<JSONObject>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : checkForHeaderPost completed");
                }

                @Override
                public void onError(Throwable e) {
                    if (e instanceof ANError) {
                        ANError anError = (ANError) e;
                        if (anError.getErrorCode() != 0) {
                            // received ANError from server
                            // error.getErrorCode() - the ANError code from server
                            // error.getErrorBody() - the ANError body from server
                            // error.getErrorDetail() - just a ANError detail
                            Log.d(TAG, "onError errorCode : " + anError.getErrorCode());
                            Log.d(TAG, "onError errorBody : " + anError.getErrorBody());
                            Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
                        } else {
                            // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                            Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
                        }
                    } else {
                        Log.d(TAG, "onError errorMessage : " + e.getMessage());
                    }
                }

                @Override
                public void onNext(JSONObject response) {
                    Log.d(TAG, "onResponse object : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            });
}

From source file:com.TagFu.facebook.Session.java

Session(final Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy,
        final boolean loadTokenFromCache) {

    // if the application ID passed in is null, try to get it from the
    // meta-data in the manifest.
    if ((context != null) && (applicationId == null)) {
        applicationId = Utility.getMetadataApplicationId(context);
    }//w ww.j  a  va  2 s . com

    Validate.notNull(applicationId, "applicationId");

    initializeStaticContext(context);

    if (tokenCachingStrategy == null) {
        tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(staticContext);
    }

    this.applicationId = applicationId;
    this.tokenCachingStrategy = tokenCachingStrategy;
    this.state = SessionState.CREATED;
    this.pendingAuthorizationRequest = null;
    this.callbacks = new ArrayList<StatusCallback>();
    this.handler = new Handler(Looper.getMainLooper());

    final Bundle tokenState = loadTokenFromCache ? tokenCachingStrategy.load() : null;
    if (TokenCachingStrategy.hasTokenInformation(tokenState)) {
        final Date cachedExpirationDate = TokenCachingStrategy.getDate(tokenState,
                TokenCachingStrategy.EXPIRATION_DATE_KEY);
        final Date now = new Date();

        if ((cachedExpirationDate == null) || cachedExpirationDate.before(now)) {
            // If expired or we require new permissions, clear out the
            // current token cache.
            tokenCachingStrategy.clear();
            this.tokenInfo = AccessToken.createEmptyToken();
        } else {
            // Otherwise we have a valid token, so use it.
            this.tokenInfo = AccessToken.createFromCache(tokenState);
            this.state = SessionState.CREATED_TOKEN_LOADED;
        }
    } else {
        this.tokenInfo = AccessToken.createEmptyToken();
    }
}

From source file:com.example.levelup.core.app.PaymentCodeFragment.java

/**
 * Updates the views to show a given state.
 * /*from w w  w . j  a  v  a 2s.com*/
 * @param uiState one of {@link #UI_STATE_LOADING}, {@link #UI_STATE_ERROR_MESSAGE}, or
 *        {@link #UI_STATE_SHOWING_CODE}.
 */
private void setUiState(int uiState) {
    if (Looper.getMainLooper() != Looper.myLooper()) {
        throw new IllegalStateException("Must be called from main thread");
    }

    int qrCodeVisibility;
    int progressVisibility;
    int errorMessageVisibility;

    switch (uiState) {
    case UI_STATE_LOADING:
        qrCodeVisibility = View.INVISIBLE;
        progressVisibility = View.VISIBLE;
        errorMessageVisibility = View.GONE;
        break;

    case UI_STATE_SHOWING_CODE:
        qrCodeVisibility = View.VISIBLE;
        progressVisibility = View.GONE;
        errorMessageVisibility = View.GONE;
        break;

    case UI_STATE_ERROR_MESSAGE:
        qrCodeVisibility = View.INVISIBLE;
        progressVisibility = View.GONE;
        errorMessageVisibility = View.VISIBLE;
        break;

    default:
        throw new IllegalArgumentException();
    }

    View fragmentView = getView();

    mCodeView.setVisibility(qrCodeVisibility);
    fragmentView.findViewById(R.id.progress).setVisibility(progressVisibility);
    fragmentView.findViewById(R.id.error_message).setVisibility(errorMessageVisibility);
}