List of usage examples for android.os CountDownTimer CountDownTimer
public CountDownTimer(long millisInFuture, long countDownInterval)
From source file:galilei.kelimekavanozu.activity.PoemBuilderActivity.java
private CountDownTimer createCountdown(long remainingSeconds) { countdownView.setCurrentTime(remainingSeconds); return new CountDownTimer(remainingSeconds * 1000, 1000) { public void onTick(long millisUntilFinished) { final long secsToFinish = millisUntilFinished / 1000; if (secsToFinish == 10) { countdownText.setTextColor(getResources().getColor(R.color.red_font)); countdownView.setColor(getResources().getColor(R.color.red_font)); shuffleText.setTextColor(getResources().getColor(R.color.red_font)); }/*from w w w . j av a 2 s.c om*/ countdownText.setText("" + secsToFinish); countdownView.setCurrentTime(secsToFinish); Crashlytics.setLong(App.CRASHLYTICS_KEY_COUNTDOWN, secsToFinish); } public void onFinish() { Crashlytics.log("PoemBuilder: countdown timer ended, saving poem..."); if (poemContainer.getChildCount() > 0) { createPoem(); } else { Crashlytics.log("PoemBuilder: Countdown finishes counting, no words added"); onBackPressed(); } } }.start(); }
From source file:com.pertamina.tbbm.rewulu.ecodriving.MainActivity.java
@Override public void appExit() { // TODO Auto-generated method stub if (!cdExit) { cdExit = true;/* ww w. j a v a2 s . c o m*/ new CountDownTimer(1500, 300) { @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } @Override public void onFinish() { // TODO Auto-generated method stub try { cdExit = false; } catch (Exception e) { // TODO: handle exception } } }.start(); Utils.toast(getApplicationContext(), R.string.exit_confirm); } else this.finish(); }
From source file:co.taqat.call.CallActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; if (getResources().getBoolean(R.bool.orientation_portrait_only)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }/*from w ww . j a va 2s . c o m*/ getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); setContentView(R.layout.call); isTransferAllowed = getApplicationContext().getResources().getBoolean(R.bool.allow_transfers); if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { BluetoothManager.getInstance().initBluetooth(); } cameraNumber = AndroidCameraConfiguration.retrieveCameras().length; try { // Yeah, this is hidden field. field = PowerManager.class.getClass().getField("PROXIMITY_SCREEN_OFF_WAKE_LOCK").getInt(null); } catch (Throwable ignored) { } powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(field, getLocalClassName()); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mListener = new LinphoneCoreListenerBase() { @Override public void messageReceived(LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) { displayMissedChats(); } @Override public void callState(LinphoneCore lc, final LinphoneCall call, LinphoneCall.State state, String message) { if (LinphoneManager.getLc().getCallsNb() == 0) { finish(); return; } if (state == State.IncomingReceived) { startIncomingCallActivity(); return; } else if (state == State.Paused || state == State.PausedByRemote || state == State.Pausing) { if (LinphoneManager.getLc().getCurrentCall() != null) { enabledVideoButton(false); } if (isVideoEnabled(call)) { showAudioView(); } } else if (state == State.Resuming) { if (LinphonePreferences.instance().isVideoEnabled()) { status.refreshStatusItems(call, isVideoEnabled(call)); if (call.getCurrentParamsCopy().getVideoEnabled()) { showVideoView(); } } if (LinphoneManager.getLc().getCurrentCall() != null) { enabledVideoButton(true); } } else if (state == State.StreamsRunning) { switchVideo(isVideoEnabled(call)); enableAndRefreshInCallActions(); if (status != null) { videoProgress.setVisibility(View.GONE); status.refreshStatusItems(call, isVideoEnabled(call)); } } else if (state == State.CallUpdatedByRemote) { // If the correspondent proposes video while audio call boolean videoEnabled = LinphonePreferences.instance().isVideoEnabled(); if (!videoEnabled) { acceptCallUpdate(false); } boolean remoteVideo = call.getRemoteParams().getVideoEnabled(); boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled(); boolean autoAcceptCameraPolicy = true;//LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !LinphoneManager.getLc().isInConference()) { showAcceptCallUpdateDialog(); timer = new CountDownTimer(SECONDS_BEFORE_DENYING_CALL_UPDATE, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { //TODO dismiss dialog acceptCallUpdate(false); } }.start(); /*showAcceptCallUpdateDialog(); timer = new CountDownTimer(SECONDS_BEFORE_DENYING_CALL_UPDATE, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { //TODO dismiss dialog } }.start();*/ } // else if (remoteVideo && !LinphoneManager.getLc().isInConference() && autoAcceptCameraPolicy) { // mHandler.post(new Runnable() { // @Override // public void run() { // acceptCallUpdate(true); // } // }); // } } refreshIncallUi(); transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null); } @Override public void callEncryptionChanged(LinphoneCore lc, final LinphoneCall call, boolean encrypted, String authenticationToken) { if (status != null) { if (call.getCurrentParamsCopy().getMediaEncryption().equals(LinphoneCore.MediaEncryption.ZRTP) && !call.isAuthenticationTokenVerified()) { status.showZRTPDialog(call); } status.refreshStatusItems(call, call.getCurrentParamsCopy().getVideoEnabled()); } } }; if (findViewById(R.id.fragmentContainer) != null) { initUI(); if (LinphoneManager.getLc().getCallsNb() > 0) { LinphoneCall call = LinphoneManager.getLc().getCalls()[0]; if (LinphoneUtils.isCallEstablished(call)) { enableAndRefreshInCallActions(); } } if (savedInstanceState != null) { // Fragment already created, no need to create it again (else it will generate a memory leak with duplicated fragments) isSpeakerEnabled = savedInstanceState.getBoolean("Speaker"); isMicMuted = savedInstanceState.getBoolean("Mic"); isVideoCallPaused = savedInstanceState.getBoolean("VideoCallPaused"); refreshInCallActions(); return; } else { isSpeakerEnabled = LinphoneManager.getLc().isSpeakerEnabled(); isMicMuted = LinphoneManager.getLc().isMicMuted(); } Fragment callFragment; if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) { callFragment = new CallVideoFragment(); videoCallFragment = (CallVideoFragment) callFragment; displayVideoCall(false); LinphoneManager.getInstance().routeAudioToSpeaker(); isSpeakerEnabled = true; } else { callFragment = new CallAudioFragment(); audioCallFragment = (CallAudioFragment) callFragment; } if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { BluetoothManager.getInstance().routeAudioToBluetooth(); } callFragment.setArguments(getIntent().getExtras()); getFragmentManager().beginTransaction().add(R.id.fragmentContainer, callFragment) .commitAllowingStateLoss(); } }
From source file:org.sirimangalo.meditationplus.ActivityMain.java
@Override protected void onResume() { super.onResume(); isShowing = true;/*from ww w . j a v a 2s.co m*/ listVersion = -1; chatVersion = -1; restartTimer = true; refreshPeriod = Integer.parseInt(prefs.getString("refresh_period", "10")) * 1000; refreshPeriod = Math.max(refreshPeriod, 10); fullRefreshPeriod = Integer.parseInt(prefs.getString("full_refresh_period", "60")) * 1000; fullRefreshPeriod = Math.max(fullRefreshPeriod, 60); if (ct != null) ct.cancel(); ct = new CountDownTimer(fullRefreshPeriod, refreshPeriod) { @Override public void onTick(long l) { ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); if (l < fullRefreshPeriod - refreshPeriod && isShowing) { doSubmit(null, nvp, false); } } @Override public void onFinish() { if (isShowing) { listVersion = -1; chatVersion = -1; restartTimer = true; ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("full_update", "true")); doSubmit(null, nvp, false); } } }; loginToken = prefs.getString("login_token", ""); if (loginToken.equals("")) { Intent i = new Intent(this, ActivityMain.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!doingLogin) startActivity(i); } else { username = prefs.getString("username", ""); password = ""; doSubmit(null, new ArrayList<NameValuePair>(), false); } }
From source file:mgumiero9.com.talentcubetest.view.Camera2VideoFragment.java
@Override public void onViewCreated(final View view, Bundle savedInstanceState) { mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture); mButtonOk = (Button) view.findViewById(R.id.btn_ok); mButtonOk.setOnClickListener(this); myCountDown = (TextView) view.findViewById(R.id.countdown8); mButtonVideo = (Button) view.findViewById(R.id.video); mButtonVideo.setOnClickListener(this); //Log.e(TAG, "performed click: " + mButtonVideo.performClick()); Log.e(TAG, "started recording..."); Log.e(TAG, "This is the variable mIsRecordingVideo: " + mIsRecordingVideo); // Counting Down new CountDownTimer(45000, 1000) { public void onTick(long millisUntilFinished) { myCountDown.setText("" + ((millisUntilFinished / 1000) - 1)); }/*from w w w . jav a2 s . c om*/ public void onFinish() { //myCountDown.setText("done!"); //takePicture(); if (mIsRecordingVideo) { stopRecordingVideo(); Log.e(TAG, "stopping recording video... timer"); } VideoDisplay videoDisplay = new VideoDisplay(); getActivity().getFragmentManager().beginTransaction().replace(R.id.container, videoDisplay) .addToBackStack(null).commit(); } }.start(); }
From source file:com.mchp.android.PIC32_BTSK.PIC32_BTSK.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (D)//ww w . j a va 2 s . c o m Log.e(TAG, "+++ ON CREATE +++"); // delegated in Android 5.0 // Request the Action Bar. // requestWindowFeature(Window.FEATURE_ACTION_BAR); // Set up the action bar // actionBar = getSupportActionBar(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); // actionBar.setHomeButtonEnabled(true); // Get the window layout setContentView(R.layout.main); // Use toolbar instead of action bar toolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setIcon(R.drawable.app_icon); // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported on this device. Exit the app. if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } // Initialize the temperature log mTemperatures = new LinkedList<Integer>(); TemperatureFragment.initTemperatureList(mTemperatures, maxCount); // Set up the tab interface. Add one tab for each of the three fragments. mFragmentManager = this.getSupportFragmentManager(); mTabHost = (FragmentTabHost) findViewById(R.id.tabhost); mTabHost.setup(this, mFragmentManager, R.id.tabFrameLayout); mTabHost.addTab(mTabHost.newTabSpec("color").setIndicator("Color"), ColorFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("temperature").setIndicator("Temperature"), TemperatureFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("text").setIndicator("Text"), TextFragment.class, null); mTabHost.setOnTabChangedListener(this); // Set up the send delay count down timer. While it's counting down, no messages can be sent over Bluetooth. mSendTimer = new CountDownTimer(mSendDelay, mSendDelay) { public void onTick(long millisUntilFinished) { } public void onFinish() { mSendTimeElapsed = true; // Send the last color if (mLastColor != null) { sendMessage(mLastColor); mLastColor = null; return; } } }; // Get the input method manager for hiding the soft keyboard mgr = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); // Setup toasts mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); BTtoSocketThreadQueue = new ArrayBlockingQueue<String>(5); socketThreadToBtQueue = new ArrayBlockingQueue<String>(5); }
From source file:net.kidlogger.kidlogger.KLService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { //List file synchronizer listFileSync = new ListFileSync(this); // Check a previous file and send the file if exist checkPrevFiles();// w w w . j a v a 2 s.c o m // Handle outgoing call delay mHandler = new Handler() { public void handleMessage(Message msg) { String message = (String) msg.obj; if (message == null) return; //Log.i("KLS", "message: " + message); if (message.equals("start")) { delayNewCallEvent = new CountDownTimer(15000L, 1000L) { public void onTick(long millisUntilFinish) { } public void onFinish() { new Thread(new Runnable() { public void run() { //Log.i("KLS", "doAfterDelay"); doAfterDelay(); } }).start(); } }.start(); } else if (message.equals("stop")) { //Log.i("KLS", "Stop delay"); if (delayNewCallEvent != null) { delayNewCallEvent.cancel(); delayNewCallEvent = null; } } } }; // Define a BroadcastReceiver to detect if date is changed /*dateChanged = new BroadcastReceiver(){ public void onReceive(Context context, Intent intent){ String action = intent.getAction(); if(action != null && action.equals(Intent.ACTION_DATE_CHANGED)){ new Thread(new Runnable(){ public void run(){ checkPrevFiles(); app.logError(CN, "Date is changed"); } }).start(); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_DATE_CHANGED); registerReceiver(dateChanged, filter);*/ // Stub of remote service remoteServiceStub = new IRemoteService.Stub() { public void sendString(String string) throws RemoteException { runKeyEvent(string); } }; // Setup things to log setupLogging(); // Uploading files if (Settings.uploadLogs(this)) { mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (mAlarmManager == null) { app.logError(CN + "onStartCommand", "Couldn't get AlarmManager"); uploadOn = false; } else { //Intent i = new Intent(this, AlarmReceiver.class); Intent i = new Intent(KLService.ALARM_ACTION); mPI = PendingIntent.getBroadcast(this, 0, i, 0); mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), postSendingFreq, mPI); } //--------------------------------------------------------------------------------- /*mUploadData = new Runnable(){ public void run(){ new Thread(new Runnable(){ public void run(){ //doSendingFile(); doSendHtml(); checkDate(); if(!mIsRoaming) doSendMedia(); } }).start(); handlering.postDelayed(mUploadData, postSendingFreq); } }; handlering.postDelayed(mUploadData, postSendingFreq);*/ //--------------------------------------------------------------------------------- uploadOn = true; } // Log power boolean powerOn = getBoolPref("powerOff"); if (powerOn) { new Thread(new Runnable() { public void run() { sync.writeLog(".htm", Templates.getPowerLog(false)); } }).start(); //WriteThread wpl = new WriteThread(sync, ".htm", Templates.getPowerLog(false)); saveToPref("powerOff", false); } // Log start service logServiceState(true); app.mService = this; app.mServiceOnCreate = false; //Log.i(CN + "onStartCommand", "onStartCommand"); return START_STICKY; }
From source file:com.mov.android.camera2video.Camera2VideoFragment.java
@Override public void onViewCreated(final View view, Bundle savedInstanceState) { mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture); //mButtonVideo = (Button) view.findViewById(R.id.video); //mButtonVideo.setOnClickListener(this); //view.findViewById(R.id.info).setOnClickListener(this); mCountDownAnimation = new CountDownAnimation((TextView) getView().findViewById(R.id.pre_record), 3); mCountDownAnimation.setCountDownListener(this); mCountDownTimer = new CountDownTimer(mDuration, 100) { public void onTick(long millisUntilFinished) { //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); }//from w ww. j av a 2s .com public void onFinish() { stopRecordingVideo(); //closeCamera(); //stopBackgroundThread(); getActivity().getFragmentManager().popBackStackImmediate(); } }; mTimerView = (TimerView) getView().findViewById(R.id.timer); }
From source file:pro.dbro.bart.UsherService.java
private void makeLegCountdownTimer(long msUntilNext) { //make sure we don't leak any timers if (timer != null) timer.cancel();/*from w ww. jav a 2 s . c o m*/ // Make a new timer to expire EVENT_PADDING_MS before event timer = new CountDownTimer(msUntilNext - EVENT_PADDING_MS, UPDATE_INTERVAL_MS) { //new CountDownTimer(5000, 1000){ @Override public void onFinish() { // TODO Auto-generated method stub Vibrator v = (Vibrator) getSystemService(c.VIBRATOR_SERVICE); long[] vPattern = { 0, 400, 300, 400, 300, 400, 300, 400 }; v.vibrate(vPattern, -1); //if(didBoard) // if we've boarded, we're handling the last leg // currentLeg ++; didBoard = !didBoard; // Our next move is departing the final leg train if ((usherRoute.legs.size() == currentLeg + 1) && !didBoard) { NotificationCompat.Builder builder = new NotificationCompat.Builder(c); if (contentIntent == null) { Log.d("ContentIntent", "was null"); setContentIntent(); } builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.ic_launcher_notification) //.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img)) .setWhen(0).setTicker("This is your stop! Take care!"); notification = builder.getNotification(); mNM.notify(NOTIFICATION, notification); //TheActivity.removeStopServiceText(); stopSelf(); } // Our next move is departing the current leg's train else if (didBoard) { //Set timer for this leg's disembark time Date now = new Date(); long msUntilNext = ((((leg) usherRoute.legs.get(currentLeg)).disembarkTime.getTime() - now.getTime())); //Log.v("UsherState","leg: "+ String.valueOf(currentLeg)+ " / "+String.valueOf(usherRoute.legs.size())+" Boarded. Next: "+String.valueOf(msUntilNext)+"ms"); updateNotification(true); makeLegCountdownTimer(msUntilNext); // this cancels current timer } // Our next move is boarding the next leg's train else { currentLeg++; Date now = new Date(); long msUntilNext = ((((leg) usherRoute.legs.get(currentLeg)).boardTime.getTime() - now.getTime())); //Log.v("UsherState","leg: "+ String.valueOf(currentLeg)+ " / "+String.valueOf(usherRoute.legs.size())+" Waiting. Next: "+String.valueOf(msUntilNext)+"ms"); updateNotification(true); makeLegCountdownTimer(msUntilNext); } } @Override public void onTick(long arg0) { updateNotification(false); } }.start(); //timer.start(); // Set Reminder timer REMINDER_PADDING_MS ms before event if (msUntilNext > (REMINDER_PADDING_MS + 30 * 1000)) { // if next event is more than 30 seconds + REMINDER_PADDING_MS out, set reminder //avoid leaking timer if (reminderTimer != null) reminderTimer.cancel(); reminderTimer = new CountDownTimer(msUntilNext - REMINDER_PADDING_MS, msUntilNext - REMINDER_PADDING_MS) { @Override public void onFinish() { // TODO: Is this a good time for updating? //requestDataUpdate(); updateNotification(true); Vibrator v = (Vibrator) getSystemService(c.VIBRATOR_SERVICE); long[] vPattern = { 0, 400, 300, 400 }; v.vibrate(vPattern, -1); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }.start(); } }
From source file:com.google.sample.beaconservice.MainActivityFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); final ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar); progressBar.setProgress(0);/* ww w . j a v a 2 s. c om*/ progressBar.getProgressDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY); scanButton = (Button) rootView.findViewById(R.id.scanButton); scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Utils.setEnabledViews(false, scanButton); arrayAdapter.clear(); scanner.startScan(SCAN_FILTERS, SCAN_SETTINGS, scanCallback); Log.i(TAG, "starting scan"); client = new ProximityBeaconImpl(getActivity(), accountNameView.getText().toString()); CountDownTimer countDownTimer = new CountDownTimer(SCAN_TIME_MILLIS, 100) { @Override public void onTick(long millisUntilFinished) { double i = (1 - millisUntilFinished / (double) SCAN_TIME_MILLIS) * 100; progressBar.setProgress((int) i); } @Override public void onFinish() { progressBar.setProgress(100); } }; countDownTimer.start(); Runnable stopScanning = new Runnable() { @Override public void run() { scanner.stopScan(scanCallback); Log.i(TAG, "stopped scan"); Utils.setEnabledViews(true, scanButton); } }; handler.postDelayed(stopScanning, SCAN_TIME_MILLIS); } }); accountNameView = (TextView) rootView.findViewById(R.id.accountName); accountNameView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pickUserAccount(); } }); // Set the account name from the shared prefs if we ever set it before. String accountName = sharedPreferences.getString("accountName", ""); if (!accountName.isEmpty()) { accountNameView.setText(accountName); } else { pickUserAccount(); } ListView listView = (ListView) rootView.findViewById(R.id.listView); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Beacon beacon = arrayAdapter.getItem(position); if (beacon.status.equals(Beacon.NOT_AUTHORIZED)) { new AlertDialog.Builder(getActivity()).setTitle("Not Authorized") .setMessage("You don't have permission to view the details of this beacon") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); return; } if (beacon.status.equals(Beacon.STATUS_UNSPECIFIED)) { return; } Bundle bundle = new Bundle(); bundle.putString("accountName", accountNameView.getText().toString()); bundle.putParcelable("beacon", arrayAdapter.getItem(position)); ManageBeaconFragment fragment = new ManageBeaconFragment(); fragment.setArguments(bundle); getFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(TAG) .commit(); } }); return rootView; }