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:it.flaviomascetti.posture.PostureCheckFragment.java

@Override
public void onStart() {
    super.onStart();

    button = (Button) getActivity().findViewById(R.id.button_posture_check);

    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
        Log.e(getString(R.string.app_name), getString(R.string.error_write_permission));

        ActivityCompat.requestPermissions(getActivity(),
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSION_REQUEST_SDCARD_WRITE);
    } else // if the permission is granted the button has to be enabled
        button.setEnabled(true);//from  w  w  w . j  av  a  2 s .com

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Close the keyboard
            InputMethodManager inputManager = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

            // Retrieve the chest height from the editText
            EditText et = (EditText) getActivity().findViewById(R.id.edit_text_height);
            Integer height = Integer.parseInt(et.getText().toString());

            if (height >= 1000 && height <= 2000) {
                chestHeight = height;

                et.setEnabled(false);

                // Check SdCard write permission
                Calendar c = Calendar.getInstance();
                String name = String.valueOf(c.get(Calendar.YEAR)) + "-"
                        + String.valueOf(c.get(Calendar.MONTH) + 1) + "-"
                        + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "-"
                        + String.valueOf(c.get(Calendar.HOUR)) + "-" + String.valueOf(c.get(Calendar.MINUTE))
                        + "-" + String.valueOf(c.get(Calendar.SECOND));

                // Create the results file
                file = createFile(folder, name + ".csv");

                // Showing the start snackbar
                Snackbar.make(getActivity().findViewById(R.id.fragment_posture_test), R.string.snack_begin_test,
                        Snackbar.LENGTH_LONG).show();

                // Opening the output stream on the file
                try {
                    bW = new BufferedWriter(new FileWriter(file, true));
                    bW.write("x\t" + //
                    "y\t" + // Acceleration force
                    "z\t" + //
                    "x (mm)\t" + // Conversion of acceleration
                    "z (mm)\t" + // force to mm
                    "dCoP\t" + // Euclidean distance from actualCoP to previous CoP
                    "lengthCoPPath"); // Summation of euclidean dist
                } catch (IOException e) {
                    e.printStackTrace();
                }

                testInProgress = false;

                // Delayed start of function testStart
                Handler handler = new Handler();
                handler.postDelayed(testStart, 7000); // 7000 ms = 7 sec*

                // Make the Begin Button unclickable
                button.setEnabled(false);
            } else {
                // Showing the error snackbar
                Snackbar.make(getActivity().findViewById(R.id.fragment_posture_test),
                        R.string.snack_error_height, Snackbar.LENGTH_LONG).show();
            }

        }
    });
}

From source file:com.sbhstimetable.sbhs_timetable_android.CountdownFragment.java

public void updateTimer() {
    final View f = this.getView();
    if (f == null) {
        return;/*from  w  w w  . j a  v a2  s. com*/
    }

    if (timeLeft != null) {
        cancelling = true;
        timeLeft.cancel();
        cancelling = false;
    }

    RelativeLayout extraData = (RelativeLayout) f.findViewById(R.id.countdown_extraData);
    TextView teacher = (TextView) extraData.findViewById(R.id.countdown_extraData_teacher);
    teacher.setText("");
    TextView room = (TextView) extraData.findViewById(R.id.countdown_extraData_room);
    room.setText("");
    TextView subject = (TextView) extraData.findViewById(R.id.countdown_extraData_subject);
    subject.setText("");
    String label = "Something";
    String connector = "happens in";
    TodayJson.Period p = null;
    if (DateTimeHelper.bells != null) {
        BelltimesJson.Bell next = DateTimeHelper.bells.getNextBell();
        if (next != null) {
            BelltimesJson.Bell now = DateTimeHelper.bells.getIndex(next.getIndex() - 1);
            if (now.isPeriod() && now.getPeriodNumber() < 5) { // in a period, it's not last period.
                connector = "ends in";
                if (ApiAccessor.isLoggedIn() && TodayJson.getInstance() != null) {
                    p = TodayJson.getInstance().getPeriod(now.getPeriodNumber());
                    label = p.name();
                    teacher.setText(p.teacher());
                    room.setText(p.room());
                    subject.setText(p.name());
                    extraData.setVisibility(View.VISIBLE);
                } else {
                    label = now.getLabel();
                    extraData.setVisibility(View.INVISIBLE);
                }
            } else if (now.isPeriod() && now.getPeriodNumber() == 5) { // last period
                connector = "in";
                label = "School ends";
                extraData.setVisibility(View.INVISIBLE);
            } else if (now.getIndex() + 1 < DateTimeHelper.bells.getMaxIndex()
                    && DateTimeHelper.bells.getIndex(now.getIndex() + 1).isPeriod()) { // in a break followed by a period - Lunch 2, Recess, Transition.
                connector = "starts in";
                if (ApiAccessor.isLoggedIn() && TodayJson.getInstance() != null) {
                    p = TodayJson.getInstance()
                            .getPeriod(DateTimeHelper.bells.getIndex(now.getIndex() + 1).getPeriodNumber());
                    label = p.name();
                    teacher.setText(p.teacher());
                    room.setText(p.room());
                    subject.setText(p.name());
                    extraData.setVisibility(View.VISIBLE);
                } else {
                    label = DateTimeHelper.bells.getIndex(now.getIndex() + 1).getLabel();
                    extraData.setVisibility(View.VISIBLE);
                }
            } else { // There's consecutive non-periods - i.e lunch 1 -> lunch 2
                label = now.getLabel();
                connector = "starts in";
            }
        } else {
            // end of day
            label = "School starts";
            connector = "in";
            if (TodayJson.getInstance() != null && TodayJson.getInstance().getPeriod(1) != null) {
                extraData.setVisibility(View.VISIBLE);
                p = TodayJson.getInstance().getPeriod(1);
                teacher.setText(p.teacher());
                room.setText(p.room());
                subject.setText(p.name());
            } else {
                extraData.setVisibility(View.INVISIBLE);
            }
        }
    }

    if (p != null) {
        if (p.teacherChanged()) {
            teacher.setTextColor(getActivity().getResources().getColor(R.color.standout));
        } else {
            //teacher.setTextColor(getActivity().getResources().getColor(R.color.secondary_text_dark));
        }
        if (p.roomChanged()) {
            room.setTextColor(getActivity().getResources().getColor(R.color.standout));
        } else {
            //room.setTextColor(getActivity().getResources().getColor(android.R.color.secondary_text_dark));
        }
    }

    final String innerLabel = label;
    ((TextView) f.findViewById(R.id.countdown_name)).setText(label);
    ((TextView) f.findViewById(R.id.countdown_in)).setText(connector);
    final TextView t = (TextView) f.findViewById(R.id.countdown_countdown);
    final CountdownFragment frag = this;
    CountDownTimer timer = new CountDownTimer(DateTimeHelper.milliSecondsUntilNextEvent(), 1000) {
        long lastTime = 10000;
        boolean isLast = innerLabel.equals("School ends");

        @Override
        public void onTick(long l) {
            lastTime = l;
            t.setText(DateTimeHelper.formatToCountdown(l));
        }

        @Override
        public void onFinish() {
            if (this.lastTime <= 1000 && !cancelling) {
                if (this.isLast) {
                    ApiAccessor.getToday(frag.getActivity());
                    ApiAccessor.getBelltimes(frag.getActivity());
                }
                final Handler h = new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        updateTimer();
                    }
                }, 1000);
            }
        }
    };
    timer.start();
    timeLeft = timer;
}

From source file:com.bjerva.tsplex.fragments.SignListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ma = (MainActivity) getActivity();/*from www .j  a  v a 2 s.com*/

    mGaInstance = GoogleAnalytics.getInstance(ma);
    mGaTracker = mGaInstance.getTracker("UA-39295928-1");

    if (ma.isDoneLoading()) {
        Log.d(TAG, "Loading signs here");
        loadSigns();
    } else {
        final Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {
                if (ma.isDoneLoading()) {
                    loadSigns();
                } else {
                    handler.postDelayed(this, 150);
                }
            }
        };
        handler.postDelayed(r, 1000);
    }
}

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

/**
 * Refresh the list of installed Applications from the user studies.
 *///from  w  ww. j  ava2s  .c  o m
private void refreshInstalledApplications() {
    Log.d(LOG_TAG, "refreshing the installed Applications.");
    if (WelcomeActivity.checkInstalledStatesOfApks() == null) {
        if (retriesCheckValidState < 4) {
            Handler delayedRetryHandler = new Handler();
            delayedRetryHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshInstalledApplications();
                }
            }, 1500);
            retriesCheckValidState++;
        } else {
            // TODO:show error when all retries didn't work?
            // TODO:BIG also do this for viewAvailableApplicationsList?
        }
    } else {
        retriesCheckValidState = 0;
    }
    if (InstalledExternalApplicationsManager.getInstance() == null)
        InstalledExternalApplicationsManager.init(mActivity);

    installedApps = sortForDisplay(new LinkedList<InstalledExternalApplication>(
            InstalledExternalApplicationsManager.getInstance().getApps()));

    populateList(installedApps);
}

From source file:com.peaceworld.wikisms.view.newui.BaseActivity.java

public void switchMenu(Fragment fragment) {

    getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, fragment).commit();
    Handler h = new Handler();
    h.postDelayed(new Runnable() {
        public void run() {
            getSlidingMenu().showMenu();
        }//from www. j  a  va2  s .co  m
    }, 50);

    //toggle();
}

From source file:com.amazon.android.tv.tenfoot.ui.fragments.ContentDetailsFragment.java

/**
 * Since we do not have direct access to the details overview actions row, we are adding a
 * delayed handler that waits for some time, searches for the row and then updates the
 * properties. This is not a fool-proof method,
 * > In slow devices its possible that this does not succeed in achieving the desired result.
 * > In fast devices its possible that the update is clearly visible to the user.
 * TODO: Find a better approach to update action properties
 *//*from   w ww . jav a  2  s.c o m*/
private void updateActionsProperties() {

    Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(() -> {
        View view = getView();
        if (view != null) {
            HorizontalGridView horizontalGridView = (HorizontalGridView) view
                    .findViewById(R.id.details_overview_actions);

            if (horizontalGridView != null) {
                // This is required to make sure this button gets the focus whenever
                // detailsFragment is resumed.
                horizontalGridView.requestFocus();
                for (int i = 0; i < horizontalGridView.getChildCount(); i++) {
                    final Button button = (Button) horizontalGridView.getChildAt(i);
                    if (button != null) {
                        // Button objects are recreated every time MovieDetailsFragment is
                        // created or restored, so we have to bind OnKeyListener to them on
                        // resuming the Fragment.
                        button.setOnKeyListener((v, keyCode, keyEvent) -> {
                            if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
                                    && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                                button.performClick();
                            }
                            return false;
                        });
                    }
                }
            }
        }
    }, 400);
}

From source file:com.peaceworld.wikisms.view.newui.BaseActivity.java

public void switchContent(Fragment fragment, boolean toggle) {

    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();

    if (toggle) {
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            public void run() {
                getSlidingMenu().showContent();
            }//  w w  w  . jav a  2s .  com
        }, 50);
    }
    //toggle();
}

From source file:com.adkdevelopment.simpleflashlightadfree.ui.EmergencyFragment.java

/**
 * Starts emergency sound from assets//  w  w w.  j  a v  a  2s .  co  m
 */
public void emergencySignal() {

    try {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying() && status == FlashlightService.STATUS_OFF) {
            mMediaPlayer.stop();
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;

            mLinearLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorBackground));
        } else if (status == FlashlightService.STATUS_BLINK) {

            final AnimationDrawable drawable = new AnimationDrawable();
            final Handler handler = new Handler();

            drawable.addFrame(new ColorDrawable(Color.RED), 400);
            drawable.addFrame(new ColorDrawable(Color.BLUE), 400);
            drawable.setOneShot(false);

            mLinearLayout.setBackground(drawable);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    drawable.start();
                }
            }, 100);

            mMediaPlayer = new MediaPlayer();
            AssetFileDescriptor descriptor = getActivity().getAssets().openFd("sews.mp3");
            mMediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                    descriptor.getLength());
            descriptor.close();

            mMediaPlayer.prepare();
            mMediaPlayer.setVolume(1f, 1f);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.techmighty.baseplayer.activities.MainActivity.java

private void updatePosition(final MenuItem menuItem) {
    runnable = null;/*w w  w. j a  v  a 2s. co m*/

    switch (menuItem.getItemId()) {
    case R.id.nav_library:
        runnable = navigateLibrary;

        break;
    case R.id.nav_playlists:
        runnable = navigatePlaylist;

        break;
    case R.id.nav_nowplaying:
        NavigationUtils.navigateToNowplaying(MainActivity.this, false);
        break;
    case R.id.nav_queue:
        runnable = navigateQueue;

        break;
    case R.id.nav_settings:
        NavigationUtils.navigateToSettings(MainActivity.this);
        break;
    case R.id.nav_help:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data = Uri.parse("mailto:techmightian@gmail.com");
        intent.setData(data);
        startActivity(intent);
        break;
    case R.id.nav_about:
        mDrawerLayout.closeDrawers();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Helpers.showAbout(MainActivity.this);
            }
        }, 350);

        break;
    }

    if (runnable != null) {
        menuItem.setChecked(true);
        mDrawerLayout.closeDrawers();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        }, 350);
    }
}

From source file:edu.cloud.iot.reception.ocr.FaceRecognitionActivity.java

public void nextHandler(View view) {
    // call AsynTask to perform network operation on separate thread
    try {//from  w  ww  . j  a va 2  s.com
        asyncFaceRecog = new AsyncFaceRecognition();
        asyncFaceRecog.setParent(this);
        // asyncFaceRecog.setBaseFile(imageBytes);
        // asyncFaceRecog.setCompareFile(imageBytes);
        Log.i("EDebug::ResponseOutput", "Triggering FaceRecognition service..");
        Log.i("EDebug::VisitorImageByteArray", "Visitor Image --> " + imageBytes.toString());
        Log.i("EDebug::LicenseImageByteArray", "License Image --> " + licenseBytes.toString());
        // asyncFaceRecog.setBaseFile(licenseBytes);
        // asyncFaceRecog.setCompareFile(imageBytes);
        asyncFaceRecog.asyncState = "processing";
        asyncFaceRecog.execute("");
        // jsonResponse = asyncFaceRecog.getResponse();

        // Log.i("ResponseOutput", jsonResponse.toString(1));
    } catch (Exception ex) {
        Log.i("EDebug::FaceRecogError", "ERROR" + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
    // while(asyncFaceRecog.asyncState.equalsIgnoreCase("processing")){
    // Log.i("EDebug:: (While Loop) asyncFaceRecog.asyncState = ",asyncFaceRecog.asyncState+"");
    // try {
    // Thread.sleep(1000);
    // } catch (InterruptedException e) {
    // e.printStackTrace();
    // }
    // }
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            while (asyncFaceRecog.asyncState.equalsIgnoreCase("processing")) {
                Log.i("EDebug:: Thread - asyncFaceRecog.asyncState = ", "" + asyncFaceRecog.asyncState);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }, 500);
}