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.groundupworks.wings.dropbox.DropboxEndpoint.java

/**
 * Links an account in a background thread. If unsuccessful, the link error is handled on a ui thread and a
 * {@link Toast} will be displayed.//from   w w w  .j  ava  2  s .c  o  m
 */
private void link() {
    synchronized (mDropboxApiLock) {
        if (mDropboxApi != null) {
            final DropboxAPI<AndroidAuthSession> dropboxApi = mDropboxApi;

            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    String accountName = null;
                    String shareUrl = null;
                    String accessToken = null;

                    // Request params.
                    synchronized (mDropboxApiLock) {
                        // Create directory for storing photos.
                        if (createPhotoFolder(dropboxApi)) {
                            // Get account params.
                            accountName = requestAccountName(dropboxApi);
                            shareUrl = requestShareUrl(dropboxApi);
                            accessToken = dropboxApi.getSession().getOAuth2AccessToken();
                        }
                    }

                    // Validate account settings and store.
                    Handler uiHandler = new Handler(Looper.getMainLooper());
                    if (accountName != null && accountName.length() > 0 && shareUrl != null
                            && shareUrl.length() > 0 && accessToken != null) {
                        storeAccountParams(accountName, shareUrl, accessToken);

                        // Emit link state change event on ui thread.
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                notifyLinkStateChanged(new LinkEvent(true));
                            }
                        });
                    } else {
                        // Handle error on ui thread.
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                handleLinkError();
                            }
                        });
                    }
                }
            });
        }
    }
}

From source file:im.neon.contacts.ContactsManager.java

/**
 * List the local contacts./*from   w  w  w.j av  a  2  s  .  com*/
 */
public void refreshLocalContactsSnapshot() {
    boolean isPopulating;

    synchronized (LOG_TAG) {
        isPopulating = mIsPopulating;
    }

    // test if there is a population is in progress
    if (isPopulating) {
        return;
    }

    synchronized (LOG_TAG) {
        mIsPopulating = true;
    }

    // refresh the contacts list in background
    Thread t = new Thread(new Runnable() {
        public void run() {
            long t0 = System.currentTimeMillis();
            ContentResolver cr = mContext.getContentResolver();
            HashMap<String, Contact> dict = new HashMap<>();

            // test if the user allows to access to the contact
            if (isContactBookAccessAllowed()) {
                // get the names
                Cursor namesCur = null;

                try {
                    namesCur = cr.query(ContactsContract.Data.CONTENT_URI,
                            new String[] { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID,
                                    ContactsContract.Contacts.PHOTO_THUMBNAIL_URI },
                            ContactsContract.Data.MIMETYPE + " = ?",
                            new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE },
                            null);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Contact names query Msg="
                            + e.getMessage());
                }

                if (namesCur != null) {
                    try {
                        while (namesCur.moveToNext()) {
                            String displayName = namesCur.getString(
                                    namesCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                            String contactId = namesCur.getString(namesCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID));
                            String thumbnailUri = namesCur.getString(namesCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.StructuredName.PHOTO_THUMBNAIL_URI));

                            if (null != contactId) {
                                Contact contact = dict.get(contactId);

                                if (null == contact) {
                                    contact = new Contact(contactId);
                                    dict.put(contactId, contact);
                                }

                                if (null != displayName) {
                                    contact.setDisplayName(displayName);
                                }

                                if (null != thumbnailUri) {
                                    contact.setThumbnailUri(thumbnailUri);
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG,
                                "## refreshLocalContactsSnapshot(): Exception - Contact names query2 Msg="
                                        + e.getMessage());
                    }

                    namesCur.close();
                }

                // get the phonenumbers
                Cursor phonesCur = null;

                try {
                    phonesCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID },
                            null, null, null);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Phone numbers query Msg="
                            + e.getMessage());
                }

                if (null != phonesCur) {
                    try {
                        while (phonesCur.moveToNext()) {
                            final String pn = phonesCur.getString(
                                    phonesCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            final String pnE164 = phonesCur.getString(phonesCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));

                            if (!TextUtils.isEmpty(pn)) {
                                String contactId = phonesCur.getString(phonesCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

                                if (null != contactId) {
                                    Contact contact = dict.get(contactId);
                                    if (null == contact) {
                                        contact = new Contact(contactId);
                                        dict.put(contactId, contact);
                                    }

                                    contact.addPhoneNumber(pn, pnE164);
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG,
                                "## refreshLocalContactsSnapshot(): Exception - Phone numbers query2 Msg="
                                        + e.getMessage());
                    }

                    phonesCur.close();
                }

                // get the emails
                Cursor emailsCur = null;

                try {
                    emailsCur = cr
                            .query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                    new String[] { ContactsContract.CommonDataKinds.Email.DATA, // actual email
                                            ContactsContract.CommonDataKinds.Email.CONTACT_ID },
                                    null, null, null);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Emails query Msg="
                            + e.getMessage());
                }

                if (emailsCur != null) {
                    try {
                        while (emailsCur.moveToNext()) {
                            String email = emailsCur.getString(
                                    emailsCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                            if (!TextUtils.isEmpty(email)) {
                                String contactId = emailsCur.getString(emailsCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));

                                if (null != contactId) {
                                    Contact contact = dict.get(contactId);
                                    if (null == contact) {
                                        contact = new Contact(contactId);
                                        dict.put(contactId, contact);
                                    }

                                    contact.addEmailAdress(email);
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Emails query2 Msg="
                                + e.getMessage());
                    }

                    emailsCur.close();
                }
            }

            synchronized (LOG_TAG) {
                mContactsList = new ArrayList<>(dict.values());
                mIsPopulating = false;
            }

            if (0 != mContactsList.size()) {
                long delta = System.currentTimeMillis() - t0;

                VectorApp.sendGAStats(VectorApp.getInstance(), VectorApp.GOOGLE_ANALYTICS_STATS_CATEGORY,
                        VectorApp.GOOGLE_ANALYTICS_STARTUP_CONTACTS_ACTION,
                        mContactsList.size() + " contacts in " + delta + " ms", delta);
            }

            // define the PIDs listener
            PIDsRetriever.getInstance().setPIDsRetrieverListener(mPIDsRetrieverListener);

            // trigger a PIDs retrieval
            // add a network listener to ensure that the PIDS will be retreived asap a valid network will be found.
            MXSession defaultSession = Matrix.getInstance(VectorApp.getInstance()).getDefaultSession();
            if (null != defaultSession) {
                defaultSession.getNetworkConnectivityReceiver().addEventListener(mNetworkConnectivityReceiver);

                // reset the PIDs retriever statuses
                mIsRetrievingPids = false;
                mArePidsRetrieved = false;

                // the PIDs retrieval is done on demand.
            }

            if (null != mListeners) {
                Handler handler = new Handler(Looper.getMainLooper());

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        for (ContactsManagerListener listener : mListeners) {
                            try {
                                listener.onRefresh();
                            } catch (Exception e) {
                                Log.e(LOG_TAG,
                                        "refreshLocalContactsSnapshot : onRefresh failed" + e.getMessage());
                            }
                        }
                    }
                });
            }
        }
    });

    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:com.mikhaellopez.saveinsta.activity.MainActivity.java

public void onEventMainThread(EventChangeDominantColor eventChangeDominantColor) {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override//from   w  w w.  j a  v a2s.  c om
        public void run() {
            // Get Dominant Color
            final int color = getDominantColor(mImageToDownload);
            if (color != 0) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mCardView.getVisibility() == View.VISIBLE) {
                            // Set Theme color with Dominant color of Image
                            setThemeColor(mCurrentDominantColor, color);
                        }
                    }
                });
            } else if (BuildConfig.DEBUG) {
                Log.e(getClass().getName(), "Color Unknown");
            }
        }
    }).start();
}

From source file:fashiome.android.fragments.MapListFragment.java

private void dropPinEffect(final Marker marker) {
    // Handler allows us to repeat a code block after a specified delay
    final android.os.Handler handler = new android.os.Handler();
    final long start = SystemClock.uptimeMillis();
    final long duration = 1500;

    // Use the bounce interpolator
    final android.view.animation.Interpolator interpolator = new BounceInterpolator();

    // Animate marker with a bounce updating its position every 15ms
    handler.post(new Runnable() {
        @Override// w  w  w. ja  v  a 2  s.  c  o  m
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            // Calculate t for bounce based on elapsed time
            float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
            // Set the anchor
            marker.setAnchor(0.5f, 1.0f + 14 * t);

            if (t > 0.0) {
                // Post this event again 15ms from now.
                handler.postDelayed(this, 15);
            } else { // done elapsing, show window
                marker.showInfoWindow();
            }
        }
    });
}

From source file:org.schabi.newpipe.VideoItemDetailFragment.java

private void postNewErrorToast(Handler h, final String message) {
    h.post(new Runnable() {
        @Override/*  w w  w . j  ava2s . com*/
        public void run() {
            Toast.makeText(VideoItemDetailFragment.this.getActivity(), message, Toast.LENGTH_LONG).show();
        }
    });
}

From source file:org.schabi.newpipe.VideoItemDetailFragment.java

private void postNewErrorToast(Handler h, final int stringResource) {
    h.post(new Runnable() {
        @Override/* w  w w . j  a  v  a 2 s  .c o m*/
        public void run() {
            Toast.makeText(VideoItemDetailFragment.this.getActivity(), stringResource, Toast.LENGTH_LONG)
                    .show();
        }
    });
}

From source file:github.madmarty.madsonic.util.Util.java

private static void updateSimpleNotification(Context context, final DownloadServiceImpl downloadService,
        Handler handler, MusicDirectory.Entry song, boolean playing) {

    if (song == null || !playing) {
        hidePlayingNotification(context, downloadService, handler);
    } else {// www.j av  a  2  s  . c o  m
        final Notification notification = createSimpleNotification(context, song);

        // Send the notification and put the service in the foreground.
        handler.post(new Runnable() {
            @Override
            public void run() {
                downloadService.startForeground(Constants.NOTIFICATION_ID_PLAYING, notification);
            }
        });
    }
}

From source file:com.intel.gameworkload.GameLayer.java

private void updateActivityResult() {
    Handler handler = new Handler(mActivity.getMainLooper());
    handler.post(new MyTask(getBenchmarkResult(), benchmarkdetails));
}

From source file:com.intel.gameworkload.GameLayer.java

private void exitActivity() {
    Handler handler = new Handler(mActivity.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            mActivity.finish();//from w  w  w .  j  a v a  2 s. c  o  m
        }
    });
}

From source file:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    final FragmentActivity activity = getActivity();

    final LayoutInflater inflater = LayoutInflater.from(activity);

    final Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_Dialog))
            .setTitle(R.string.transaction_summary_title);

    final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.transaction_summary_fragment, null);

    dialog.setView(view);/*from w w w . ja v  a 2  s.  com*/

    try {
        final MyRemoteWallet wallet = application.getRemoteWallet();

        BigInteger totalOutputValue = BigInteger.ZERO;
        for (TransactionOutput output : tx.getOutputs()) {
            totalOutputValue = totalOutputValue.add(output.getValue());
        }

        final TextView resultDescriptionView = (TextView) view.findViewById(R.id.result_description);
        final TextView toView = (TextView) view.findViewById(R.id.transaction_to);
        final TextView toViewLabel = (TextView) view.findViewById(R.id.transaction_to_label);
        final View toViewContainer = (View) view.findViewById(R.id.transaction_to_container);
        final TextView hashView = (TextView) view.findViewById(R.id.transaction_hash);
        final TextView transactionTimeView = (TextView) view.findViewById(R.id.transaction_date);
        final TextView confirmationsView = (TextView) view.findViewById(R.id.transaction_confirmations);
        final TextView noteView = (TextView) view.findViewById(R.id.transaction_note);
        final Button addNoteButton = (Button) view.findViewById(R.id.add_note_button);
        final TextView feeView = (TextView) view.findViewById(R.id.transaction_fee);
        final View feeViewContainer = view.findViewById(R.id.transaction_fee_container);
        final TextView valueNowView = (TextView) view.findViewById(R.id.transaction_value);
        final View valueNowContainerView = view.findViewById(R.id.transaction_value_container);

        String to = null;
        for (TransactionOutput output : tx.getOutputs()) {
            try {
                String toAddress = output.getScriptPubKey().getToAddress().toString();
                if (!wallet.isAddressMine(toAddress)) {
                    to = toAddress;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String from = null;
        for (TransactionInput input : tx.getInputs()) {
            try {
                String fromAddress = input.getFromAddress().toString();
                if (!wallet.isAddressMine(fromAddress)) {
                    from = fromAddress;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long realResult = 0;
        int confirmations = 0;

        if (tx instanceof MyTransaction) {
            MyTransaction myTx = (MyTransaction) tx;

            realResult = myTx.getResult().longValue();

            if (wallet.getLatestBlock() != null) {
                confirmations = wallet.getLatestBlock().getHeight() - myTx.getHeight() + 1;
            }

        } else if (application.isInP2PFallbackMode()) {
            realResult = tx.getValue(application.bitcoinjWallet).longValue();

            if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING)
                confirmations = tx.getConfidence().getDepthInBlocks();
        }

        final long finalResult = realResult;

        if (realResult <= 0) {
            toViewLabel.setText(R.string.transaction_fragment_to);

            if (to == null) {
                ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer);
            } else {
                toView.setText(to);
            }
        } else {
            toViewLabel.setText(R.string.transaction_fragment_from);

            if (from == null) {
                ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer);
            } else {
                toView.setText(from);
            }
        }

        //confirmations view
        if (confirmations > 0) {
            confirmationsView.setText("" + confirmations);
        } else {
            confirmationsView.setText("Unconfirmed");
        }

        //Hash String view
        final String hashString = new String(Hex.encode(tx.getHash().getBytes()), "UTF-8");

        hashView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https:/" + Constants.BLOCKCHAIN_DOMAIN + "/tx/" + hashString));

                startActivity(browserIntent);
            }
        });

        //Notes View
        String note = wallet.getTxNotes().get(hashString);

        if (note == null) {
            addNoteButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                    AddNoteDialog.showDialog(getFragmentManager(), hashString);
                }
            });

            view.removeView(noteView);
        } else {
            view.removeView(addNoteButton);

            noteView.setText(note);

            noteView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                    AddNoteDialog.showDialog(getFragmentManager(), hashString);
                }
            });
        }

        addNoteButton.setEnabled(!application.isInP2PFallbackMode());

        SpannableString content = new SpannableString(hashString);
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        hashView.setText(content);

        if (realResult > 0 && from != null)
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_received,
                    WalletUtils.formatValue(BigInteger.valueOf(realResult))));
        else if (realResult < 0 && to != null)
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_sent,
                    WalletUtils.formatValue(BigInteger.valueOf(realResult))));
        else
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_moved,
                    WalletUtils.formatValue(totalOutputValue)));

        final Date time = tx.getUpdateTime();

        transactionTimeView.setText(dateFormat.format(time));

        //These will be made visible again later once information is fetched from server
        feeViewContainer.setVisibility(View.GONE);
        valueNowContainerView.setVisibility(View.GONE);

        if (tx instanceof MyTransaction) {
            MyTransaction myTx = (MyTransaction) tx;

            final long txIndex = myTx.getTxIndex();

            final Handler handler = new Handler();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final JSONObject obj = getTransactionSummary(txIndex, wallet.getGUID(), finalResult);

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (obj.get("fee") != null) {
                                        feeViewContainer.setVisibility(View.VISIBLE);

                                        feeView.setText(WalletUtils.formatValue(
                                                BigInteger.valueOf(Long.valueOf(obj.get("fee").toString())))
                                                + " BTC");
                                    }

                                    if (obj.get("confirmations") != null) {
                                        int confirmations = ((Number) obj.get("confirmations")).intValue();

                                        confirmationsView.setText("" + confirmations);
                                    }

                                    String result_local = (String) obj.get("result_local");
                                    String result_local_historical = (String) obj
                                            .get("result_local_historical");

                                    if (result_local != null && result_local.length() > 0) {
                                        valueNowContainerView.setVisibility(View.VISIBLE);

                                        if (result_local_historical == null
                                                || result_local_historical.length() == 0
                                                || result_local_historical.equals(result_local)) {
                                            valueNowView.setText(result_local);
                                        } else {
                                            valueNowView.setText(getString(R.string.value_now_ten, result_local,
                                                    result_local_historical));
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Dialog d = dialog.create();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    lp.dimAmount = 0;
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

    d.show();

    d.getWindow().setAttributes(lp);

    d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    return d;
}