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:de.da_sense.moses.client.AvailableFragment.java

@Override
public void onResume() {
    super.onResume();
    this.isPaused = false;
    boolean checkRefreshTime = (lastListRefreshTime == null) ? true
            : (System.currentTimeMillis() - lastListRefreshTime > REFRESH_THRESHHOLD);
    if (checkRefreshTime) {
        requestExternalApplications();/*  w w  w  . j  a  v  a2  s  .c  om*/
    }

    Handler secondTryConnect = new Handler();
    secondTryConnect.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!isPaused) {
                requestExternalApplications();
            }
        }
    }, 2500);
}

From source file:com.androguide.honamicontrol.kernel.cpucontrol.CPUActivity.java

public void onlineCoresPolling() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override//from www . j  a va2 s .c om
        public void run() {
            String cores = CPUHelper.readOneLineNotRoot(OFFLINE_CPUS);
            String displayed;
            if (cores.equals("1-3"))
                displayed = "1/4";
            else if (cores.equals("2-3"))
                displayed = "2/4";
            else if (cores.equals("3-3"))
                displayed = "3/4";
            else
                displayed = "4/4";
            mCoresOnline.setText("Cores Online: " + displayed);
            onlineCoresPolling();
        }

    }, 125);
}

From source file:de.da_sense.moses.client.AvailableFragment.java

/**
 * Request the list of available apps from the server and initialize the
 * request APK controls./*www .  j  av a2  s  .c o m*/
 */
private void requestExternalApplications() {
    if (MosesService.getInstance() == null) {
        if (requestListRetries < 5) {
            Handler delayedRetryHandler = new Handler();
            delayedRetryHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestExternalApplications();
                }
            }, 1000);
            requestListRetries++;
        } else {
            // TODO: show error when all retries didn't work?
        }
    } else {
        requestListRetries = 0;
        lastListRefreshTime = System.currentTimeMillis();
        ApkMethods.getExternalApplications(AvailableFragment.this);
        initControlsOnRequestApks();
    }
}

From source file:org.akvo.caddisfly.sensor.ec.CalibrateSensorActivity.java

private void calibratePoint(final double[] calibrations, final int index) {

    progressDialog = new ProgressDialog(this);
    progressDialog.setTitle(R.string.pleaseWait);
    progressDialog.setMessage(getString(R.string.calibrating));
    progressDialog.setIndeterminate(false);
    progressDialog.setMax(PROGRESS_MAX);
    progressDialog.setCancelable(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.show();// w  w w .  j  a  va  2  s .c om

    final Handler progressHandler = new Handler();
    Runnable progressRunnable = new Runnable() {
        public void run() {
            progressDialog.incrementProgressBy(1);
            if (progressDialog.getProgress() == progressDialog.getMax()) {
                progressDialog.dismiss();
            } else {
                progressHandler.postDelayed(this, 1000);
            }
        }
    };

    progressHandler.postDelayed(progressRunnable, 100);

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

            String requestCommand = "SET POINT" + calibrationIndex + " " + calibrations[index] + LINE_FEED;

            usbService.write(requestCommand.getBytes(StandardCharsets.UTF_8));

            (new Handler()).postDelayed(new Runnable() {
                public void run() {

                    if (calibrationIndex > 5) {

                        AlertUtil.showAlert(mContext, R.string.calibrationSuccessful, R.string.sensorCalibrated,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialogInterface.dismiss();
                                        finish();
                                    }
                                }, null, null);

                    } else {
                        displayInformation(calibrationIndex);
                    }
                }
            }, 1000);
        }
    }, CALIBRATION_DELAY_MILLIS);
}

From source file:de.da_sense.moses.client.AvailableFragment.java

/**
 * Controls the appearance of the button during a refresh. It disables the
 * button and animates its text by periodically appending full stops. At the
 * end of the animation, the button gets enabled with the default text.
 * /*from   w w  w.  j av a2  s . co m*/
 * @param refreshButton
 *            the button which appearance will change
 * @param minimalString
 *            a String for the starting message
 * @param parentLayout
 *            the current state of the layout (it may change during the
 *            refresh)
 */
private void refreshResfreshBtnTimeout(final Button refreshButton, final String minimalString,
        final LayoutState parentLayout) {
    // disable the button during a refresh
    refreshButton.setEnabled(false);
    refreshButton.setText(minimalString);
    // changes the text on the button over time
    Handler enableRefreshHandler = new Handler();
    enableRefreshHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!isPaused && lastSetLayout == parentLayout) {
                refreshButton.setText(minimalString + ".");
            }
        }
    }, 800);
    enableRefreshHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!isPaused && lastSetLayout == parentLayout) {
                refreshButton.setText(minimalString + "..");
            }
        }
    }, 1600);
    enableRefreshHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!isPaused && lastSetLayout == parentLayout) {
                refreshButton.setText(minimalString + "...");
            }
        }
    }, 2400);
    // and then enables the button
    enableRefreshHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!isPaused && lastSetLayout == parentLayout) {
                refreshButton.setText(minimalString);
                refreshButton.setEnabled(true);
            }
        }
    }, 3000);
}

From source file:com.kaszubski.kamil.emmhelper.MainActivity.java

@Override
public boolean onQueryTextChange(final String newText) {
    Log.v(TAG, "query \"" + newText + "\"");
    Fragment fragment = fragmentManager.findFragmentByTag(Constants.FRAGMENT_SEARCH);
    if (newText.trim().length() > 0) {
        if (progressBar == null && fragment != null)
            progressBar = ((SearchFragment) fragment).getProgressBar();

        if (previousQuery != null && newText.contains(previousQuery)) {
            Log.i(TAG, "similar query true");
            final Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override//from   w  w  w .  j a v a2 s .c  om
                public void run() {
                    if (searchPackages.getStatus() == AsyncTask.Status.FINISHED) {
                        searchPackages = new SearchPackages(true);
                        searchPackages.execute(newText);
                    } else {
                        handler.postDelayed(this, 200);
                    }
                }
            });

        } else {
            Log.i(TAG, "similar query false");
            searchResults.clear();
            if (searchPackages != null && searchPackages.getStatus() != AsyncTask.Status.FINISHED) {
                searchPackages.cancel(true);
                progressBar.setVisibility(View.INVISIBLE);
            }

            searchPackages = new SearchPackages();
            searchPackages.execute(newText);
        }
        previousQuery = newText;
        progressBar.setVisibility(View.VISIBLE);

    } else if (fragment != null)
        ((SearchFragment) fragment).setSearchResults(list);
    return true;
}

From source file:com.example.android.tryanimationt.TryAnimationFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mCardView = (CardView) view.findViewById(R.id.cardview);

    fab1st = (android.widget.ImageButton) view.findViewById(R.id.fabBt);
    fab2nd = (android.widget.ImageButton) view.findViewById(R.id.fabBt2);
    fab3rd = (android.widget.ImageButton) view.findViewById(R.id.fab3);

    footer = view.findViewById(R.id.footer);

    animButtons(fab1st, true, 2500, 0);/*from   w w  w .  j a  va2s . co m*/
    animButtons(fab2nd, true, 1000, 150);
    animButtons(fab3rd, true, 2000, 250);

    fab1st.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AnimatorSet animSet = new AnimatorSet();
            ObjectAnimator anim2 = ObjectAnimator.ofFloat(fab1st, "rotationX", 0, 359);
            anim2.setDuration(1500);

            ObjectAnimator anim3 = ObjectAnimator.ofFloat(fab1st, "rotationY", 0, 359);
            anim3.setDuration(1500);

            ObjectAnimator animTrx = ObjectAnimator.ofFloat(fab1st, "translationX", 0, -20);
            animTrx.setDuration(2500);
            ObjectAnimator animTry = ObjectAnimator.ofFloat(fab1st, "translationY", 0, -20);
            animTry.setDuration(2500);

            animSet.setInterpolator(new BounceInterpolator());
            animSet.playTogether(anim2, anim3, animTry, animTrx);

            animSet.start();

        }
    });

    fab1st.setOutlineProvider(new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
            outline.setOval(0, 0, size, size);
            outline.setRoundRect(0, 0, size, size, size / 2);
        }
    });

    fab1st.setClipToOutline(true);

    final View vImage = view.findViewById(R.id.image);
    final View vCard = view.findViewById(R.id.cardview);
    final View vCardTextPart = view.findViewById(R.id.cardview_textpart2);
    final View vCardContentContainer = view.findViewById(R.id.cardContentContainer);

    vCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),

                    // Now we provide a list of Pair items which contain the view we can transitioning
                    // from, and the name of the view it is transitioning to, in the launched activity

                    android.support.v4.util.Pair.create(vImage, "photo_hero"),
                    android.support.v4.util.Pair.create(vCardTextPart, "sharedSceneTrasintionText"));

            Intent intent = new Intent(getActivity(), sceneTransitionActivity.class);
            intent.putExtra("photo_hero", R.drawable.image1);
            ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
        }
    });

    fab2nd.setOutlineProvider(new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
            outline.setOval(0, 0, size, size);
            outline.setRoundRect(0, 0, size, size, size / 2);
        }
    });

    fab2nd.setClipToOutline(true);

    final AnimationDrawable[] animDrawables = new AnimationDrawable[2];
    animDrawables[0] = (AnimationDrawable) getResources().getDrawable(R.drawable.anim_off_to_on);
    animDrawables[1] = (AnimationDrawable) getResources().getDrawable(R.drawable.anim_on_to_off);
    animDrawables[0].setOneShot(true);
    animDrawables[1].setOneShot(true);

    fab2nd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final int fab2InconIndex = mAnimationStateIndex;
            mAnimationStateIndex = (mAnimationStateIndex + 1) % 2;

            /*****************************************************/
            // animate the card

            //final Animation myRotation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_anim);
            //mCardView.startAnimation(myRotation);

            int start;
            int end;
            if (mAnimationStateIndex == 0) {
                start = Color.rgb(0x71, 0xc3, 0xde);
                end = Color.rgb(0x68, 0xe8, 0xee);
            } else {
                start = Color.rgb(0x68, 0xe8, 0xee);
                end = Color.rgb(0x71, 0xc3, 0xde);
            }

            AnimatorSet animSet = new AnimatorSet();

            ValueAnimator valueAnimator = ObjectAnimator.ofInt(vCardContentContainer, "backgroundColor", start,
                    end);
            valueAnimator.setInterpolator(new BounceInterpolator());
            valueAnimator.setDuration(2000);
            valueAnimator.setEvaluator(new ArgbEvaluator());

            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int animProgress = (Integer) animation.getAnimatedValue();

                }
            });
            valueAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mCardView.setRadius(8);
                    //mCardView.setElevation(0);
                }
            });

            float rotateStart, rotateEnd;
            float scaleXStart, scaleXEnd;
            float rotateXStart, rotateXEnd;
            float rotateYStart, rotateYEnd;
            float transitionXStart, transitionXEnd;
            float transitionYStart, transitionYEnd;

            if (mAnimationStateIndex == 0) {
                rotateStart = 0f;
                rotateEnd = 80f;
                scaleXStart = 1f;
                scaleXEnd = 0.66f;
                rotateXStart = 0f;
                rotateXEnd = 30f;
                rotateYStart = 0f;
                rotateYEnd = 30f;
                transitionYStart = 0f;
                transitionYEnd = -100f;
                transitionXStart = 0f;
                transitionXEnd = 100f;
            } else {
                rotateStart = 80f;
                rotateEnd = 0f;
                scaleXStart = 0.66f;
                scaleXEnd = 1;
                rotateXStart = 30;
                rotateXEnd = 0f;
                rotateYStart = 30f;
                rotateYEnd = 0f;
                transitionYStart = -100f;
                transitionYEnd = 0f;
                transitionXStart = 100f;
                transitionXEnd = 0f;
            }

            ObjectAnimator anim = ObjectAnimator.ofFloat(mCardView, "rotation", rotateStart, rotateEnd);
            anim.setDuration(2000);

            ObjectAnimator anim1 = ObjectAnimator.ofFloat(mCardView, "scaleX", scaleXStart, scaleXEnd);
            anim1.setDuration(2000);

            ObjectAnimator anim2 = ObjectAnimator.ofFloat(mCardView, "rotationX", rotateXStart, rotateXEnd);
            anim2.setDuration(2000);

            ObjectAnimator anim3 = ObjectAnimator.ofFloat(mCardView, "rotationY", rotateYStart, rotateYEnd);
            anim3.setDuration(2000);

            ObjectAnimator animTry = ObjectAnimator.ofFloat(mCardView, "translationY", transitionYStart,
                    transitionYEnd);
            animTry.setDuration(2000);
            ObjectAnimator animTrx = ObjectAnimator.ofFloat(mCardView, "translationX", transitionXStart,
                    transitionXEnd);
            animTrx.setDuration(2000);
            animSet.setInterpolator(new BounceInterpolator());
            animSet.playTogether(valueAnimator, anim, anim2, anim3, anim1, animTry, animTrx);

            float controlX1, controlY1, controlX2, controlY2;
            if (mAnimationStateIndex == 0) {
                controlX1 = 0f;
                controlY1 = 0.25f;
                controlX2 = 1;
                controlY2 = 1;
            } else {
                controlX1 = 1;
                controlY1 = 1;
                controlX2 = 0.25f;
                controlY2 = 1;
            }

            PathInterpolator pathInterpolator = new PathInterpolator(controlX1, controlY1, controlX2,
                    controlY2);
            animTrx.setInterpolator(pathInterpolator);

            animSet.start();

            /*****************************************************/
            // animate rotate white button

            RotateAnimation r = new RotateAnimation(0, 359, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            r.setDuration(2000);
            r.setFillAfter(true);

            r.setInterpolator(new BounceInterpolator());

            fab2nd.startAnimation(r);

            // change 2nd button image
            fab2nd.setImageDrawable(animDrawables[fab2InconIndex]);
            animDrawables[fab2InconIndex].start();

            /*****************************************************/
            // animate changing 3rd button image
            fab3rd.setImageDrawable(animDrawables[mAnimationStateIndex]);
            animDrawables[mAnimationStateIndex].start();

            /*****************************************************/
            // using AnimatedStateListDrawable to animate the 1st button image by its state
            {
                Drawable drawable = getActivity().getResources().getDrawable(R.drawable.icon_anim);
                fab1st.setImageDrawable(drawable);

                final int[] STATE_CHECKED = new int[] { android.R.attr.state_checked };
                final int[] STATE_UNCHECKED = new int[] {};

                // set state
                fab1st.setImageState((mAnimationStateIndex != 0) ? STATE_UNCHECKED : STATE_CHECKED, false);
                drawable.jumpToCurrentState();
                // change to state
                fab1st.setImageState((mAnimationStateIndex != 0) ? STATE_CHECKED : STATE_UNCHECKED, false);
            }

        }
    });

    fab3rd.setOutlineProvider(new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
            outline.setOval(0, 0, size, size);
            outline.setRoundRect(0, 0, size, size, size / 2);
        }
    });

    fab3rd.setClipToOutline(true);
    final CheckBox circleFadeout = (CheckBox) view.findViewById(R.id.circleFadeout);

    circleFadeout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (((CheckBox) v).isChecked()) {
            }
        }
    });

    final ImageButton vLogoBt = fab3rd;
    vLogoBt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            animButtons(fab1st, false, 2000, 0);
            animButtons(fab2nd, false, 600, 150);
            animButtons(fab3rd, false, 1500, 250);

            Handler delayHandler = new Handler();
            delayHandler.postDelayed(new Runnable() {

                @Override
                public void run() {

                    Intent logoIntent = new Intent(getActivity(), LogoActivity.class);

                    logoIntent.putExtra(LogoActivity.LOGO_VIEW_IMAGE_FADEOUT,
                            (circleFadeout.isChecked() ? 1 : 0));
                    logoIntent.putExtra(LogoActivity.LOGO_VIEW_TRANSTION_TYPE, logoActivityTransitionType);

                    startActivityForResult(logoIntent, mRequestCode,
                            ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());

                }
            }, 1000);

            // footer slide down
            slideView(footer, false);
        }
    });

    mRadioGrp = (RadioGroup) view.findViewById(R.id.radioGroup);
    mRadioGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            int selectedId = mRadioGrp.getCheckedRadioButtonId();

            String transitionType = "using";
            switch (selectedId) {
            case R.id.radioFade:
                logoActivityTransitionType = 0;
                transitionType = transitionType + " Fade";
                break;
            case R.id.radioExplode:
                logoActivityTransitionType = 1;
                transitionType = transitionType + " Explode";
                break;
            default:
                logoActivityTransitionType = 2;
                transitionType = transitionType + " Slide";
            }
            mSwitcher.setText(transitionType + " transition");
        }
    });

    mSwitcher = (TextSwitcher) view.findViewById(R.id.textSwitcher);
    mSwitcher.setFactory(mFactory);

    Animation in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_top);
    Animation out = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_top);
    mSwitcher.setInAnimation(in);
    mSwitcher.setOutAnimation(out);
    mSwitcher.setCurrentText("using Fade transition");

    // footer slide up
    slideView(footer, true);
}

From source file:org.tlhInganHol.android.klingonassistant.BaseActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.search:
        onSearchRequested();//from   w w  w  .java2s  . c  om
        return true;
    case android.R.id.home:
        mDrawer.toggleMenu();
        break;
    case R.id.social_network:
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        if (sharedPrefs.getString(Preferences.KEY_SOCIAL_NETWORK_LIST_PREFERENCE, /* default */"gplus")
                .equals("gplus")) {
            // Launch Google+ Klingon speakers community.
            launchExternal("https://plus.google.com/communities/108380135139365833546");
        } else {
            // Launch Facebook "Learn Klingon" group.
            launchFacebook("LearnKlingon");
        }
        break;
    /* TUTORIAL */
    case R.id.request_translation:
        requestTranslation();
        break;
    case R.id.float_mode:
        // Minimize the app and cause it to "float".
        Log.d(TAG, "Show floating window.");
        StandOutWindow.show(this, FloatingWindow.class, StandOutWindow.DEFAULT_ID);

        // Broadcast the kill order to finish all non-floating activities.
        // Work around race condition.
        Log.d(TAG, "Broadcast kill order to non-floating window.");
        final Intent intent = new Intent(ACTION_KILL);
        intent.setType(KILL_TYPE);
        Handler killNonFloatingWindowHandler = new Handler();
        Runnable killNonFloatingWindowRunnable = new Runnable() {
            public void run() {
                sendBroadcast(intent);
            }
        };
        killNonFloatingWindowHandler.postDelayed(killNonFloatingWindowRunnable, 100); // 100 ms

        return true;
    case R.id.about:
        // Show "About" screen.
        displayHelp(QUERY_FOR_ABOUT);
        return true;
    case R.id.preferences:
        // Show "Preferences" screen.
        startActivity(new Intent(this, Preferences.class));
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        return true;
    default:
    }

    return super.onOptionsItemSelected(item);
}

From source file:org.odk.collect.android.activities.GeoTraceOsmMapActivity.java

private void zoomToBounds() {
    mapView.getController().setZoom(4);//from   w  w w. jav  a  2 s. c  om
    mapView.invalidate();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            double minLat = Double.MAX_VALUE;
            double maxLat = Double.MIN_VALUE;
            double minLong = Double.MAX_VALUE;
            double maxLong = Double.MIN_VALUE;
            Integer size = mapMarkers.size();
            for (int i = 0; i < size; i++) {
                GeoPoint tempMarker = mapMarkers.get(i).getPosition();
                if (tempMarker.getLatitude() < minLat) {
                    minLat = tempMarker.getLatitude();
                }
                if (tempMarker.getLatitude() > maxLat) {
                    maxLat = tempMarker.getLatitude();
                }
                if (tempMarker.getLongitude() < minLong) {
                    minLong = tempMarker.getLongitude();
                }
                if (tempMarker.getLongitude() > maxLong) {
                    maxLong = tempMarker.getLongitude();
                }
            }
            BoundingBox boundingBox = new BoundingBox(maxLat, maxLong, minLat, minLong);
            mapView.zoomToBoundingBox(boundingBox, false);
            mapView.invalidate();
        }
    }, 100);
    mapView.invalidate();

}

From source file:zack.yovel.clear.controller.foreground.MainActivity.java

private void scheduleProgressDismiss(int expirationDuration) {
    Handler dismissHandler;
    try {//from ww w  .  java2 s . c o m
        dismissHandler = getWindow().getDecorView().getHandler();
    } catch (NullPointerException e) {
        Log.e(TAG, "scheduleProgressDismiss failed with error: " + e.getMessage());
        dismissHandler = handler;
    }

    if (dismissHandler != null) {
        dismissHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (progress != null && progress.isShowing()) {
                    progress.dismiss();
                    progress = null;
                    Log.d("test", "scheduleProgressDismiss");
                    getCannotFindLocationDialog().show();
                }
            }
        }, expirationDuration);
    }
}