Example usage for android.os Handler postDelayed

List of usage examples for android.os Handler postDelayed

Introduction

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

Prototype

public final boolean postDelayed(Runnable r, long delayMillis) 

Source Link

Document

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.

Usage

From source file:com.iride.ayride.HomePageActivity.java

private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long DURATION_MS = 1000;
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final LatLng startPosition = marker.getPosition();
    handler.post(new Runnable() {
        @Override/*from   www  .j  a v  a 2  s.c  o m*/
        public void run() {
            float elapsed = SystemClock.uptimeMillis() - start;
            float t = elapsed / DURATION_MS;
            float v = interpolator.getInterpolation(t);

            double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude;
            double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude;
            marker.setPosition(new LatLng(currentLat, currentLng));

            // if animation is not finished yet, repeat
            if (t < 1) {
                handler.postDelayed(this, 16);
            }
        }
    });
}

From source file:org.cryptsecure.Communicator.java

/**
 * Update sent received read async./*from   ww  w . j  a v  a2 s  . c om*/
 * 
 * @param context
 *            the context
 * @param mid
 *            the mid
 * @param hostUid
 *            the host uid
 * @param sent
 *            the sent
 * @param received
 *            the received
 * @param read
 *            the read
 * @param revoked
 *            the revoked
 */
public static void updateSentReceivedReadAsync(final Context context, final int mid, final int hostUid,
        final boolean sent, final boolean received, final boolean read, final boolean revoked,
        final boolean decryptionfailed) {
    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    Log.d("communicator",
                            " GROUP updateSentReceivedReadAsync() #1 " + Conversation.getHostUid() + " == "
                                    + hostUid + ", mid=" + mid + ", sent=" + sent + ", received=" + received
                                    + ", read=" + read);
                    if (Conversation.isAlive() && (Conversation.getHostUid() == hostUid || hostUid == -1)) {
                        Log.d("communicator", " GROUP updateSentReceivedReadAsync() #2");

                        if (decryptionfailed) {
                            Conversation.setDecryptionFailed(context, mid);
                        } else if (read) {
                            Conversation.setRead(context, mid);
                        } else if (received) {
                            Conversation.setReceived(context, mid);
                        } else if (sent) {
                            Conversation.setSent(context, mid);
                        }
                    }
                    if (revoked) {
                        Log.d("communicator",
                                "REVOKE GROUP AS SENDER??? updateSentReceivedReadAsync() Conversation.getHostUid()="
                                        + Conversation.getHostUid() + ", hostUid=" + hostUid);

                        if (Conversation.getInstance() != null
                                && (Conversation.getHostUid() == hostUid || hostUid == -1)) {
                            Log.d("communicator",
                                    "REVOKE GROUP AS SENDER updateSentReceivedReadAsync() #3 mid=" + mid);
                            Conversation.setRevokedInConversation(context, mid);
                        }
                        // for precaution: clear system notifications
                        // for this user
                        if (Utility.loadBooleanSetting(context, Setup.OPTION_NOTIFICATION,
                                Setup.DEFAULT_NOTIFICATION)) {
                            Communicator.cancelNotification(context, hostUid);
                        }
                    }
                    // If message is sent, we possibly want the update the
                    // userlist if it is visible!
                    if (revoked || sent) {
                        if (Main.getInstance() != null) {
                            // in the revoked case we also want to update
                            // the first line!
                            Main.getInstance().rebuildUserlist(context, false);
                        }
                    }
                }
            }, 200);
        }
    });
}

From source file:org.cryptsecure.Communicator.java

/**
 * Live update or notify.// w w  w.j a  v  a 2s.  c  om
 * 
 * @param context
 *            the context
 * @param newItem
 *            the new item
 */
public static void liveUpdateOrNotify(final Context context, final ConversationItem newItem) {
    Log.d("communicator", "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #1 from=" + newItem.from
            + ", part=" + newItem.part + ", multipartid=" + newItem.multipartid);

    // Consider localgroupid as an alternative "from"
    int uidFromTmp = newItem.from;
    int localgroupid = Utility.parseInt(newItem.groupId, -1);
    if (localgroupid != -1) {
        Log.d("communicator", "@@@@ liveUpdateOrNotify() Conversation.getHostUid()=" + Conversation.getHostUid()
                + ", localgroupid=" + localgroupid);
        uidFromTmp = localgroupid;
    }
    final int uidFrom = uidFromTmp;

    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    if (Conversation.isVisible() || Main.isVisible()) {
                        // Possibly there are new users added and we need to
                        // prompt!
                        Setup.possiblyPromptAutoAddedUser(context);
                    }

                    // Live - update if possible,
                    // otherwise create notification!
                    if (Conversation.isVisible() && Conversation.getHostUid() == uidFrom) {
                        // The conversation is currently
                        // open, try to update this
                        // right away!
                        //
                        // ATTENTION: If not scrolled down then send an
                        // additional toast!
                        if (!Conversation.scrolledDown && !newItem.isKey && newItem.readyToProcess()) {
                            if (newItem.transport == DB.TRANSPORT_INTERNET) {
                                Utility.showToastShortAsync(context,
                                        "New message " + newItem.localid + " received.");
                            } else {
                                Utility.showToastShortAsync(context,
                                        "New SMS " + newItem.localid + " received.");
                            }
                        }

                        Log.d("communicator",
                                "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #A , part="
                                        + newItem.part + ", newItem.multipartid=" + newItem.multipartid);

                        if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                            // This IS a multipart message
                            Conversation.hideMultiparts(context, newItem.multipartid);
                        }
                        Conversation.getInstance().updateConversationlist(context);
                        if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                            Conversation
                                    .setMultipartProgress(
                                            context, newItem.multipartid, DB.getPercentReceivedComplete(context,
                                                    newItem.multipartid, newItem.from, newItem.parts),
                                            newItem.text);
                        }
                    } else {
                        // The conversation is NOT
                        // currently
                        // open, we need a new
                        // notification
                        Log.d("communicator",
                                "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #2 " + newItem.from);
                        if (!newItem.isKey && newItem.readyToProcess()) {
                            Log.d("communicator", "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #3 "
                                    + newItem.from);
                            createNotification(context, newItem, uidFrom);
                        }
                        if (Conversation.isAlive() && Conversation.getHostUid() == uidFrom) {
                            // Still update because conversation is in
                            // memory!
                            // Also possibly scroll down: If the user
                            // unlocks the phone,
                            // and scrolledDown was true, then he expects to
                            // see the
                            // last/newest message!
                            if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                                // This IS a multipart message
                                Conversation.hideMultiparts(context, newItem.multipartid);
                            }
                            Conversation.getInstance().updateConversationlist(context);
                            if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                                Conversation.setMultipartProgress(
                                        context, newItem.multipartid, DB.getPercentReceivedComplete(context,
                                                newItem.multipartid, newItem.from, newItem.parts),
                                        newItem.text);
                            }

                        }
                    }

                    if (Main.isVisible()) {
                        Main.getInstance().rebuildUserlist(context, false);
                    }
                }
            }, 200);
        }
    });
}

From source file:com.ywesee.amiko.MainActivity.java

/**
 * Shows the splash screen over the full Activity
 *///from w ww.j  av  a  2s. co m
protected void showSplashScreen(boolean showIt, boolean dismissAuto) {
    if (showIt) {
        mSplashDialog = new Dialog(this, android.R.style.Theme_Holo /*Translucent_NoTitleBar_Fullscreen*/);
        mSplashDialog.setContentView(R.layout.splash_screen);
        mSplashDialog.setCancelable(false);
        mSplashDialog.show();

        // Enable flag (disable toast message)
        mRestoringState = true;

        mSplashDialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                createMainLayout();
                // Re-enable toaster once the splash screen has been removed...
                mRestoringState = false;
                //
                mSearch.requestFocus();
                // Show keyboard
                showSoftKeyboard(100);
            }
        });

        // Set Runnable to remove splash screen just in case
        if (dismissAuto) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mSplashDialog != null) {
                        mSplashDialog.dismiss();
                        mSplashDialog = null;
                    }
                }
            }, 3000);
        }
    }
}

From source file:com.ywesee.amiko.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case (R.id.menu_search): {
        showSoftKeyboard(300);/*w  w  w  . j a  va  2 s.  com*/
        return true;
    }
    case (R.id.menu_pref2): {
        Intent intent = new Intent(this, ReportActivity.class);
        startActivity(intent);
        return true;
    }
    case (R.id.menu_pref3): {
        // Download new database (blocking call)
        if (!mUpdateInProgress)
            requestPermissionAndDownloadUpdates();
        mToastObject.show(getString(R.string.menu_pref3), Toast.LENGTH_SHORT);
        return true;
    }
    case (R.id.menu_share): {
        // Remove softkeyboard
        hideSoftKeyboard(10);
        // Take screenshot and start email activity after 500ms (wait for the keyboard to disappear)
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mToastObject.show(getString(R.string.menu_share), Toast.LENGTH_SHORT);
                sendFeedbackScreenshot(MainActivity.this, 1);
            }
        }, 500);
        return true;
    }
    case (R.id.menu_rate): {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // Try Google play
        String uri_str = "market://details?id=com.ywesee.amiko.de";
        if (Constants.appLanguage().equals("fr"))
            uri_str = "market://details?id=com.ywesee.amiko.fr";
        intent.setData(Uri.parse(uri_str));
        if (myStartActivity(intent) == false) {
            // Market (Google play) app seems not installed, let's try to open a webbrowser
            uri_str = "https://play.google.com/store/apps/details?id=com.ywesee.amiko.de";
            if (Constants.appLanguage().equals("fr"))
                uri_str = "https://play.google.com/store/apps/details?id=com.ywesee.amiko.fr&hl=fr";
            intent.setData(Uri.parse(uri_str));
            if (myStartActivity(intent) == false) {
                // Well if this also fails, we have run out of options, inform the user.
                mToastObject.show("Could not open Android market, please install the market app.",
                        Toast.LENGTH_SHORT);
            }
        }
        return true;
    }
    case (R.id.menu_help): {
        mToastObject.show(getString(R.string.menu_help), Toast.LENGTH_SHORT);
        if (Constants.appOwner().equals("ywesee")) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.ywesee.com/AmiKo/Index"));
            startActivity(browserIntent);
        }
        return true;
    }
    default:
        break;
    }

    return true;
}

From source file:com.ywesee.amiko.MainActivity.java

/**
 * This function creates the main layout, called when splashscreen is over
 *//*from   w w w.jav a 2 s.c om*/
public void createMainLayout() {
    //
    setContentView(R.layout.activity_main);

    // Initialize views
    mSuggestView = getLayoutInflater().inflate(R.layout.suggest_view, null);
    mShowView = getLayoutInflater().inflate(R.layout.show_view, null);

    // Sets current view
    mCurrentView = mSuggestView;

    // Setup webviews
    // Add views to viewholder
    mViewHolder = (ViewGroup) findViewById(R.id.main_layout);
    mViewHolder.addView(mSuggestView);
    mViewHolder.addView(mShowView);

    setLayoutTransition();

    mBottomNavigationView = findViewById(R.id.bottom_navigation);
    setupBottomNavigationViewListener();

    // Define and load webview
    ExpertInfoView mExpertInfoView = new ExpertInfoView(this, (WebView) findViewById(R.id.fach_info_view));
    mExpertInfoView.adjustZoom();

    mWebView = mExpertInfoView.getWebView();
    setFindListener(mWebView);
    setupGestureDetector(mWebView);

    // Set up observer to JS messages
    JSInterface jsinterface = mExpertInfoView.getJSInterface();
    jsinterface.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            String s = (String) arg;
            if (s.equals("notify_interaction")) {
                // Remove softkeyboard
                hideSoftKeyboard(100);
                // Take screenshot and start email activity after 500ms (wait for the keyboard to disappear)
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendFeedbackScreenshot(MainActivity.this, 2);
                    }
                }, 500);
            } else {
                if (s.equals("delete_all")) {
                    mMedInteractionBasket.clearBasket();
                } else {
                    mMedInteractionBasket.deleteFromBasket(s);
                }
                //
                // TODO: please comment this "hack"
                //
                Handler mainHandler = new Handler(getMainLooper());
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mMedInteractionBasket.updateInteractionsHtml();
                        String html_str = mMedInteractionBasket.getInteractionsHtml();
                        mWebView.loadDataWithBaseURL("file:///android_res/drawable/", html_str, "text/html",
                                "utf-8", null);
                    }
                });
            }
        }
    });

    // Initialize suggestion listview
    mListView = (ListView) findViewById(R.id.suggestView);
    mListView.setClickable(true);

    // Set visibility of views
    mSuggestView.setVisibility(View.VISIBLE);
    mShowView.setVisibility(View.GONE);

    // Setup initial view
    setCurrentView(mSuggestView, false);
    // Reset it
    resetView(false);
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public void getYouTubeAuthTokenWithPermissionAndUpload(final Activity activity, String accountName,
        final String path, final Handler handler, final String emailAddress, final long sdrecord_id) {

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();

    this.youTubeName = accountName;

    this.authorizer = new GlsAuthorizer.GlsAuthorizerFactory().getAuthorizer(activity,
            GlsAuthorizer.YOUTUBE_AUTH_TOKEN_TYPE);

    this.authorizer.fetchAuthToken(accountName, activity, new AuthorizationListener<String>() {
        public void onCanceled() {

            Log.d(TAG, " Cancelled in fetchAuthToken! ");

        }//from  w w w. ja  v  a2s.c  o m

        public void onError(Exception e) {

            Log.d(TAG, " Error in fetchAuthToken! ");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(false);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

        }

        public void onSuccess(String result) {
            PublishingUtils.this.clientLoginToken = result;
            File file = new File(path);
            // Launch Async YouTube video upload.
            asyncYouTubeUpload(activity, file, handler, emailAddress, sdrecord_id);
        }
    });
}

From source file:com.dish.browser.activity.BrowserActivity.java

/**
 * displays the WebView contained in the LightningView Also handles the
 * removal of previous views// w ww  .  ja va 2  s.co  m
 *
 * @param view
 *            the LightningView to show
 */
private synchronized void showTab(LightningView view) {
    // Set the background color so the color mode color doesn't show through
    mBrowserFrame.setBackgroundColor(mBackgroundColor);
    if (view == null) {
        return;
    }
    mBrowserFrame.removeAllViews();
    if (mCurrentView != null) {
        mCurrentView.setForegroundTab(false);
        mCurrentView.onPause();
    }
    mCurrentView = view;
    mCurrentView.setForegroundTab(true);
    if (mCurrentView.getWebView() != null) {
        updateUrl(mCurrentView.getUrl(), true);
        updateProgress(mCurrentView.getProgress());
    } else {
        updateUrl("", true);
        updateProgress(0);
    }

    mBrowserFrame.addView(mCurrentView.getWebView(), MATCH_PARENT);
    // Remove browser frame background to reduce overdraw
    mBrowserFrame.setBackgroundColor(0);
    mCurrentView.requestFocus();
    mCurrentView.onResume();

    // Use a delayed handler to make the transition smooth
    // otherwise it will get caught up with the showTab code
    // and cause a janky motion
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mDrawerLayout.closeDrawers();
        }
    }, 150);
}

From source file:openscience.crowdsource.experiments.MainActivity.java

/*************************************************************************/
public void addListenersOnButtons() {
    Button b_sdk = (Button) findViewById(R.id.b_sdk);
    Button b_about = (Button) findViewById(R.id.b_about);
    b_clean = (Button) findViewById(R.id.b_clean);
    Button b_stats = (Button) findViewById(R.id.b_stats);
    Button b_users = (Button) findViewById(R.id.b_users);

    /*************************************************************************/
    b_sdk.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings({ "unused", "unchecked" })
        @Override/*from  ww  w  .  j a  v a 2  s.  c  om*/
        public void onClick(View arg0) {
            log.append("\nOpening " + url_sdk + " ...\n");

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url_sdk));

            startActivity(browserIntent);
        }
    });

    /*************************************************************************/
    b_about.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings({ "unused", "unchecked" })
        @Override
        public void onClick(View arg0) {
            log.append("\nOpening " + url_about + " ...\n");

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url_about));

            startActivity(browserIntent);
        }
    });

    /*************************************************************************/
    b_clean.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            log.setText("");
            log.setText("Cleaning local tmp files ...\n");
            if (!clean_log_tmp())
                log.setText("  ERROR: Can't create directory " + path + " ...\n");
        }
    });

    /*************************************************************************/
    b_stats.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings({ "unused", "unchecked" })
        @Override
        public void onClick(View arg0) {
            log.append("\nOpening " + url_stats + " ...\n");

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url_stats));

            startActivity(browserIntent);
        }
    });

    /*************************************************************************/
    b_users.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings({ "unused", "unchecked" })
        @Override
        public void onClick(View arg0) {
            log.append("\nOpening " + url_users + " ...\n");

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url_users));

            startActivity(browserIntent);
        }
    });

    /*************************************************************************/
    b_start.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings({ "unused", "unchecked" })
        @Override
        public void onClick(View arg0) {
            if (running) {
                running = false;

                b_start.setEnabled(false);

                log.append(s_line);
                log.append(s_thanks);
                log.append("Interrupting crowd-tuning and quitting program ...");

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        finish();
                        System.exit(0);
                    }
                }, 1500);

            } else {
                running = true;
                b_start.setText(s_b_stop);
                b_clean.setEnabled(false);

                String email1 = t_email.getText().toString().replaceAll("(\\r|\\n)", "");
                if (email1.equals("")) {
                    email1 = openme.gen_uid();
                }
                if (!email1.equals(email)) {
                    email = email1;
                    String pp = path0 + '/' + cemail;
                    if (!save_one_string_file(pp, email)) {
                        log.append("ERROR: can't write local configuration (" + pp + "!");
                        return;
                    }
                }

                CheckBox c_continuous = (CheckBox) findViewById(R.id.c_continuous);
                if (c_continuous.isChecked())
                    iterations = -1;

                crowdTask = new runCodeAsync().execute("");
            }
        }
    });
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

@Override
public void onShutterClick() {
    if (!CameraController.isRemoteCamera()) {
        if (shutterOff)
            return;

        if (isRecording) {
            long now = SystemClock.uptimeMillis();
            long delta = now - mRecordingStartTime;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    stopRecording();//  ww  w. j a v  a 2 s.c  om
                }
            }, 1500 - delta);
        } else {
            this.startRecording();
        }
    } else {//Sony camera
        pauseVideoButton.setVisibility(View.GONE);
        if (isRecording) {
            stopRecordingSonyRemote();
        } else {
            startRecordingSonyRemote();
        }
    }
}