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.ruesga.timelinechart.TimelineChartView.java

private void init(Context ctx, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    mUiHandler = new Handler(Looper.getMainLooper(), mMessenger);
    if (!isInEditMode()) {
        mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    }//w w  w.  j  ava  2s  . c  o m

    final Resources res = getResources();
    final Resources.Theme theme = ctx.getTheme();

    mTickFormats = getResources().getStringArray(R.array.tlcDefTickLabelFormats);
    mTickLabels = getResources().getStringArray(R.array.tlcDefTickLabelValues);

    final DisplayMetrics dp = getResources().getDisplayMetrics();
    mSize8 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, dp);
    mSize12 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, dp);
    mSize20 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, dp);

    final ViewConfiguration vc = ViewConfiguration.get(ctx);
    mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
    mTouchSlop = vc.getScaledTouchSlop() / 2;
    mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
    mScroller = new OverScroller(ctx);

    int graphBgColor = ContextCompat.getColor(ctx, R.color.tlcDefGraphBackgroundColor);
    int footerBgColor = ContextCompat.getColor(ctx, R.color.tlcDefFooterBackgroundColor);

    mDefFooterBarHeight = mFooterBarHeight = res.getDimension(R.dimen.tlcDefFooterBarHeight);
    mShowFooter = res.getBoolean(R.bool.tlcDefShowFooter);
    mGraphMode = res.getInteger(R.integer.tlcDefGraphMode);
    mPlaySelectionSoundEffect = res.getBoolean(R.bool.tlcDefPlaySelectionSoundEffect);
    mSelectionSoundEffectSource = res.getInteger(R.integer.tlcDefSelectionSoundEffectSource);
    mAnimateCursorTransition = res.getBoolean(R.bool.tlcDefAnimateCursorTransition);
    mFollowCursorPosition = res.getBoolean(R.bool.tlcDefFollowCursorPosition);
    mAlwaysEnsureSelection = res.getBoolean(R.bool.tlcDefAlwaysEnsureSelection);

    mGraphAreaBgPaint = new Paint();
    mGraphAreaBgPaint.setColor(graphBgColor);
    mFooterAreaBgPaint = new Paint();
    mFooterAreaBgPaint.setColor(footerBgColor);
    mTickLabelFgPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
    mTickLabelFgPaint.setFakeBoldText(true);
    mTickLabelFgPaint.setColor(MaterialPaletteHelper.isDarkColor(footerBgColor) ? Color.LTGRAY : Color.DKGRAY);

    mBarItemWidth = res.getDimension(R.dimen.tlcDefBarItemWidth);
    mBarItemSpace = res.getDimension(R.dimen.tlcDefBarItemSpace);

    TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.tlcTimelineChartView, defStyleAttr,
            defStyleRes);
    try {
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.tlcTimelineChartView_tlcGraphBackground) {
                graphBgColor = a.getColor(attr, graphBgColor);
                mGraphAreaBgPaint.setColor(graphBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcShowFooter) {
                mShowFooter = a.getBoolean(attr, mShowFooter);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBackground) {
                footerBgColor = a.getColor(attr, footerBgColor);
                mFooterAreaBgPaint.setColor(footerBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBarHeight) {
                mFooterBarHeight = a.getDimension(attr, mFooterBarHeight);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcGraphMode) {
                mGraphMode = a.getInt(attr, mGraphMode);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAnimateCursorTransition) {
                mAnimateCursorTransition = a.getBoolean(attr, mAnimateCursorTransition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFollowCursorPosition) {
                mFollowCursorPosition = a.getBoolean(attr, mFollowCursorPosition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAlwaysEnsureSelection) {
                mAlwaysEnsureSelection = a.getBoolean(attr, mAlwaysEnsureSelection);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemWidth) {
                mBarItemWidth = a.getDimension(attr, mBarItemWidth);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemSpace) {
                mBarItemSpace = a.getDimension(attr, mBarItemSpace);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcPlaySelectionSoundEffect) {
                mPlaySelectionSoundEffect = a.getBoolean(attr, mPlaySelectionSoundEffect);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcSelectionSoundEffectSource) {
                mSelectionSoundEffectSource = a.getInt(attr, mSelectionSoundEffectSource);
            }
        }
    } finally {
        a.recycle();
    }

    // SurfaceView requires a background
    if (getBackground() == null) {
        setBackgroundColor(ContextCompat.getColor(ctx, android.R.color.transparent));
    }

    // Minimize the impact of create dynamic layouts by assume that in most case
    // we will have a day formatter
    mTickHasDayFormat = true;

    // Initialize stuff
    setupBackgroundHandler();
    setupTickLabels();
    if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
        setupEdgeEffects();
    }
    setupAnimators();
    setupSoundEffects();

    // Initialize the drawing refs (this will be update when we have
    // the real size of the canvas)
    computeBoundAreas();

    // Create a fake data for the edit mode
    if (isInEditMode()) {
        setupViewInEditMode();
    }
}

From source file:com.networking.ApiTestActivity.java

public void doNotCacheResponse(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).doNotCacheResponse().build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override/* ww w  . j  a  va 2  s .c  om*/
                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);
                }
            }).getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse array : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }

                @Override
                public void onError(ANError error) {
                    if (error.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 : " + error.getErrorCode());
                        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    } else {
                        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    }
                }
            });
}

From source file:com.digium.respokesdk.RespokeClient.java

/**
 * Retrieve the history of messages that have been persisted for 1 or more groups. Only those
 * messages that have been marked to be persisted when sent will show up in the history.
 *
 * @param groupIds The groups to pull history for
 * @param maxMessages The maximum number of messages per group to pull. Must be &gt;= 1
 * @param completionListener The callback called when this async operation has completed
 *//*from w w w  . j ava2  s  . c o  m*/
public void getGroupHistories(final List<String> groupIds, final Integer maxMessages,
        final GroupHistoriesCompletionListener completionListener) {
    if (!isConnected()) {
        getGroupHistoriesError(completionListener,
                "Can't complete request when not connected, " + "Please reconnect!");
        return;
    }

    if ((maxMessages == null) || (maxMessages < 1)) {
        getGroupHistoriesError(completionListener, "maxMessages must be at least 1");
        return;
    }

    if ((groupIds == null) || (groupIds.size() == 0)) {
        getGroupHistoriesError(completionListener, "At least 1 group must be specified");
        return;
    }

    Uri.Builder builder = new Uri.Builder();
    builder.appendQueryParameter("limit", maxMessages.toString());
    for (String id : groupIds) {
        builder.appendQueryParameter("groupIds", id);
    }

    String urlEndpoint = "/v1/group-histories" + builder.build().toString();
    signalingChannel.sendRESTMessage("get", urlEndpoint, null, new RespokeSignalingChannel.RESTListener() {
        @Override
        public void onSuccess(Object response) {
            if (!(response instanceof JSONObject)) {
                getGroupHistoriesError(completionListener, "Invalid response from server");
                return;
            }

            final JSONObject json = (JSONObject) response;
            final HashMap<String, List<RespokeGroupMessage>> results = new HashMap<>();

            for (Iterator<String> keys = json.keys(); keys.hasNext();) {
                final String key = keys.next();

                try {
                    final JSONArray jsonMessages = json.getJSONArray(key);

                    final ArrayList<RespokeGroupMessage> messageList = new ArrayList<>(jsonMessages.length());

                    for (int i = 0; i < jsonMessages.length(); i++) {
                        final JSONObject jsonMessage = jsonMessages.getJSONObject(i);
                        final RespokeGroupMessage message = buildGroupMessage(jsonMessage);
                        messageList.add(message);
                    }

                    results.put(key, messageList);
                } catch (JSONException e) {
                    getGroupHistoriesError(completionListener, "Error parsing JSON response");
                    return;
                }
            }

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (completionListener != null) {
                        completionListener.onSuccess(results);
                    }
                }
            });
        }

        @Override
        public void onError(final String errorMessage) {
            getGroupHistoriesError(completionListener, errorMessage);
        }
    });
}

From source file:com.jerrellmardis.amphitheatre.task.DownloadTaskHelper.java

/**
 * This takes a video object from the database and updates parameters. If this does not
 * have good data, don't touch it. This runs on its own thread by default
 * @param video SugarRecord video object, the one that we want to update
 * @param dtl Listener for when the method finishes, so we can call refresh on the UI thread
 *///  w  w w . j av  a 2 s. c  om
public static void updateSingleVideo(final Video video, final DownloadTaskListener dtl) {
    //TODO Do a check for video's parent and if it is a nameless VOB, use the parent instead
    final Video original = video.clone();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Log.d(TAG, "Run video update");
                Config config = ApiClient.getInstance().createTMDbClient().getConfig();
                if (TextUtils.isEmpty(video.getVideoUrl())
                        || video.getName().toLowerCase().contains(Constants.SAMPLE)) {
                    return;
                }
                Log.d(TAG, "Sending guess for " + video.getName());
                Guess guess = GuessItClient.guess(video.getName());
                Log.d(TAG, "Guess returns " + guess.toString());

                if (guess == null) {
                    Log.d(TAG, "There's nothing here for me");
                    return;
                }

                // if a guess is not found, search again using the parent directory's name
                if (guess != null
                        && (TextUtils.isEmpty(guess.getTitle()) || guess.getTitle().equals(video.getName()))) {

                    String[] sections = video.getVideoUrl().split("/");
                    String name = sections[sections.length - 2];

                    int indexOf = video.getVideoUrl().lastIndexOf(".");
                    String ext = video.getVideoUrl().substring(indexOf, video.getVideoUrl().length());
                    //NO We're NOT going to be doing that.
                    //                        Log.d(TAG, "Guess not found, use parent directory name: "+name+ext);
                    //                        guess = GuessItClient.guess(name + ext);
                    //                    Log.d(TAG, guess.toString());
                }

                video.setCreated(video.getCreated());
                Log.d(TAG, video.getName() + " => " + guess.toString());

                //Don't update video and ragequit
                if (guess == null
                        || (TextUtils.isEmpty(guess.getTitle()) && TextUtils.isEmpty(guess.getSeries()))) {
                    Log.d(TAG, "There's nothing here for me");
                    return;
                }
                if (guess.getTitle().equals("0")) {
                    /*  This means the guess came back undefined
                        If I decided to pursue with the movie request, it would apparently
                        return with Tai Chi Zero as the title. This is not correct, so I cannot
                        pursue with this request.
                    */

                    Log.d(TAG, "There's nothing here for me");
                    return;
                }

                //Not rage quitting; plowing ahead
                video.setName(WordUtils.capitalizeFully(guess.getTitle()));
                //        video.setVideoUrl(video.getVideoUrl());
                video.setIsMovie(guess.getType().contains("movie"));
                if (!guess.getType().contains("movie")) {
                    //tv logic
                    if (!TextUtils.isEmpty(guess.getSeries())) {
                        try {
                            TvShow tvShow = null;
                            Long tmdbId = null;

                            // look for the TV show in the database first
                            List<TvShow> tvShows = TvShow.find(TvShow.class, "original_name = ?",
                                    guess.getSeries());

                            // if a TV show is found, clone it.
                            // if not, run a TMDb search for the TV show
                            if (tvShows != null && !tvShows.isEmpty()) {
                                tvShow = TvShow.copy(tvShows.get(0));
                                tmdbId = tvShow.getTmdbId();
                            } else {
                                SearchResult result;
                                result = ApiClient.getInstance().createTMDbClient()
                                        .findTvShow(guess.getSeries());
                                if (result == null) {
                                    result = ApiClient.getInstance().createTVDBClient()
                                            .findTvShow(guess.getSeries());
                                }
                                if (result.getResults() != null && !result.getResults().isEmpty()) {
                                    tmdbId = result.getResults().get(0).getId();
                                    tvShow = ApiClient.getInstance().createTMDbClient().getTvShow(tmdbId);
                                    if (tvShow == null) {
                                        tvShow = ApiClient.getInstance().createTVDBClient().getTvShow(tmdbId);
                                    }
                                    tvShow.setTmdbId(tmdbId);
                                    tvShow.setId(null);
                                    tvShow.setFlattenedGenres(StringUtils.join(tvShow.getGenres(), ","));
                                }
                            }

                            if (tmdbId != null) {
                                // get the Episode information
                                if (guess.getEpisodeNumber() != null && guess.getSeason() != null) {
                                    Episode episode;
                                    episode = ApiClient.getInstance().createTMDbClient().getEpisode(
                                            tvShow.getTmdbId(), guess.getSeason(), guess.getEpisodeNumber());
                                    if (episode == null) {
                                        episode = ApiClient.getInstance().createTVDBClient()
                                                .getEpisode(tvShow.getId(), tvShow.getEpisode().getAirDate());
                                    }
                                    if (episode != null) {
                                        if (!TextUtils.isEmpty(episode.getStillPath())) {
                                            String stillPathUrl = config.getImages().getBase_url() + "original"
                                                    + episode.getStillPath();
                                            episode.setStillPath(stillPathUrl);
                                        }

                                        episode.setTmdbId(tmdbId);
                                        episode.setId(null);

                                        episode.save();
                                        tvShow.setEpisode(episode);
                                        video.setIsMatched(true);
                                    }
                                }

                                tvShow.save();

                                video.setName(tvShow.getOriginalName());
                                video.setOverview(tvShow.getOverview());
                                video.setTvShow(tvShow);
                                video.setIsMatched(true);
                                video.setDuration(30 * 60 * 1000);

                                String cardImageUrl = config.getImages().getBase_url() + "original"
                                        + tvShow.getPosterPath();
                                video.setCardImageUrl(cardImageUrl);

                                String bgImageUrl = config.getImages().getBase_url() + "original"
                                        + tvShow.getBackdropPath();
                                video.setBackgroundImageUrl(bgImageUrl);
                            }
                        } catch (Exception e) {
                            //Too many requests, return in 30 seconds
                            if (e.getMessage().contains("429")) {
                                //Too many requests, return in 15+x seconds
                                synchronized (this) {
                                    try {
                                        long wait = 1000 * 15 + Math.round(15000 * Math.random());
                                        Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s");
                                        this.wait(wait);
                                        updateSingleVideo(original, dtl);
                                    } catch (Exception E2) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                Log.e(TAG, e.getMessage() + "");
                                e.printStackTrace();
                            }
                            //                                return;
                        }
                    }

                    video.save();
                } else {
                    //movie logic
                    if (!TextUtils.isEmpty(guess.getTitle())) {
                        try {
                            // search for the movie
                            SearchResult result = ApiClient.getInstance().createTMDbClient()
                                    .findMovie(guess.getTitle(), guess.getYear());

                            // if found, get the detailed info for the movie
                            if (result.getResults() != null && !result.getResults().isEmpty()) {
                                Long id = result.getResults().get(0).getId();

                                if (id != null) {
                                    Movie movie;
                                    movie = ApiClient.getInstance().createTMDbClient().getMovie(id);
                                    if (movie == null) {
                                        movie = ApiClient.getInstance().createTVDBClient().getMovie(id);
                                    }
                                    movie.setTmdbId(id);
                                    movie.setId(null);
                                    movie.setFlattenedGenres(StringUtils.join(movie.getGenres(), ","));
                                    movie.setFlattenedProductionCompanies(
                                            StringUtils.join(movie.getProductionCompanies(), ","));
                                    movie.save();

                                    video.setOverview(movie.getOverview());
                                    video.setName(movie.getTitle());
                                    video.setIsMatched(true);
                                    video.setMovie(movie);
                                    if (movie != null)
                                        video.setDuration(movie.getRuntime());
                                }

                                String cardImageUrl = config.getImages().getBase_url() + "original"
                                        + result.getResults().get(0).getPoster_path();
                                video.setCardImageUrl(cardImageUrl);

                                String bgImageUrl = config.getImages().getBase_url() + "original"
                                        + result.getResults().get(0).getBackdrop_path();
                                video.setBackgroundImageUrl(bgImageUrl);
                            }
                        } catch (Exception e) {

                            if (e.getMessage().contains("429")) {
                                //Too many requests, return in 15+x seconds
                                synchronized (this) {
                                    try {
                                        long wait = 1000 * 15 + Math.round(15000 * Math.random());
                                        Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s");
                                        this.wait(wait);
                                        updateSingleVideo(original, dtl);
                                    } catch (Exception E2) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                Log.e(TAG, e.getMessage() + "");
                                e.printStackTrace();
                            }
                            //                                return;
                        }
                    }

                    video.save();
                }
                Log.d("amp:DownloadTaskHelper", video.toString());
                Handler h = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.d(TAG, "Updated video info: " + video.toString());
                        if (dtl != null)
                            dtl.onDownloadFinished();
                    }
                };
                h.sendEmptyMessage(0);
            } catch (Exception e) {
                /*
                8510-9779/com.jerrellmardis.amphitheatre.dev E/AndroidRuntime? FATAL EXCEPTION: Thread-3591
                Process: com.jerrellmardis.amphitheatre.dev, PID: 8510
                retrofit.RetrofitError: 429
                 */
                //                    Log.e(TAG, e.getMessage());
                if (e.getMessage().contains("429")) {
                    //Too many requests, return in 30 seconds
                    synchronized (this) {
                        try {
                            long wait = 1000 * 15 + Math.round(15000 * Math.random());
                            Log.d(TAG, "Delay " + original.getName() + " by " + wait + "s");
                            this.wait(wait);
                            updateSingleVideo(original, dtl);
                        } catch (Exception E2) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Log.e(TAG, "Ran into error " + e.getMessage());
                }
                //                    return;
            }
        }
    }).start();
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void getResponseOnlyIfCached(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).getResponseOnlyIfCached()
            .build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*  w  w  w .ja v  a 2 s  .c  om*/
                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);
                }
            }).getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() {
                @Override
                public void onResponse(Response okHttpResponse, JSONArray 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.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public void refreshView(final Context context) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            rebuildSubtitle(context);/*from  w  w  w. ja v  a  2 s  . c o  m*/
            if (boundView != null) {
                boundView.updateAppearance();
                boundView.requestLayout();
                boundView.invalidate();
            }
        }
    });
}

From source file:com.android.yijiang.kzx.http.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the passed Context.
 * <p>&nbsp;</p> <b>Note:</b> This will only affect requests which were created with a non-null
 * android Context. This method is intended to be used in the onDestroy method of your android
 * activities to destroy all requests which are no longer required.
 *
 * @param context               the android Context instance associated to the request.
 * @param mayInterruptIfRunning specifies if active requests should be cancelled along with
 *                              pending requests.
 *///from w  w  w  . j  a v a 2s.  c  o m
public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) {
    if (context == null) {
        Log.e(LOG_TAG, "Passed null Context to cancelRequests");
        return;
    }
    Runnable r = new Runnable() {
        @Override
        public void run() {
            List<RequestHandle> requestList = requestMap.get(context);
            if (requestList != null) {
                for (RequestHandle requestHandle : requestList) {
                    requestHandle.cancel(mayInterruptIfRunning);
                }
                requestMap.remove(context);
            }
        }
    };
    if (Looper.myLooper() == Looper.getMainLooper()) {
        new Thread(r).start();
    } else {
        r.run();
    }
}

From source file:com.android.mail.browse.ConversationCursor.java

static boolean offUiThread() {
    return Looper.getMainLooper().getThread() != Thread.currentThread();
}

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

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

    if (RedditAccountManager.getInstance(activity).getDefaultAccount().isAnonymous()) {

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                Toast.makeText(activity, "You must be logged in to do that.", Toast.LENGTH_SHORT).show();
            }/*from ww  w  .  j  a v  a 2  s  .c o m*/
        });

        return;
    }

    final int lastVoteDirection = voteDirection;

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

    case SAVE:
        saved = true;
        break;
    case UNSAVE:
        saved = false;
        break;

    case HIDE:
        hidden = true;
        break;
    case UNHIDE:
        hidden = false;
        break;

    case REPORT:
        hidden = true;
        break;

    default:
        throw new RuntimeException("Unknown post action");
    }

    refreshView(activity);

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

    RedditAPI.action(CacheManager.getInstance(activity),
            new APIResponseHandler.ActionResponseHandler(activity) {
                @Override
                protected void onCallbackException(final Throwable t) {
                    BugReportActivity.handleGlobalError(context, 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(
                            parentSubreddit == null ? null : parentSubreddit.url, user, RedditPreparedPost.this,
                            true);
                }

                private void revertOnFailure() {

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

                    case SAVE:
                        saved = false;
                        break;
                    case UNSAVE:
                        saved = true;
                        break;

                    case HIDE:
                        hidden = false;
                        break;
                    case UNHIDE:
                        hidden = true;
                        break;

                    case REPORT:
                        hidden = false;
                        break;

                    default:
                        throw new RuntimeException("Unknown post action");
                    }

                    refreshView(context);
                }

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

From source file:com.networking.ApiTestActivity.java

public void getResponseOnlyIfCached(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).getResponseOnlyIfCached()
            .build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*from w w  w .  j  a  va2  s .  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);
                }
            }).getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse array : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }

                @Override
                public void onError(ANError error) {
                    if (error.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 : " + error.getErrorCode());
                        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    } else {
                        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    }
                }
            });
}