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.primalpond.hunt.TheHunt.java

private void returnFromTutorial() {
    mInTutorial = false;//from   ww  w .j a  v  a2s .c o  m

    mGLView.onPause();
    final RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root_layout);
    Handler handler = new Handler();
    class RefreshRunnable implements Runnable {

        public RefreshRunnable() {

        }

        public void run() {
            rootLayout.removeView(findViewById(R.id.glSurfaceView));

            D3GLSurfaceView surfaceview = new D3GLSurfaceView(getApplication(), null,
                    new TheHuntRenderer(TheHunt.this));
            surfaceview.setId(R.id.glSurfaceView);
            rootLayout.addView(surfaceview);

            mGLView = (D3GLSurfaceView) findViewById(R.id.glSurfaceView);

            View actionBarPart = findViewById(R.id.actionBarPart);
            actionBarPart.bringToFront();

            mGLView.mRenderer.setActivity(TheHunt.this);
            MyApplication.setFirstRun(false);
        }
    }
    ;

    RefreshRunnable r = new RefreshRunnable();
    handler.postDelayed(r, 500);
}

From source file:jahirfiquitiva.iconshowcase.activities.ShowcaseActivity.java

public void animateIcons(int delay) {

    if (!iconsPicker && !wallsPicker) {
        switch (numOfIcons) {
        case 4://from w w  w.j ava2  s. co  m
            if (icon1 != null)
                icon1.setVisibility(View.VISIBLE);
            if (icon2 != null)
                icon2.setVisibility(View.VISIBLE);
            if (icon3 != null)
                icon3.setVisibility(View.VISIBLE);
            if (icon4 != null)
                icon4.setVisibility(View.VISIBLE);
            break;
        case 6:
            if (icon1 != null)
                icon1.setVisibility(View.VISIBLE);
            if (icon2 != null)
                icon2.setVisibility(View.VISIBLE);
            if (icon3 != null)
                icon3.setVisibility(View.VISIBLE);
            if (icon4 != null)
                icon4.setVisibility(View.VISIBLE);
            if (icon5 != null)
                icon5.setVisibility(View.VISIBLE);
            if (icon6 != null)
                icon6.setVisibility(View.VISIBLE);
            break;
        case 8:
            if (icon1 != null)
                icon1.setVisibility(View.VISIBLE);
            if (icon2 != null)
                icon2.setVisibility(View.VISIBLE);
            if (icon3 != null)
                icon3.setVisibility(View.VISIBLE);
            if (icon4 != null)
                icon4.setVisibility(View.VISIBLE);
            if (icon5 != null)
                icon5.setVisibility(View.VISIBLE);
            if (icon6 != null)
                icon6.setVisibility(View.VISIBLE);
            if (icon7 != null)
                icon7.setVisibility(View.VISIBLE);
            if (icon8 != null)
                icon8.setVisibility(View.VISIBLE);
            break;
        }
    }

    if (mPrefs.getAnimationsEnabled()) {
        final Animation anim = AnimationUtils.loadAnimation(context, R.anim.bounce);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                playIconsAnimations(anim);
            }
        }, delay);
    }

}

From source file:com.aimfire.main.MainActivity.java

/**
 * Override Activity lifecycle method.//from   www. ja  va 2  s. co m
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        /*
         * if this is initial launch, start the service
         */
        startService(new Intent(this, AimfireService.class));
    }

    PreferenceManager.setDefaultValues(this, getString(R.string.settings_file), MODE_PRIVATE,
            R.xml.pref_settings, true);

    /*
     * check persistence storage, if this is the first time we run, save certain
     * flags (like features available). check showIntro flag and show intro if 
     * necessary
     */
    checkPreferences();

    /*
     * set up UI
     */
    setContentView(R.layout.activity_main);

    /*
     * show overflow button even if we have a physical menu button
     */
    forceOverflowButton();

    /*
     * make a backup if we find old, non-compatible cvr files
     */
    if (mShowIntro) {
        checkOldCvr();
    }

    /*
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    /*
     * create directories if not exist
     */
    if (!FileUtils.initStorage()) {
        Toast.makeText(this, R.string.error_accessing_storage, Toast.LENGTH_LONG).show();
        finish();
    }

    mThumbsPagerAdapter = new ThumbsPagerAdapter(getSupportFragmentManager());

    mThumbsPager = (ViewPager) findViewById(R.id.thumbs_pager);
    mThumbsPager.setAdapter(mThumbsPagerAdapter);

    mThumbsPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When swiping between pages, select the
            // corresponding tab.
            mTabPosition = position;
            getSupportActionBar().setSelectedNavigationItem(position);
        }
    });

    ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mMyMediaTab = bar.newTab();
    mMyMediaTab.setText(getResources().getString(R.string.tab_my_media_name));
    mMyMediaTab.setTabListener(this);

    mSharedMediaTab = bar.newTab();
    mSharedMediaTab.setText(getResources().getString(R.string.tab_shared_with_me_name));
    mSharedMediaTab.setTabListener(this);

    bar.addTab(mMyMediaTab, TAB_INDEX_MY_MEDIA);
    bar.addTab(mSharedMediaTab, TAB_INDEX_SHARED_MEDIA);

    /*
     * first launch of this activity, "Shared with Me" tab is the default.
     */
    if (savedInstanceState != null) {
        /*
         * restore tab position after screen rotation
         */
        mTabPosition = savedInstanceState.getInt(KEY_TAB_POSITION);
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onCreate: restored tab position=" + mTabPosition);
    } else {
        //mTabPosition = TAB_INDEX_MY_MEDIA;
        mTabPosition = TAB_INDEX_SHARED_MEDIA;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onCreate: set initial tab position=" + mTabPosition);
    }

    mCameraFab = (FloatingActionButton) findViewById(R.id.cameraFAB);
    mCameraFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            if (!manager.isWifiEnabled()) {
                /*
                 * if wifi not enabled, no point to continue
                 */
                Toast.makeText(getApplicationContext(), R.string.error_wifi_off, Toast.LENGTH_LONG).show();
                return;
            }

            if (AudioConfigure.getAudioRouting() != AudioConfigure.AUDIO_ROUTING_BUILTIN) {
                Toast.makeText(getApplicationContext(), R.string.error_headset, Toast.LENGTH_LONG).show();
                return;
            }

            mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_ACTION_CAMERA, null);

            /*
             * initiate discovery request
             */
            mAimfireService.initDemo(true, ActivityCode.CAMCORDER.getValue(), null);
            Intent intent = new Intent(getApplicationContext(), CamcorderActivity.class);
            startActivityForResult(intent, ActivityCode.CAMCORDER.getValue());
        }
    });

    /*
     * initializes Aimfire service. if it is already started, bind to it
     */
    mAimfireServiceConn = new AimfireServiceConn(this);

    /*
     * binding doesn't happen until later. wait for it to happen in another 
     * thread and do the necessary initialization on it.
     */
    (new Thread(mAimfireServiceInitTask)).start();

    /*
     * display app build time in debug window
     */
    displayVersion();

    /*
     * show introduction with a delay (to allow onCreate init to finish)
     */
    if (mShowIntro) {
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_BEGIN, null);

        Handler mHandler = new Handler();
        mHandler.postDelayed(mIntroTask, 1000/*ms*/);

        /*
         * check if gyroscope is supported (important for Cardboard mode).
         * only show warning once after fresh install
         */
        checkGyroscope();
    } else if (mShowSurvey) {
        mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_SHOW_SURVEY, null);

        Handler mHandler = new Handler();
        mHandler.postDelayed(mSurveyTask, 1000/*ms*/);
    }

    if ((savedInstanceState == null) && isDeviceOnline()) {
        /*
         * check if new version is available
         */
        startService(new Intent(this, VersionChecker.class));

        /*
         * download samples in the background (if necessary)
         */
        startService(new Intent(this, SamplesDownloader.class));

        /*
         * notify user if upgrade is available
         */
        if (mUpgradeAvailable) {
            notifyUpgrade();
        }
    }

    //(new Thread(mLatencyTestTask)).start();
}

From source file:com.javielinux.tweettopics2.TweetTopicsActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (scanResult != null) {
        String result = scanResult.getContents();
        if (result != null) {
            if (result.startsWith("tweettopics%%qr")) {
                importSearch(result);/*from  ww w.  j  av  a 2 s  .com*/
            }
            if (result.startsWith("tweettopics%%theme")) {
                importTheme(result);
            }
        } else {
            Utils.showMessage(this, getString(R.string.error_general));
        }
    }

    switch (requestCode) {
    case ACTIVITY_NEWEDITSEARCH:

        if (data != null && data.getExtras() != null && data.getExtras().containsKey("view")) {
            boolean create_column = data.getExtras().getBoolean("view", false);

            if (create_column) {
                final int count = ColumnsUtils.nextPositionColumn();

                Entity type = new Entity("type_columns", (long) TweetTopicsUtils.COLUMN_SEARCH);
                Entity search = new Entity("columns");
                search.setValue("description", type.getString("description"));
                search.setValue("type_id", type);
                search.setValue("position", count);
                search.setValue("search_id", data.getLongExtra(DataFramework.KEY_ID, -1));
                search.save();

                goToColumn(count, true, -1);

            } else {
                getFragmentPagerAdapter().getMyActivityFragment().fillData();
            }
        }

        break;
    case ACTIVITY_TRENDS_LOCATION:
        if (resultCode == Activity.RESULT_OK) {
            goToColumn(data.getIntExtra("position", 0), true, -1);
        }
        break;
    case ACTIVITY_EDIT_SEARCH:

        if (data != null && data.getExtras() != null && data.getExtras().containsKey("view")) {
            boolean view_column = data.getExtras().getBoolean("view", false);

            if (view_column) {
                Entity search_entity = new Entity("search", data.getLongExtra(DataFramework.KEY_ID, -1));
                openSearchColumn(search_entity);
            }
        }

        break;
    case ACTIVITY_SHOW_USER_LISTS:
        if (resultCode == Activity.RESULT_OK && data != null) {
            final int position = data.getIntExtra("position", 0);

            Handler myHandler = new Handler();
            myHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getFragmentPagerAdapter().refreshColumnList();
                    refreshActionBarColumns();
                    getViewPager().setCurrentItem(position, false);
                }
            }, 100);
        }
        break;
    }

}

From source file:com.sentaroh.android.Utilities.Dialog.FileSelectDialogFragment.java

private void restoreViewContents() {
    if (mDebugEnable)
        Log.v(APPLICATION_TAG, "restoreViewContents mSavedViewContentsValue=" + mSavedViewContentsValue);
    if (mSavedViewContentsValue == null)
        return;/*from w w w .  ja  v  a 2s  . c om*/
    Handler hndl = new Handler();
    hndl.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mCreateDirDialog != null) {
                Button btnCreate = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_create_btn);
                btnCreate.performClick();
                final EditText etDir = (EditText) mCreateDirDialog.findViewById(R.id.single_item_input_dir);
                etDir.setText(mSavedViewContentsValue.createDialogEditText);
                etDir.setSelection(mSavedViewContentsValue.createDialogEditTextSelStart,
                        mSavedViewContentsValue.createDialogEditTextSelEnd);
            }
        }
    }, 10);
    if (mSavedViewContentsValue.mainDialogSpinnerPos != -1)
        mLocalMountPointSpinner.setSelection(mSavedViewContentsValue.mainDialogSpinnerPos);

    if (mSavedViewContentsValue.mainDailogListItems != null) {
        mTreeFilelistAdapter.setDataList(mSavedViewContentsValue.mainDailogListItems);
        mTreeFileListView.setSelectionFromTop(mSavedViewContentsValue.mainDailogListViewPos[0],
                mSavedViewContentsValue.mainDailogListViewPos[1]);
    }
    resetSavedViewContents();
}

From source file:com.cyrilmottier.android.polaris2demo.MarkerDemoActivity.java

@Override
public boolean onMarkerClick(final Marker marker) {
    // This causes the marker at Perth to bounce into position when it is clicked.
    if (marker.equals(mPerth)) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mMap.getProjection();
        Point startPoint = proj.toScreenLocation(PERTH);
        startPoint.offset(0, -100);//from   ww  w.  j  ava2 s .c om
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                double lng = t * PERTH.longitude + (1 - t) * startLatLng.longitude;
                double lat = t * PERTH.latitude + (1 - t) * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                }
            }
        });
    }
    // We return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

From source file:com.example.mapdemo.VisibleRegionDemoActivity.java

public void animatePadding(final int toLeft, final int toTop, final int toRight, final int toBottom) {

    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long duration = 1000;

    final Interpolator interpolator = new OvershootInterpolator();

    final int startLeft = currentLeft;
    final int startTop = currentTop;
    final int startRight = currentRight;
    final int startBottom = currentBottom;

    currentLeft = toLeft;/*from w  w w . j  a  v  a2  s. c  om*/
    currentTop = toTop;
    currentRight = toRight;
    currentBottom = toBottom;

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);

            int left = (int) (startLeft + ((toLeft - startLeft) * t));
            int top = (int) (startTop + ((toTop - startTop) * t));
            int right = (int) (startRight + ((toRight - startRight) * t));
            int bottom = (int) (startBottom + ((toBottom - startBottom) * t));

            mMap.setPadding(left, top, right, bottom);

            if (elapsed < duration) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

From source file:com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.java

/**
 * Schedule an auto-reconnect attempt using backoff logic.
 *
 * @return true if attempt was scheduled, false otherwise.
 *///from  w w w .jav a 2s . c  om
private boolean scheduleReconnect() {
    LOGGER.info("schedule Reconnect attempt " + autoReconnectsAttempted + " of " + maxAutoReconnectAttempts
            + " in " + currentReconnectRetryTime + " seconds.");
    // schedule a reconnect if unlimited or if we haven't yet hit the limit

    if (maxAutoReconnectAttempts == -1 || autoReconnectsAttempted < maxAutoReconnectAttempts) {
        //Start a separate thread to do reconnect, because connection must not occur on the main thread.
        final HandlerThread ht = new HandlerThread("Reconnect thread");
        ht.start();
        Looper looper = ht.getLooper();
        Handler handler = new Handler(looper);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LOGGER.debug("TID: " + ht.getThreadId() + " trying to reconnect to session");
                if (mqttClient != null && !mqttClient.isConnected()) {
                    reconnectToSession();
                }
            }
        }, MILLIS_IN_ONE_SECOND * currentReconnectRetryTime);
        currentReconnectRetryTime = Math.min(currentReconnectRetryTime * 2, maxReconnectRetryTime);
        return true;
    } else {
        LOGGER.warn("schedule reconnect returns false");
        return false;
    }
}

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  .j  a  va 2s . co 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:info.curtbinder.reefangel.phone.StatusActivity.java

private void displayResponse(String response, int stringId, boolean fAlwaysToast) {
    int msgId;/* w ww.jav  a2 s  . co m*/
    boolean fShowToast = false;
    if (stringId == -1) {
        msgId = R.string.statusRefreshNeeded;
    } else {
        msgId = stringId;
    }
    if (response.contains(XMLTags.Ok)) {
        updateTime.setText(msgId);
        if (rapp.raprefs.isAutoRefreshAfterUpdate()) {
            updateTime.setText(R.string.statusWaiting);
            Log.d(TAG, "AutoRefreshAfterUpdate");
            Handler h = new Handler();
            Runnable r = new Runnable() {
                public void run() {
                    launchStatusTask();
                }
            };
            // pause for a second before we proceed
            h.postDelayed(r, 1000);
        }
    } else {
        fShowToast = true;
    }

    if (fAlwaysToast || fShowToast) {
        Toast.makeText(StatusActivity.this, response, Toast.LENGTH_LONG).show();
    }
}