Example usage for android.os CountDownTimer CountDownTimer

List of usage examples for android.os CountDownTimer CountDownTimer

Introduction

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

Prototype

public CountDownTimer(long millisInFuture, long countDownInterval) 

Source Link

Usage

From source file:com.woofy.haifa.MapActivity.java

public void playGame(final ArrayList<Round> roundlist, final int round, final int delay, final int game_id) {
    if (round == 0) {
        game_on = true;/*from   ww  w.j  av a  2 s . c o m*/
    } else if (!game_on) {
        return;
    }

    track = true;
    if (round == 0) {
        game_counter = 0;
    }
    final TextView timer = (TextView) findViewById(R.id.gametimer);
    timer.setVisibility(View.VISIBLE);
    if (round >= roundlist.size()) {
        timer.setText("You WIN");
        //TODO you win
        return;
    }
    final TextView plist = (TextView) findViewById(R.id.players_list);
    plist.setVisibility(View.VISIBLE);
    final Round r1 = roundlist.get(round);
    final Circle zone1 = zz1 = drawCircle(r1.ll1, r1.circle_radius);
    final Circle zone2 = zz2 = drawCircle(r1.ll2, r1.circle_radius);
    final Circle zone3 = zz3 = drawCircle(r1.ll3, r1.circle_radius);

    long time_limit = r1.seconds + delay * 1000, interval = 1000;
    counttimer = new CountDownTimer(time_limit, interval) {
        @SuppressLint("NewApi")
        public void onTick(long milliUntilFinished) {
            if (!game_on) {
                zone1.remove();
                zone2.remove();
                zone3.remove();
                this.cancel();
                return;
            }
            game_counter++;
            timer.setText("" + milliUntilFinished / 1000);
            Vector<BasicNameValuePair> vec = new Vector<BasicNameValuePair>();
            vec.add(new BasicNameValuePair("game_id", game_id + ""));
            HttpLib.PlayerList listtask = new PlayerList(vec, plist);
            listtask.execute();
            Vector<BasicNameValuePair> vec2 = new Vector<BasicNameValuePair>();
            vec2.add(new BasicNameValuePair("game_id", game_id + ""));
            vec2.add(new BasicNameValuePair("seconds", (game_counter - delay) + ""));//TODO
            HttpLib.PostTask updateseconds = new HttpLib.PostTask(vec2,
                    "http://52.1.192.145/safezone_ping.php");
            updateseconds.execute();
        }

        public void onFinish() {
            zone1.remove();
            zone2.remove();
            zone3.remove();
            if (!game_on) {
                return;
            }
            Location you = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
            if (you == null) {
                return;
            }
            LatLng ll = new LatLng(you.getLatitude(), you.getLongitude());
            latLngDistance(zone1.getCenter(), ll);
            float mindistance = Math.min(latLngDistance(zone1.getCenter(), ll),
                    latLngDistance(zone2.getCenter(), ll));
            mindistance = Math.min(mindistance, latLngDistance(zone3.getCenter(), ll));

            if (mindistance <= r1.circle_radius) {
                timer.setText("Next");
                playGame(roundlist, round + 1, 0, game_id);
            } else {
                timer.setText("You LOSE");
                gameEnd();
                return;
            }

        }
    }.start();
}

From source file:it.iziozi.iziozi.gui.IOBoardActivity.java

private void showUnlockAlert() {
    this.mUnlockAlert = new AlertDialog.Builder(IOBoardActivity.this)
            .setTitle(getResources().getString(R.string.unlock))
            .setMessage(getResources().getQuantityString(R.plurals.unlock_question,
                    IOBoardActivity.this.mUnlockTimeout.intValue(),
                    IOBoardActivity.this.mUnlockTimeout.intValue()))
            .setPositiveButton(getResources().getString(R.string.unlock),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mUILocked = false;
                            showSystemUI();
                            mDecorView.invalidate();
                            if (canGoImmersive() == false)
                                openOptionsMenu();
                        }/*from   w  ww .j  a  v  a2  s.  c  o  m*/
                    })
            .setNegativeButton(getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            lockUI();
                        }
                    })
            .setCancelable(false).create();

    this.mUnlockAlert.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            IOBoardActivity.this.mUnlockCountDown.cancel();
            IOBoardActivity.this.mUnlockCountDown = null;
            IOBoardActivity.this.mUnlockAlert = null;
        }
    });

    this.mUnlockAlert.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            IOBoardActivity.this.mUnlockCountDown = new CountDownTimer(
                    1000 * IOBoardActivity.this.mUnlockTimeout, 100) {
                @Override
                public void onTick(long millisUntilFinished) {

                    int sVal = ((int) Math.ceil(millisUntilFinished / 1000.f));

                    IOBoardActivity.this.mUnlockAlert.setMessage(
                            getResources().getQuantityString(R.plurals.unlock_question, sVal, sVal));
                }

                @Override
                public void onFinish() {
                    IOBoardActivity.this.mUnlockAlert.dismiss();
                    lockUI();
                }
            };

            IOBoardActivity.this.mUnlockCountDown.start();
        }
    });

    this.mUnlockAlert.show();
}

From source file:com.almalence.opencam.ApplicationScreen.java

protected void onApplicationResume() {
    isCameraConfiguring = false;/*  w ww  .j  a v a 2s  .  c  o m*/

    onResumeTimer = new CountDownTimer(50, 50) {
        public void onTick(long millisUntilFinished) {
            // Not used
        }

        public void onFinish() {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(ApplicationScreen.getMainContext());

            preview.setKeepScreenOn(true);

            captureFormat = CameraController.JPEG;

            String modeId = ApplicationScreen.getPluginManager().getActiveModeID();
            if (CameraController.isRemoteCamera() && !(modeId.contains("single") || modeId.contains("video"))) {
                prefs.edit().putInt(ApplicationScreen.sCameraModePref, 0).commit();
                CameraController.setCameraIndex(0);
                guiManager.setCameraModeGUI(0);
            }

            CameraController.onResume();
            ApplicationScreen.getGUIManager().onResume();
            ApplicationScreen.getPluginManager().onResume();

            ApplicationScreen.instance.mPausing = false;

            if (!CameraController.isRemoteCamera()) {
                // set preview, on click listener and surface buffers
                findViewById(R.id.SurfaceView02).setVisibility(View.GONE);
                preview = (SurfaceView) findViewById(R.id.SurfaceView01);
                preview.setOnClickListener(ApplicationScreen.this);
                preview.setOnTouchListener(ApplicationScreen.this);
                preview.setKeepScreenOn(true);

                surfaceHolder = preview.getHolder();
                surfaceHolder.addCallback(ApplicationScreen.this);

                // One of device camera is selected.
                if (CameraController.isUseCamera2()) {
                    ApplicationScreen.instance.findViewById(R.id.mainLayout2).setVisibility(View.VISIBLE);
                    CameraController.setupCamera(null, true);

                    if (glView != null)
                        glView.onResume();
                } else if ((surfaceCreated && (!CameraController.isCameraCreated()))) {
                    ApplicationScreen.instance.findViewById(R.id.mainLayout2).setVisibility(View.VISIBLE);
                    CameraController.setupCamera(surfaceHolder, true);

                    if (glView != null) {
                        glView.onResume();
                    }
                }
            } else {
                sonyCameraSelected();
            }
            orientListener.enable();
        }
    }.start();

    shutterPlayer = new SoundPlayer(this.getBaseContext(),
            getResources().openRawResourceFd(R.raw.plugin_capture_tick));

    if (screenTimer != null) {
        if (isScreenTimerRunning)
            screenTimer.cancel();
        screenTimer.start();
        isScreenTimerRunning = true;
    }

    long memoryFree = getAvailableInternalMemory();
    if (memoryFree < 30)
        Toast.makeText(ApplicationScreen.getMainContext(), "Almost no free space left on internal storage.",
                Toast.LENGTH_LONG).show();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    boolean dismissKeyguard = prefs.getBoolean("dismissKeyguard", true);
    if (dismissKeyguard)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    else {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    }
}

From source file:org.xingjitong.InCallActivity.java

@Override
public void onCallStateChanged(final LinphoneCall call, State state, String message) {
    if (LinphoneManager.getLc().getCallsNb() == 0) {
        finish();/*from w  ww.  j a v  a 2  s . co m*/
        return;
    }

    if (state == State.IncomingReceived) {
        startIncomingCallActivity();
        android.util.Log.v("yyppdebug", "yyppcalling State.IncomingReceived 000");

        return;
    }
    if (state == State.OutgoingRinging) {

        android.util.Log.v("yyppdebug", "yyppcalling State.OutgoingRinging 111");

        return;
    }

    if (state == State.StreamsRunning) {

        //yyppcalling add
        UserConfig.getInstance().isstreamsrunning = 1;

        boolean isVideoEnabledInCall = call.getCurrentParamsCopy().getVideoEnabled();
        if (isVideoEnabledInCall != isVideoEnabled) {
            isVideoEnabled = isVideoEnabledInCall;
            switchVideo(isVideoEnabled);
        }

        // The following should not be needed except some devices need it
        // (e.g. Galaxy S).
        LinphoneManager.getLc().enableSpeaker(isSpeakerEnabled);

        isMicMuted = LinphoneManager.getLc().isMicMuted();
        enableAndRefreshInCallActions();

        if (status != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //status.refreshStatusItems(call, isVideoEnabled);
                }
            });
        }

    }
    refreshInCallActions();

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            refreshCallList(getResources());
        }
    });

    if (state == State.CallUpdatedByRemote) {
        // If the correspondent proposes video while audio call
        boolean isVideoEnabled = LinphoneManager.getInstance().isVideoEnabled();
        if (!isVideoEnabled) {
            acceptCallUpdate(false);
            return;
        }

        boolean remoteVideo = call.getRemoteParams().getVideoEnabled();
        boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled();
        boolean autoAcceptCameraPolicy = LinphoneManager.getInstance().isAutoAcceptCamera();
        if (remoteVideo && !localVideo && !autoAcceptCameraPolicy
                && !LinphoneManager.getLc().isInConference()) {
            mHandler.post(new Runnable() {
                public void run() {
                    showAcceptCallUpdateDialog();

                    timer = new CountDownTimer(SECONDS_BEFORE_DENYING_CALL_UPDATE, 1000) {
                        public void onTick(long millisUntilFinished) {
                        }

                        public void onFinish() {
                            acceptCallUpdate(false);
                        }
                    }.start();
                }
            });
        }
        // else if (remoteVideo && !LinphoneManager.getLc().isInConference()
        // && autoAcceptCameraPolicy) {
        // mHandler.post(new Runnable() {
        // @Override
        // public void run() {
        // acceptCallUpdate(true);
        // }
        // });
        // }
    }

    transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
}

From source file:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java

public void startIntervalRecording(int ms) {
    mTimer = new CountDownTimer(ms, 1000) {
        boolean recordStart = false;

        @Override/*from  ww  w  .  j a  va2s .co m*/
        public void onTick(long millisUntilFinished) {
            if (!recordStart) {
                recordStart = true;
                startRecordingVideo();
            }
        }

        @Override
        public void onFinish() {
            recordStart = false;
            if (mIsRecordingVideo) {
                stopRecordingVideo();
                mTimer.start();
            }
        }
    };
    mTimer.start();

}

From source file:com.sim2dial.dialer.InCallActivity.java

@Override
public void onCallStateChanged(final LinphoneCall call, State state, String message) {
    if (LinphoneManager.getLc().getCallsNb() == 0) {
        finish();/*from  ww  w .  j  a  v  a  2  s . com*/
        return;
    }

    if (state == State.IncomingReceived) {
        startIncomingCallActivity();
        return;
    }

    if (state == State.StreamsRunning) {
        boolean isVideoEnabledInCall = call.getCurrentParamsCopy().getVideoEnabled();
        if (isVideoEnabledInCall != isVideoEnabled) {
            isVideoEnabled = isVideoEnabledInCall;
            switchVideo(isVideoEnabled, false);
        }

        boolean routeToBT = getResources().getBoolean(R.bool.route_audio_to_bluetooth_if_available);
        if (routeToBT && LinphoneManager.isInstanciated() && !isSpeakerEnabled) {
            LinphoneManager.getInstance().routeToBluetoothIfAvailable();
        } else {
            // The following should not be needed except some devices need
            // it (e.g. Galaxy S).
            LinphoneManager.getLc().enableSpeaker(isSpeakerEnabled);
        }

        isMicMuted = LinphoneManager.getLc().isMicMuted();
        enableAndRefreshInCallActions();

        if (status != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    status.refreshStatusItems(call, isVideoEnabled);
                }
            });
        }
    }
    refreshInCallActions();

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            refreshCallList(getResources());
        }
    });

    if (state == State.CallUpdatedByRemote) {
        // If the correspondent proposes video while audio call
        boolean isVideoEnabled = LinphoneManager.getInstance().isVideoEnabled();
        if (!isVideoEnabled) {
            acceptCallUpdate(false);
            return;
        }

        boolean remoteVideo = call.getRemoteParams().getVideoEnabled();
        boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled();
        boolean autoAcceptCameraPolicy = LinphoneManager.getInstance().isAutoAcceptCamera();
        if (remoteVideo && !localVideo && !autoAcceptCameraPolicy
                && !LinphoneManager.getLc().isInConference()) {
            mHandler.post(new Runnable() {
                public void run() {
                    showAcceptCallUpdateDialog();

                    timer = new CountDownTimer(SECONDS_BEFORE_DENYING_CALL_UPDATE, 1000) {
                        public void onTick(long millisUntilFinished) {
                        }

                        public void onFinish() {
                            acceptCallUpdate(false);
                        }
                    }.start();
                }
            });
        }
        // else if (remoteVideo && !LinphoneManager.getLc().isInConference()
        // && autoAcceptCameraPolicy) {
        // mHandler.post(new Runnable() {
        // @Override
        // public void run() {
        // acceptCallUpdate(true);
        // }
        // });
        // }
    }

    mHandler.post(new Runnable() {
        public void run() {
            transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
        }
    });
}

From source file:dk.bearware.gui.MainActivity.java

void createStatusTimer() {

    final TextView connection = (TextView) findViewById(R.id.connectionstat_textview);
    final TextView ping = (TextView) findViewById(R.id.pingstat_textview);
    final TextView total = (TextView) findViewById(R.id.totalstat_textview);
    final int defcolor = connection.getTextColors().getDefaultColor();

    if (stats_timer == null) {
        stats_timer = new CountDownTimer(10000, 1000) {

            ClientStatistics prev_stats;

            public void onTick(long millisUntilFinished) {

                if (ttclient == null || accessibilityAssistant.isUiUpdateDiscouraged())
                    return;
                filesAdapter.performPendingUpdate();

                int con = R.string.stat_offline;
                int con_color = Color.RED;
                int flags = ttclient.getFlags();
                if ((flags & ClientFlag.CLIENT_CONNECTED) == ClientFlag.CLIENT_CONNECTED) {
                    con = R.string.stat_online;
                    con_color = Color.GREEN;
                } else if ((flags & ClientFlag.CLIENT_CONNECTING) == ClientFlag.CLIENT_CONNECTING) {
                    con = R.string.stat_connecting;
                }/*from  www  .  j  a  v a 2s. c o m*/

                connection.setText(con);
                connection.setTextColor(con_color);

                ClientStatistics stats = new ClientStatistics();
                if (!ttclient.getClientStatistics(stats))
                    return;

                if (prev_stats == null)
                    prev_stats = stats;

                long totalrx = stats.nUdpBytesRecv - prev_stats.nUdpBytesRecv;
                long totaltx = stats.nUdpBytesSent - prev_stats.nUdpBytesSent;
                long voicerx = stats.nVoiceBytesRecv - prev_stats.nVoiceBytesRecv;
                long voicetx = stats.nVoiceBytesSent - prev_stats.nVoiceBytesSent;
                long deskrx = stats.nDesktopBytesRecv - prev_stats.nDesktopBytesRecv;
                long desktx = stats.nDesktopBytesSent - prev_stats.nDesktopBytesSent;
                long mfrx = (stats.nMediaFileAudioBytesRecv + stats.nMediaFileVideoBytesRecv)
                        - (prev_stats.nMediaFileAudioBytesRecv + prev_stats.nMediaFileVideoBytesRecv);
                long mftx = (stats.nMediaFileAudioBytesSent + stats.nMediaFileVideoBytesSent)
                        - (prev_stats.nMediaFileAudioBytesSent + prev_stats.nMediaFileVideoBytesSent);

                String str;
                if (stats.nUdpPingTimeMs >= 0) {
                    str = String.format("%1$d", stats.nUdpPingTimeMs);
                    ping.setText(str);

                    if (stats.nUdpPingTimeMs > 250) {
                        ping.setTextColor(Color.RED);
                    } else {
                        ping.setTextColor(defcolor);
                    }
                }

                str = String.format("%1$d/%2$d KB", totalrx / 1024, totaltx / 1024);
                total.setText(str);

                prev_stats = stats;
            }

            public void onFinish() {
                start();
            }
        }.start();
    }

}

From source file:com.almalence.opencam.ApplicationScreen.java

@Override
public void relaunchCamera() {
    if (!CameraController.isRemoteCamera()) {
        if (CameraController.isUseCamera2() || ApplicationScreen.getPluginManager().isRestart()) {
            new CountDownTimer(100, 100) {
                public void onTick(long millisUntilFinished) {
                    // Not used
                }/*from www  . j  a va 2  s.c  om*/

                public void onFinish() {
                    ApplicationScreen.getPluginManager().switchMode(ConfigParser.getInstance()
                            .getMode(ApplicationScreen.getPluginManager().getActiveModeID()));
                }
            }.start();
        } else {
            // Need this for correct exposure control state, after switching
            // DRO-on/DRO-off in single mode.
            guiManager.onPluginsInitialized();
        }
    } else {
        ApplicationScreen.getGUIManager().setCameraModeGUI(0);
        ApplicationScreen.instance.pauseMain();
        ApplicationScreen.instance.switchingMode(false);
        ApplicationScreen.instance.resumeMain();
    }
}

From source file:me.trashout.fragment.DashboardFragment.java

private void startHuntingMode(final long totalDurationTimeInMilis, final long counterTimeInMilis) {
    dashboardTrashHunterProgressBar.setProgress(100);

    int barVal = (int) ((((double) counterTimeInMilis) / (double) (totalDurationTimeInMilis)) * 100.0);
    dashboardTrashHunterProgressBar.setProgress(barVal);

    Log.d(TAG, "startHuntingMode: barVal = " + barVal);

    long seconds = counterTimeInMilis / 1000;
    dashboardTrashHunterTimer/*from w w w  . j  a  va 2 s  .  c o  m*/
            .setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));

    if (countDownTimer != null)
        countDownTimer.cancel();
    countDownTimer = new CountDownTimer(counterTimeInMilis, 500) {
        // 500 means, onTick function will be called at every 500 milliseconds

        @Override
        public void onTick(long leftTimeInMilliseconds) {
            int barVal = (int) ((((double) leftTimeInMilliseconds) / (double) (totalDurationTimeInMilis))
                    * 100.0);
            dashboardTrashHunterProgressBar.setProgressWithAnimation(barVal, 2500);

            long seconds = leftTimeInMilliseconds / 1000;
            dashboardTrashHunterTimer
                    .setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
        }

        @Override
        public void onFinish() {
            showToast(R.string.trashHunter_finished);
            dashboardTrashHunterTimer.setText("");
            setHunterMode(false, 0, 0);
        }
    }.start();

    countDownTimer.onTick(counterTimeInMilis);
}

From source file:com.almalence.opencam.PluginManager.java

private void delayedCapture(int delayInterval) {
    initializeSoundPlayers(//from  w  w  w.  ja  va2  s.c  om
            ApplicationScreen.getAppResources().openRawResourceFd(R.raw.plugin_capture_selftimer_countdown),
            ApplicationScreen.getAppResources()
                    .openRawResourceFd(R.raw.plugin_capture_selftimer_finalcountdown));
    countdownHandler.removeCallbacks(flashOff);
    finalcountdownHandler.removeCallbacks(flashBlink);

    timer = new CountDownTimer(delayInterval * 1000 + 500, 1000) {
        public void onTick(long millisUntilFinished) {
            countdownView.setRotation(90 - MainScreen.getOrientation());
            countdownView.setText(String.valueOf(millisUntilFinished / 1000));
            countdownView.clearAnimation();
            countdownLayout.setVisibility(View.VISIBLE);
            countdownView.startAnimation(countdownAnimation);

            if (!delayedCaptureFlashPrefCommon && !delayedCaptureSoundPrefCommon)
                return;

            TickEverySecond((millisUntilFinished / 1000 <= 1) ? true : false);

            if (delayedCaptureFlashPrefCommon) {
                if (millisUntilFinished > 1000) {
                    try {
                        flashModeBackUp = CameraController.getFlashMode();
                        CameraController.setCameraFlashMode(CameraParameters.FLASH_MODE_TORCH);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("Self-timer", "Torch exception: " + e.getMessage());
                    }
                    countdownHandler.postDelayed(flashOff, 50);
                }
            }
        }

        public void onFinish() {
            countdownView.clearAnimation();
            countdownLayout.setVisibility(View.GONE);

            countdownHandler.removeCallbacks(flashOff);
            finalcountdownHandler.removeCallbacks(flashBlink);
            if (delayedCaptureFlashPrefCommon)
                if (CameraController.getSupportedFlashModes() != null)
                    CameraController.setCameraFlashMode(flashModeBackUp);

            Message msg = new Message();
            msg.what = ApplicationInterface.MSG_DELAYED_CAPTURE;
            ApplicationScreen.getMessageHandler().sendMessage(msg);

            timer = null;
        }
    };
    timer.start();
}