Example usage for android.os Handler post

List of usage examples for android.os Handler post

Introduction

In this page you can find the example usage for android.os Handler post.

Prototype

public final boolean post(Runnable r) 

Source Link

Document

Causes the Runnable r to be added to the message queue.

Usage

From source file:com.nttec.everychan.cache.BitmapCache.java

/**
 *   ?  ?  ImageView.<br>/*from  www  .  j  av  a  2s  .  c  o m*/
 * ? ImageView ??? ?:<ul>
 * <li>? ? ? ,  ?  (? ??,   )</li>
 * <li> {@link Boolean#TRUE},    ?</li>
 * <li> {@link Boolean#FALSE},      ( ?   downloadFromInternet == false)</li></ul>
 * @param hash ? ( ? )
 * @param url ? URL (?  ?)
 * @param maxSize ?   ??,     ,  0, ? ?? ?  ?
 * @param chan   ? ??   
 * @param zipFile - - ?  ? ?  (  null)
 * @param task ?? 
 * @param imageView  {@link ImageView},    
 * @param executor ? ?
 * @param handler Handler UI 
 * @param downloadFromInternet     
 * @param defaultResId ID ?? ?  , ?    ( ?  downloadFromInternet == false),
 *  0 - ?    
 */
public void asyncGet(String hash, String url, int maxSize, ChanModule chan, ReadableContainer zipFile,
        CancellableTask task, ImageView imageView, Executor executor, Handler handler,
        boolean downloadFromInternet, int defaultResId) {
    if (hash == null) {
        Logger.e(TAG, "received null hash for url: " + url);
        imageView.setTag(Boolean.FALSE);
        imageView.setImageResource(defaultResId);
        return;
    }
    Bitmap fromLru = getFromMemory(hash);
    if (fromLru != null) {
        imageView.setTag(Boolean.TRUE);
        imageView.setImageBitmap(fromLru);
        return;
    } else {
        imageView.setImageBitmap(EMPTY_BMP);
    }
    class ImageDownloader implements Runnable {
        private final String hash;
        private final String url;
        private final int maxSize;
        private final ChanModule chan;
        private final ReadableContainer zipFile;
        private final CancellableTask task;
        private final ImageView imageView;
        private final Handler handler;
        private final boolean downloadFromInternet;
        private final int defaultResId;

        public ImageDownloader(String hash, String url, int maxSize, ChanModule chan, ReadableContainer zipFile,
                CancellableTask task, ImageView imageView, Handler handler, boolean downloadFromInternet,
                int defaultResId) {
            this.hash = hash;
            this.url = url;
            this.maxSize = maxSize;
            this.chan = chan;
            this.zipFile = zipFile;
            this.task = task;
            this.imageView = imageView;
            this.handler = handler;
            this.downloadFromInternet = downloadFromInternet;
            this.defaultResId = defaultResId;
        }

        private Bitmap bmp;

        @Override
        public void run() {
            bmp = getFromCache(hash);
            if (bmp == null && zipFile != null)
                bmp = getFromContainer(hash, zipFile);
            if (bmp == null && downloadFromInternet) {
                bmp = download(hash, url, maxSize, chan, task);
            }
            if (task != null && task.isCancelled())
                return;
            if (imageView.getTag() == null || !imageView.getTag().equals(hash))
                return;
            if (bmp == null) {
                if (defaultResId == 0) {
                    imageView.setTag(Boolean.FALSE);
                    return;
                }
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (imageView.getTag() == null || !imageView.getTag().equals(hash))
                            return;
                        if (bmp != null) {
                            imageView.setTag(Boolean.TRUE);
                            imageView.setImageBitmap(bmp);
                        } else {
                            imageView.setTag(Boolean.FALSE);
                            imageView.setImageResource(defaultResId);
                        }
                    } catch (OutOfMemoryError oom) {
                        MainApplication.freeMemory();
                        Logger.e(TAG, oom);
                    }
                }
            });
        }
    }
    if (task != null && task.isCancelled())
        return;
    imageView.setTag(hash);
    executor.execute(new ImageDownloader(hash, url, maxSize, chan, zipFile, task, imageView, handler,
            downloadFromInternet, defaultResId));
}

From source file:edumsg.edumsg_android_app.RVAdapter.java

@Override
public void onBindViewHolder(final TweetViewHolder holder, final int position) {
    View hoverView = LayoutInflater.from(context).inflate(R.layout.tweet_hover_view, null);
    ButterKnife.bind(this, hoverView);
    holder.tweetBlurLayout.setHoverView(hoverView);
    holder.tweetBlurLayout.addChildAppearAnimator(hoverView, R.id.retweet_button, Techniques.FlipInX);
    holder.tweetBlurLayout.addChildAppearAnimator(hoverView, R.id.reply_button, Techniques.FlipInX);
    holder.tweetBlurLayout.addChildAppearAnimator(hoverView, R.id.favorite_button, Techniques.FlipInX);
    holder.tweetBlurLayout.addChildAppearAnimator(hoverView, R.id.more_button, Techniques.FlipInX);
    holder.tweetBlurLayout.addChildDisappearAnimator(hoverView, R.id.retweet_button, Techniques.FlipOutX);
    holder.tweetBlurLayout.addChildDisappearAnimator(hoverView, R.id.reply_button, Techniques.FlipOutX);
    holder.tweetBlurLayout.addChildDisappearAnimator(hoverView, R.id.favorite_button, Techniques.FlipOutX);
    holder.tweetBlurLayout.addChildDisappearAnimator(hoverView, R.id.more_button, Techniques.FlipOutX);
    try {/*from   w ww .ja  v a 2 s  .  co  m*/
        holder.tweetBlurLayout.dismissHover();
    } catch (Exception e) {
    }
    final Tweet tweetObject = tweetObjects.get(position);
    holder.repliesProgress.setIndeterminate(true);
    Picasso.with(context).load(tweetObject.getImgUrl()).placeholder(R.mipmap.ic_launcher).fit()
            .into(holder.userImage);
    holder.userImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyAppCompatActivity main = (MyAppCompatActivity) context;
            Intent intent = new Intent(main, ProfileActivity.class);
            intent.putExtra("username", tweetObject.getCreator().getUsername());
            //                intent.putExtra("name", tweetObject.getCreator().getName());
            //                intent.putExtra("avatar_url", tweetObject.getCreator().getAvatar_url());
            //                intent.putExtra("bio", tweetObject.getCreator().getBio());
            intent.putExtra("creatorId", tweetObject.getCreator().getId());
            main.startActivity(intent);
        }
    });
    String info = context.getString(R.string.user_info, tweetObject.getCreator().getName(),
            tweetObject.getCreator().getUsername());
    holder.creatorInfo.setText(info);
    holder.tweet.setText(tweetObject.getTweet());
    replyBtn.setColorFilter(Color.rgb(128, 128, 128));
    setButtonStates(tweetObject, retweetBtn, favoriteBtn);
    retweetBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                retweet(tweetObject.getId());
                tweetObject.setIsRetweeted(true);
            } else {
                unretweet(tweetObject.getId());
                tweetObject.setIsRetweeted(false);
            }
        }
    });
    //        retweetBtn.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    ////                String btnTag = (String) retweetBtn.getTag();
    //                if (!retweetBtn.isChecked()) {
    //                    retweetBtn.setChecked(true);
    //                    retweet(tweetObject.getId());
    //                    tweetObject.setIsRetweeted(true);
    //                    int colorFilter2 = Color.rgb(111, 229, 98);
    ////                    retweetBtn.setColorFilter(colorFilter2);
    ////                    retweetBtn.setTag("R");
    //                } else {
    //                    retweetBtn.setChecked(false);
    //                    unretweet(tweetObject.getId());
    //                    tweetObject.setIsRetweeted(false);
    //                    int colorFilter1 = Color.rgb(128, 128, 128);
    ////                    retweetBtn.setColorFilter(colorFilter1);
    ////                    retweetBtn.setTag("notR");
    //                }
    //            }
    //        });
    if (tweetObject.getCreator().getUsername().equals(MyAppCompatActivity.username)) {
        //            retweetBtn.setColorFilter(Color.rgb(210, 210, 210));
        retweetBtn.setClickable(false);
    }
    favoriteBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                favorite(tweetObject.getId());
                tweetObject.setIsFavorited(true);
            } else {
                unfavorite(tweetObject.getId());
                tweetObject.setIsFavorited(false);
            }
        }
    });
    //        favoriteBtn.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //
    ////                String btnTag = (String) favoriteBtn.getTag();
    //                if (!favoriteBtn.isChecked()) {
    //                    favoriteBtn.setChecked(true);
    //                    favorite(tweetObject.getId());
    //                    tweetObject.setIsFavorited(true);
    //                    int colorFilter2 = Color.rgb(128, 128, 128);
    ////                    favoriteBtn.setColorFilter(colorFilter2);
    //                    favoriteBtn.setTag("F");
    //                } else {
    //                    favoriteBtn.setChecked(false);
    //                    unfavorite(tweetObject.getId());
    //                    tweetObject.setIsFavorited(false);
    //                    int colorFilter1 = Color.rgb(206, 45, 79);
    ////                    favoriteBtn.setColorFilter(colorFilter1);
    //                    favoriteBtn.setTag("notF");
    //                }
    //            }
    //        });

    replyBtn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                replyBtn.setColorFilter(Color.rgb(55, 58, 60));
                return true;
            case MotionEvent.ACTION_UP:
                holder.tweetBlurLayout.toggleHover();
                replyBtn.setColorFilter(Color.rgb(128, 128, 128));
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                final EditText input = new EditText(context);
                input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                input.setLines(4);
                input.setSingleLine(false);
                input.setBackgroundDrawable(null);
                builder.setView(input);
                builder.setPositiveButton("Reply", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        reply(tweetObject.getId(), input.getText().toString());
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        Button posBtn = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                        posBtn.setBackgroundColor(cPrimary);
                        posBtn.setTextColor(Color.WHITE);
                        final float scale = context.getApplicationContext().getResources()
                                .getDisplayMetrics().density;
                        int pixels = (int) (10 * scale + 0.5f);
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, 0, pixels, 0);
                        posBtn.setLayoutParams(layoutParams);
                        Button negBtn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                        negBtn.setBackgroundColor(cPrimary);
                        negBtn.setTextColor(Color.WHITE);
                    }
                });
                dialog.show();
                return true;
            }
            return false;
        }
    });
    moreBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //                holder.tweetBlurLayout.toggleHover();
            if (holder.repliesLayout.getVisibility() == View.VISIBLE) {
                holder.repliesLayout.setVisibility(View.GONE);
            } else {
                MyAppCompatActivity main = (MyAppCompatActivity) context;
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("queue", "TWEET");
                jsonParams.put("method", "get_earliest_replies");
                jsonParams.put("tweet_id", tweetObject.getId() + "");
                jsonParams.put("session_id", sessionId);
                JSONObject jsonRequest = new JSONObject(jsonParams);
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                        MainActivity.requestUrl, jsonRequest, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(final JSONObject response) {
                                final ObjectMapper mapper = new ObjectMapper();
                                try {
                                    final Map<String, Object> responseMap = mapper.readValue(
                                            response.toString(), new TypeReference<HashMap<String, Object>>() {
                                            });
                                    if (responseMap.get("code").equals("200")) {
                                        ArrayList repliesMap = (ArrayList) responseMap.get("earliest_replies");
                                        ArrayList<Tweet> replies = getEarliestReplies(repliesMap);
                                        tweetObject.setReplies(replies);
                                        if (!replies.isEmpty()) {
                                            Tweet firstReply = replies.get(0);
                                            holder.reply1.setText(firstReply.getTweet());
                                            String info = context.getString(R.string.user_info,
                                                    firstReply.getCreator().getName(),
                                                    firstReply.getCreator().getUsername());
                                            holder.replyCreatorInfo1.setText(info);
                                            Picasso.with(context).load(firstReply.getCreator().getAvatar_url())
                                                    .placeholder(R.mipmap.ic_launcher).fit()
                                                    .into(holder.replyUserImg1);
                                            holder.replyBtn1.setColorFilter(Color.rgb(128, 128, 128));
                                            //                                        setButtonStates(firstReply, holder.retweetBtn1, holder.favoriteBtn1);

                                            if (replies.size() > 1) {
                                                Tweet secondReply = replies.get(1);
                                                holder.reply2.setText(secondReply.getTweet());
                                                info = context.getString(R.string.user_info,
                                                        secondReply.getCreator().getName(),
                                                        secondReply.getCreator().getUsername());
                                                holder.replyCreatorInfo2.setText(info);
                                                Picasso.with(context)
                                                        .load(secondReply.getCreator().getAvatar_url())
                                                        .placeholder(R.mipmap.ic_launcher).fit()
                                                        .into(holder.replyUserImg2);
                                                holder.replyBtn2.setColorFilter(Color.rgb(128, 128, 128));
                                                //                                            setButtonStates(secondReply, holder.retweetBtn2, holder.favoriteBtn2);
                                                holder.replyLayout2.setVisibility(View.VISIBLE);
                                            }
                                            if (replies.size() > 2) {
                                                Tweet thirdReply = replies.get(2);
                                                holder.reply3.setText(thirdReply.getTweet());
                                                info = context.getString(R.string.user_info,
                                                        thirdReply.getCreator().getName(),
                                                        thirdReply.getCreator().getUsername());
                                                holder.replyCreatorInfo3.setText(info);
                                                Picasso.with(context)
                                                        .load(thirdReply.getCreator().getAvatar_url())
                                                        .placeholder(R.mipmap.ic_launcher).fit()
                                                        .into(holder.replyUserImg3);
                                                holder.replyBtn3.setColorFilter(Color.rgb(128, 128, 128));
                                                //                                            setButtonStates(thirdReply, holder.retweetBtn3, holder.favoriteBtn3);
                                                holder.replyLayout3.setVisibility(View.VISIBLE);
                                            }
                                            if (replies.size() > 3) {
                                                holder.showMoreBtn.setVisibility(View.VISIBLE);
                                            }
                                            holder.repliesProgress.setVisibility(View.GONE);
                                            holder.repliesLayout.setVisibility(View.VISIBLE);
                                        } else {
                                            holder.repliesProgress.setVisibility(View.GONE);
                                            holder.repliesLayout.setVisibility(View.GONE);
                                        }
                                    }
                                } catch (Exception e) {
                                    //                                Log.e("JSONMapper", e.getMessage());
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                if (volleyError.networkResponse != null
                                        && volleyError.networkResponse.data != null
                                        && volleyError.networkResponse.statusCode == 400) {
                                    try {
                                        String errorJson = new String(volleyError.networkResponse.data);
                                        JSONObject errorObj = new JSONObject(errorJson);
                                        String error = errorObj.getString("message");
                                    } catch (JSONException e) {
                                        //                                    Log.e("Response Error Msg", e.getMessage());
                                    }
                                } else {
                                    //                                Log.e("Volley", volleyError.toString());
                                }
                            }
                        }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "application/json; charset=utf-8");
                        return headers;
                    }

                    ;
                };
                jsonObjectRequest.setTag("Request");
                main.getVolleyRequestQueue().add(jsonObjectRequest);
                holder.repliesProgress.setVisibility(View.VISIBLE);
            }
        }
    });

    final Handler handler = new Handler();
    holder.replyBtn1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                holder.replyBtn1.setColorFilter(Color.rgb(55, 58, 60));
                return true;
            case MotionEvent.ACTION_UP:
                holder.replyBtn1.setColorFilter(Color.rgb(128, 128, 128));
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                final EditText input = new EditText(context);
                input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                input.setLines(4);
                input.setSingleLine(false);
                input.setBackgroundDrawable(null);
                builder.setView(input);
                builder.setPositiveButton("Reply", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (holder.replyBtn1.getVisibility() == View.VISIBLE) {
                                    while (tweetObject.getReplies() == null)
                                        ;
                                    reply(tweetObject.getReplies().get(0).getId(), input.getText().toString());
                                }
                            }
                        });
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setBackgroundColor(cPrimary);
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(cPrimary);
                    }
                });
                dialog.show();
                return true;
            }
            return false;
        }
    });

    holder.replyBtn2.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                holder.replyBtn2.setColorFilter(Color.rgb(55, 58, 60));
                return true;
            case MotionEvent.ACTION_UP:
                holder.replyBtn2.setColorFilter(Color.rgb(128, 128, 128));
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                final EditText input = new EditText(context);
                input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                input.setLines(4);
                input.setSingleLine(false);
                input.setBackgroundDrawable(null);
                builder.setView(input);
                builder.setPositiveButton("Reply", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (holder.replyBtn2.getVisibility() == View.VISIBLE) {
                                    while (tweetObject.getReplies() == null)
                                        ;
                                    reply(tweetObject.getReplies().get(1).getId(), input.getText().toString());
                                }
                            }
                        });
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setBackgroundColor(cPrimary);
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(cPrimary);
                    }
                });
                dialog.show();
                return true;
            }
            return false;
        }
    });

    holder.replyBtn3.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                holder.replyBtn3.setColorFilter(Color.rgb(55, 58, 60));
                return true;
            case MotionEvent.ACTION_UP:
                holder.replyBtn3.setColorFilter(Color.rgb(128, 128, 128));
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                final EditText input = new EditText(context);
                input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                input.setLines(4);
                input.setSingleLine(false);
                input.setBackgroundDrawable(null);
                builder.setView(input);
                builder.setPositiveButton("Reply", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (holder.replyBtn3.getVisibility() == View.VISIBLE) {
                                    while (tweetObject.getReplies() == null)
                                        ;
                                    reply(tweetObject.getReplies().get(2).getId(), input.getText().toString());
                                }
                            }
                        });
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setBackgroundColor(cPrimary);
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(cPrimary);
                    }
                });
                dialog.show();
                return true;
            }
            return false;
        }
    });

    holder.retweetBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.retweetBtn1.getTag();
            if (holder.retweetBtn1.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(0);
                        if (btnTag.equals("notR")) {
                            retweet(reply.getId());
                            reply.setIsRetweeted(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.retweetBtn1.setColorFilter(colorFilter2);
                            holder.retweetBtn1.setTag("R");
                        } else if (btnTag.equals("R")) {
                            unretweet(reply.getId());
                            reply.setIsRetweeted(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.retweetBtn1.setColorFilter(colorFilter1);
                            holder.retweetBtn1.setTag("notR");
                        }
                    }
                });
            }
        }
    });
    holder.favoriteBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.favoriteBtn1.getTag();
            if (holder.favoriteBtn1.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(0);
                        if (btnTag.equals("notF")) {
                            favorite(reply.getId());
                            reply.setIsFavorited(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.favoriteBtn1.setColorFilter(colorFilter2);
                            holder.favoriteBtn1.setTag("F");
                        } else if (btnTag.equals("F")) {
                            unfavorite(reply.getId());
                            reply.setIsFavorited(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.favoriteBtn1.setColorFilter(colorFilter1);
                            holder.favoriteBtn1.setTag("notF");
                        }
                    }
                });
            }
        }
    });

    holder.retweetBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.retweetBtn2.getTag();
            if (holder.retweetBtn2.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(1);
                        if (btnTag.equals("notR")) {
                            retweet(reply.getId());
                            reply.setIsRetweeted(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.retweetBtn2.setColorFilter(colorFilter2);
                            holder.retweetBtn2.setTag("R");
                        } else if (btnTag.equals("R")) {
                            unretweet(reply.getId());
                            reply.setIsRetweeted(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.retweetBtn2.setColorFilter(colorFilter1);
                            holder.retweetBtn2.setTag("notR");
                        }
                    }
                });
            }
        }
    });
    holder.favoriteBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.favoriteBtn2.getTag();
            if (holder.favoriteBtn2.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(1);
                        if (btnTag.equals("notF")) {
                            favorite(reply.getId());
                            reply.setIsFavorited(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.favoriteBtn2.setColorFilter(colorFilter2);
                            holder.favoriteBtn2.setTag("F");
                        } else if (btnTag.equals("F")) {
                            unfavorite(reply.getId());
                            reply.setIsFavorited(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.favoriteBtn2.setColorFilter(colorFilter1);
                            holder.favoriteBtn2.setTag("notF");
                        }
                    }
                });
            }
        }
    });

    holder.retweetBtn3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.retweetBtn3.getTag();
            if (holder.retweetBtn3.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(2);
                        if (btnTag.equals("notR")) {
                            retweet(reply.getId());
                            reply.setIsRetweeted(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.retweetBtn3.setColorFilter(colorFilter2);
                            holder.retweetBtn3.setTag("R");
                        } else if (btnTag.equals("R")) {
                            unretweet(reply.getId());
                            reply.setIsRetweeted(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.retweetBtn3.setColorFilter(colorFilter1);
                            holder.retweetBtn3.setTag("notR");
                        }
                    }
                });
            }
        }
    });
    holder.favoriteBtn3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String btnTag = (String) holder.favoriteBtn3.getTag();
            if (holder.favoriteBtn3.getVisibility() == View.VISIBLE) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        while (tweetObject.getReplies() == null)
                            ;
                        Tweet reply = tweetObject.getReplies().get(2);
                        if (btnTag.equals("notF")) {
                            favorite(reply.getId());
                            reply.setIsFavorited(true);
                            int colorFilter2 = Color.rgb(0, 0, 0);
                            holder.favoriteBtn3.setColorFilter(colorFilter2);
                            holder.favoriteBtn3.setTag("F");
                        } else if (btnTag.equals("F")) {
                            unfavorite(reply.getId());
                            reply.setIsFavorited(false);
                            int colorFilter1 = Color.rgb(128, 128, 128);
                            holder.favoriteBtn3.setColorFilter(colorFilter1);
                            holder.favoriteBtn3.setTag("notF");
                        }
                    }
                });
            }
        }
    });

    holder.showMoreBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyAppCompatActivity main = (MyAppCompatActivity) context;
            FragmentManager fragmentManager = main.getSupportFragmentManager();
            MainActivityFragment mainActivityFragment = new MainActivityFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("tweetId", tweetObject.getId());
            bundle.putString("username", MyAppCompatActivity.username);
            bundle.putString("sessionId", main.getSessionId());
            mainActivityFragment.setArguments(bundle);
            fragmentManager.beginTransaction().add(android.R.id.content, mainActivityFragment)
                    .addToBackStack("replies").commit();
        }
    });
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * Resend the unsent messages//from  w w w. j  a  v a 2s. com
 */
public void resendUnsentMessages() {
    // check if the call is done in the right thread
    if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {
            @Override
            public void run() {
                resendUnsentMessages();
            }
        });

        return;
    }

    List<Event> unsent = getUnsentMessages();

    if (unsent.size() > 0) {
        mResendingEventsList = new ArrayList<>(unsent);

        // reset the timestamp
        for (Event event : mResendingEventsList) {
            event.mSentState = Event.SentState.UNSENT;
        }

        resend(mResendingEventsList.get(0));
        mResendingEventsList.remove(0);
    }
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * The media upload fails./*from  www.j av a2  s  .  c o  m*/
 *
 * @param serverResponseCode the response code.
 * @param serverErrorMessage the error message.
 * @param messageRow         the messageRow
 */
private void commonMediaUploadError(int serverResponseCode, final String serverErrorMessage,
        final MessageRow messageRow) {
    // warn the user that the media upload fails
    if (serverResponseCode == 500) {
        Timer relaunchTimer = new Timer();
        mPendingRelaunchTimersByEventId.put(messageRow.getEvent().eventId, relaunchTimer);
        relaunchTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mPendingRelaunchTimersByEventId.containsKey(messageRow.getEvent().eventId)) {
                    mPendingRelaunchTimersByEventId.remove(messageRow.getEvent().eventId);

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            resend(messageRow.getEvent());
                        }
                    });
                }
            }
        }, 1000);
    } else {
        messageRow.getEvent().mSentState = Event.SentState.UNDELIVERABLE;
        onMessageSendingFailed(messageRow.getEvent());

        if (null != getActivity()) {
            Toast.makeText(getActivity(), (null != serverErrorMessage) ? serverErrorMessage
                    : getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG).show();
        }
    }
}

From source file:com.filemanager.free.activities.MainActivity.java

void sendScroll(final HorizontalScrollView scrollView) {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override//from w  ww  .j  a  v a 2 s  .c o m
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignored) {
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_RIGHT);
                }
            });
        }
    }).start();
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * Resend an event.// w  w  w.ja  va 2 s  .  c o  m
 *
 * @param event the event to resend.
 */
protected void resend(final Event event) {
    // sanity check
    // should never happen but got it in a GA issue
    if (null == event.eventId) {
        Log.e(LOG_TAG, "resend : got an event with a null eventId");
        return;
    }

    // check if the call is done in the right thread
    if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {
            @Override
            public void run() {
                resend(event);
            }
        });

        return;
    }

    // update the timestamp
    event.originServerTs = System.currentTimeMillis();

    // remove the event
    getSession().getDataHandler().deleteRoomEvent(event);
    mAdapter.removeEventById(event.eventId);
    mPendingRelaunchTimersByEventId.remove(event.eventId);

    // send it again
    final Message message = JsonUtils.toMessage(event.getContent());

    // resend an image ?
    if (message instanceof ImageMessage) {
        ImageMessage imageMessage = (ImageMessage) message;

        // media has not been uploaded
        if (imageMessage.isLocalContent() || imageMessage.isThumbnailLocalContent()) {
            uploadImageContent(imageMessage, null, imageMessage.thumbnailUrl, imageMessage.url,
                    imageMessage.body, imageMessage.getMimeType());
            return;
        }
    } else if (message instanceof FileMessage) {
        FileMessage fileMessage = (FileMessage) message;

        // media has not been uploaded
        if (fileMessage.isLocalContent()) {
            uploadFileContent(fileMessage.url, fileMessage.getMimeType(), fileMessage.body);
            return;
        }
    } else if (message instanceof VideoMessage) {
        VideoMessage videoMessage = (VideoMessage) message;

        // media has not been uploaded
        if (videoMessage.isLocalContent() || videoMessage.isThumbnailLocalContent()) {
            String thumbnailUrl = null;
            String thumbnailMimeType = null;

            if (null != videoMessage.info) {
                thumbnailUrl = videoMessage.info.thumbnail_url;

                if (null != videoMessage.info.thumbnail_info) {
                    thumbnailMimeType = videoMessage.info.thumbnail_info.mimetype;
                }
            }

            uploadVideoContent(videoMessage, null, thumbnailUrl, thumbnailMimeType, videoMessage.url,
                    videoMessage.body, videoMessage.getVideoMimeType());
            return;
        } else if (message instanceof LocationMessage) {
            LocationMessage locationMessage = (LocationMessage) message;

            // media has not been uploaded
            if (locationMessage.isLocalThumbnailContent()) {
                String thumbMimeType = null;

                if (null != locationMessage.thumbnail_info) {
                    thumbMimeType = locationMessage.thumbnail_info.mimetype;
                }

                uploadLocationContent(locationMessage.thumbnail_url, thumbMimeType, locationMessage.geo_uri,
                        locationMessage.body);
                return;
            }
        }
    }

    send(message);
}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

public void onIceGatheringComplete() {
    final RCConnection connection = this;

    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override//w  w  w  .j  a  va  2  s  .c  o m
        public void run() {
            RCLogger.i(TAG, "onIceGatheringComplete");
            if (peerConnectionClient == null) {
                // if the user hangs up the call before its setup we need to bail
                return;
            }
            if (signalingParameters.initiator) {
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put(RCConnection.ParameterKeys.CONNECTION_PEER, signalingParameters.sipUrl);
                parameters.put("sdp", connection.signalingParameters.generateSipSdp(
                        connection.signalingParameters.offerSdp, connection.signalingParameters.iceCandidates));
                parameters.put(ParameterKeys.CONNECTION_CUSTOM_SIP_HEADERS,
                        connection.signalingParameters.sipHeaders);

                signalingClient.call(jobId, parameters);
            } else {
                HashMap<String, Object> parameters = new HashMap<>();
                parameters.put("sdp",
                        connection.signalingParameters.generateSipSdp(connection.signalingParameters.answerSdp,
                                connection.signalingParameters.iceCandidates));
                signalingClient.accept(jobId, parameters);
                //connection.state = ConnectionState.CONNECTING;
            }
        }
    };
    mainHandler.post(myRunnable);
}

From source file:com.android.mms.ui.MessageUtils.java

public static void resizeImage(final Context context, final Uri imageUri, final Handler handler,
        final ResizeImageResultCallback cb, final boolean append, boolean showToast) {

    /** M: Show a progress toast if the resize hasn't finished
     * within one second.//from w  ww. j a  v a  2  s .co m
     * Stash the runnable for showing it away so we can cancel
     * it later if the resize completes ahead of the deadline.
    */
    final Runnable showProgress = new Runnable() {
        public void run() {
            Toast.makeText(context, R.string.compressing, Toast.LENGTH_SHORT).show();
        }
    };
    if (showToast) {
        handler.post(showProgress);
        //          handler.postDelayed(showProgress, 1000);
    }
    final PduPart part;
    try {
        UriImage image = new UriImage(context, imageUri);
        part = image.getResizedImageAsPart(MmsConfig.getMaxImageWidth(), MmsConfig.getMaxImageHeight(),
                MmsConfig.getUserSetMmsSizeLimit(true) - MESSAGE_OVERHEAD);
        cb.onResizeResult(part, append);
    } catch (IllegalArgumentException e) {
        MmsLog.e(TAG, "Unexpected IllegalArgumentException.", e);
    } finally {
        /// M: Cancel pending show of the progress toast if necessary.
        handler.removeCallbacks(showProgress);
    }
}

From source file:org.numixproject.hermes.activity.ConversationActivity.java

/**
 * On activity result//from  w  w w  . j av  a2s . co  m
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        // ignore other result codes
        return;
    }

    switch (requestCode) {
    case REQUEST_CODE_SPEECH:
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        if (matches.size() > 0) {
            input.setText(matches.get(0));
        }
        break;
    case REQUEST_CODE_JOIN:
        addRecentRoom(data.getExtras().getString("channel"));
        joinChannelBuffer = data.getExtras().getString("channel");
        final Handler handler2 = new Handler();
        handler2.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshActivity();
            }
        }, 100);
        break;
    case REQUEST_CODE_USERS:
        Intent intent = new Intent(this, UserActivity.class);
        intent.putExtra(Extra.USER, data.getStringExtra(Extra.USER));
        startActivityForResult(intent, REQUEST_CODE_USER);
        break;
    case REQUEST_CODE_NICK_COMPLETION:
        insertNickCompletion((AutoCompleteTextView) findViewById(R.id.input),
                data.getExtras().getString(Extra.USER));
        break;
    case REQUEST_CODE_USER:
        final int actionId = data.getExtras().getInt(Extra.ACTION);
        final String nickname = data.getExtras().getString(Extra.USER);
        final IRCConnection connection = binder.getService().getConnection(server.getId());
        final String conversation = server.getSelectedConversation();
        final Handler handler = new Handler();

        // XXX: Implement me - The action should be handled after onResume()
        //                     to catch the broadcasts... now we just wait a second
        // Yes .. that's very ugly - we need some kind of queue that is handled after onResume()

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Do nothing
                }

                String nicknameWithoutPrefix = nickname;

                while (nicknameWithoutPrefix.startsWith("@") || nicknameWithoutPrefix.startsWith("+")
                        || nicknameWithoutPrefix.startsWith(".") || nicknameWithoutPrefix.startsWith("%")) {
                    // Strip prefix(es) now
                    nicknameWithoutPrefix = nicknameWithoutPrefix.substring(1);
                }

                switch (actionId) {
                case User.ACTION_REPLY:
                    final String replyText = nicknameWithoutPrefix + ": ";
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            input.setText(replyText);
                            input.setSelection(replyText.length());
                        }
                    });
                    break;
                case User.ACTION_QUERY:
                    Conversation query = server.getConversation(nicknameWithoutPrefix);
                    if (query == null) {
                        // Open a query if there's none yet
                        query = new Query(nicknameWithoutPrefix);
                        query.setHistorySize(binder.getService().getSettings().getHistorySize());
                        server.addConversation(query);

                        Intent intent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_NEW,
                                server.getId(), nicknameWithoutPrefix);
                        binder.getService().sendBroadcast(intent);
                    }
                    break;
                case User.ACTION_WHOIS:
                    connection.whois(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_OP:
                    connection.op(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEOP:
                    connection.deOp(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_VOICE:
                    connection.voice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEVOICE:
                    connection.deVoice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_KICK:
                    connection.kick(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_BAN:
                    connection.ban(conversation, nicknameWithoutPrefix + "!*@*");
                    break;
                }
            }
        }.start();

        break;
    }
}

From source file:io.realm.RealmTests.java

@Test
public void closeRealmInChangeListener() {
    realm.close();//from  ww  w . j  a v a 2  s .c om
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    HandlerThread handlerThread = new HandlerThread("background");
    handlerThread.start();
    final Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            final Realm realm = Realm.getInstance(realmConfig);
            final RealmChangeListener listener = new RealmChangeListener() {
                @Override
                public void onChange() {
                    if (realm.where(AllTypes.class).count() == 1) {
                        realm.removeChangeListener(this);
                        realm.close();
                        signalTestFinished.countDown();
                    }
                }
            };

            realm.addChangeListener(listener);

            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.createObject(AllTypes.class);
                }
            });
        }
    });
    TestHelper.awaitOrFail(signalTestFinished);
}