Passing Countdown Timer beetwen Activities in Android - android

I'm trying to pass the a CountDownTimer value from Activity 1(PrimerNivel) to Activity 2(SegundoNivel)and start the CountDownTimer in Activity 2 from the value that got from the Activity 1.
But the CountDownTimer in Activity 2 is reset to zero. I can't find the error. could someone help me?
This is the code
Activity 1:
public class PrimerNivel extends InicioActivity {
private TextView cuentaRegresiva;
long startTime = 60 * 1000;
private final long interval = 1 * 1000;
MyCountDownTimer countDownTimer;
long tiempoRestante;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
countDownTimer = new MyCountDownTimer(startTime, interval);
cuentaRegresiva.setText(cuentaRegresiva.getText() + String.valueOf(startTime / 1000));
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
cuentaRegresiva.setText("");
}
#Override
public void onTick(long millisUntilFinished) {
tiempoRestante= millisUntilFinished;
cuentaRegresiva.setText(""+millisUntilFinished/1000);
}}
OnClickListener siguiente =new OnClickListener(){
public void onClick(View arg0) {
Intent aNivelSiguiente = new Intent(PrimerNivel.this, SegundoNivel.class);
aNivelSiguiente.putExtra("regresivaAnterior", tiempoRestante);
startActivity(aNivelSiguiente);
PrimerNivel.this.finish();
}};
}
Activity 2:
public class SegundoNivel extends InicioActivity {
private TextView cuentaRegresiva;
long startTime;
private final long interval = 1 * 1000;
MyCountDownTimer countDownTimer;
Bundle bundle;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
countDownTimer = new MyCountDownTimer(startTime, interval);
bundle = getIntent().getExtras();
startTime= bundle.getLong("regresivaAnterior")/1000;
cuentaRegresiva.setText(""+startTime);
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
cuentaRegresiva.setText("");
}
#Override
public void onTick(long millisUntilFinished) {
cuentaRegresiva.setText(""+millisUntilFinished/1000);
}}

You are creating the CountDownTimer before getting the value. Simply move the code that creates the timer to below where you get the value.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
bundle = getIntent().getExtras();
startTime= bundle.getLong("regresivaAnterior")/1000;
// move it here after you've gotten the value
countDownTimer = new MyCountDownTimer(startTime, interval);
cuentaRegresiva.setText(""+startTime);
countDownTimer.start();
You may need to cancel your first timer to get the correct value at the correct time. Try calling
countDownTimer.cancel();
countDownTimer = null;
before creating the Intent. Also, you are dividing the startTime by 1000 after you get the value from the Intent. I'm not sure you want to be doing that.

Related

Reset value to default when using OnclickListener in Android

I'm trying to do some example about countdown timer using Button and set OnclickListener for that Button. My Default value is 10 and it will be decrease each second, how can i reset my value back to 10?
CountDownTimer cannot be restarted, it can only be used once. You either have to create your own count down class that can handle being restarted, or just create a new instance of your CountDownTimer and cancel the old instance.
See the example code below where we have a CountDownTimer that counts down for 10 seconds in 1 second intervals, a Button that resets the timer when clicked (by cancelling the current timer and starting a new one), and a TextView that displays the time left in the current timer.
public class YourActivity extends Activity {
private CountDownTimer countDownTimer;
private TextView timerDisplayTextView;
private static final long TEN_SECONDS = TimeUnit.SECONDS.toMillis(10);
private static final long COUNTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(1);
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Button myButton; // initialized here
// timerDisplayTextView initialized here
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
showTimeInTextView(TEN_SECONDS);
}
});
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
countDownTimer.cancel();
}
private void showTimeInTextView(long millisecondsLeft) {
timerDisplayTextView.setText(TimeUnit.MILLISECONDS.toSeconds(millisecondsLeft) + " seconds left");
}
private CountDownTimer getNewCountDownTimer(long length) {
return new CountDownTimer(length, COUNTDOWN_INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
showTimeInTextView(millisUntilFinished);
}
#Override
public void onFinish() {
}
};
}
}

Close and go to an activity after user downtime

I want to make a method (service, alarm, etc.) that can be calculated after x downtime user with the app
Which closes the current activity
and will send the initial activity (login)
Thank you very much
http://androidbite.blogspot.in/2012/11/android-count-down-timer-example.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Refer this link and some examples on countdown timer if you want to use this.
I answer
code is
private long startTime=15*60*1000; // 15 MINS IDLE TIME
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTimer = new MyCountDownTimer(startTime, interval);
}
#Override
public void onUserInteraction(){
super.onUserInteraction();
//Reset the timer on user interaction...
countDownTimer.cancel();
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//DO WHATEVER YOU WANT HERE
// CIERRA LA APP MATANDO EL PROCESO Y VUELVE A ABRIRLO.
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onTick(long millisUntilFinished) {
}
}
use
act.finishAffinity();
act.startActivity(new Intent(act, actMain.class));

how to get value from countdowntimer and display into toast

i have countdown timer from 1 to 9999 if i click start button the count will start, but if click stop button i need to get current value from countdown and display that value in toast but the countdown could not stop if i click stop button please help me
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView ;
private final long startTime = 9999 * 1;
private final long interval = 1 *1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1));
}
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
/*countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");*/
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
}
}
thank you
Here is my countdown timer:
QuestionCountdownTimer
public class QuestionCountdownTimer extends CountDownTimer {
private TextView remainingTimeDisplay;
private Context context;
public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) {
super(millisInFuture, countDownInterval);
this.context = context;
this.remainingTimeDisplay = remainingTimeDisplay;
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
remainingTimeDisplay.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show();
}
}
Note:
TextView remainingTimeDisplay
remainingTimeDisplay.setText(hms);
I use it to display the remaining time using a TextView
Here I call the timer:
//Start Quiz timer
QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay);
timer.start();
-first parameter: this - I use it for context to show Toast message
-second parameter: 10000 - total time (10 sec)
-third parameter: 1000 - countdown interval (1 sec)
-last parameter: dispaly remaining time in real time
Tested and working
Create your CountDownTimer like this:
public class MyCountDownTimer extends CountDownTimer
{
private long timePassed = 0;
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished)
{
timePassed++;
text.setText("" + millisUntilFinished / 1);
}
public long getTimePassed()
{
return timePassed;
}
}
And on your onClick just do:
((MyCoundDownTimer) countDownTimer).getTimePassed();
to retrieve the time and set your textview text to it.
You should use handler
private Handler tickResponseHandler = new Handler() {
public void handleMessage(Message msg) {
int time = msg.what;
//make toast or do what you want
}
}
and pass it to MyCountDownTimer constructor
private Handler handler;
public MyCountDownTimer(long startTime, long interval, Handler handler) {
super(startTime, interval);
this.handler = handler;
}
And send message
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
Message msg = new Message();
msg.what = millisUntilFinished/1;
handler.sendMessage(msg);
}
That's all you need to do :)

How to display a timer in activity in Android

I want to show timer, with every second. After 20 seconds I want that activity to call itself.
But when I don't display the timer it waits for 20 seconds as I wish to do but as soon as I implement code to display timer it just starts and suddenly stops suddenly.
Here is my code. Please help me out.
public class MainActivity extends Activity {
public int time=20;
Button end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread timerdisp = new Thread(){
TextView tv = (TextView) findViewById(R.id.timer);
public void run(){
try{
sleep(1000); // sleep for 1 seconds
tv.setText(String.valueOf(time));
time-=1;
if(time==0){
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
run();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
};
timerdisp.start();
);
}
Android provides a better facility of CountDownTimer, may be you should use that. As it provides many inbuilt methods and runs on background thread by default.
You can use onFinish() method to execute your call to the activity.
Here is an example of the same.
Try Below Code:
private long ms=0;
private long splashTime=2000;
private boolean splashActive = true;
private boolean paused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hides the titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {}
finally {
Intent intent = new Intent(Splash.this, Home.class);
startActivity(intent);
}
}
};
mythread.start();
}
and you can try this also
public class MainActivity extends Activity {
private CountDownTimer countDownTimer;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(String.valueOf(startTime / 1000));
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),xxxx.class);
startActivity(intent);
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
}
}
}
Use runOnUiThread
This acts as a normal Thread and will not allow your UI to sleep.
and the system will not hang.
or you can also use AsyncTask. I will prefer you using AsyncTask.
Use below code to call the function for every 20 seconds.
private Timer timer;
TimerTask refresher;
timer = new Timer();
refresher = new TimerTask() {
public void run() {
// your code to call every 20 seconds.
};
};
// first event immediately, following after 20 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000*20);
Use below lines to show the time :
package com.example.test;
public class MainActivity extends Activity {
private Long startTime;
public native String getLastShotName();
public native String colorNormal();
public native String flipImage();
public native String forceInvertColor();
public native String getLastTitle();
public native String myMethod();
boolean mbFlip = false;
private Timer timer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimerTask refresher;
startTime = System.currentTimeMillis();
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(updateTimer, 1000);
}
private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.textView1);
Long spentTime = System.currentTimeMillis() - startTime;
Long minius = (spentTime/1000)/60;
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};
}

How to call method from another class in Android?

I've been trying to call a method from another class.
I have 2 classes. Timer.class and DecisionMaking.class. The Timer class is suppose to call a method (I just used a toast for now) from DecisionMaking.class once the timer is onFinish(). There is no error in my codes but when the timer finish counting, the method was not called and the emulator ask to Force Close. Both of the classes are in the same package. Is there anything that I'm missing?
Timer.class
public class Timer extends Activity{
TextView timeDisplay;
MyCount timer;
int length = 10000;
long startTime;
long timeRemaining;
DecisionMaking decisionmaking;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timeDisplay = (TextView) findViewById(R.id.timer);
timer = new MyCount(length, 1000);
timer.start();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
DecisionMaking decisionmaking = new DecisionMaking();
decisionmaking.sendSms();
timer.start();
}
public void onTick(long millisUntilFinished) {
timeDisplay.setText("Time:" + millisUntilFinished / 1000);
}
}
}
DecisionMaking.class
public class DecisionMaking extends Timer{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendSms();
}
public boolean sendSms() {
Calendar cal = Calendar.getInstance();
Date d = cal.getTime();
int hour = d.getHours();
if (hour > 0 && hour < 6)
return false;
else
{
//Call SMS class here, remove toast
Toast.makeText(getBaseContext(), "SMS sent.", Toast.LENGTH_SHORT).show();
return true;
}
}
}
i think no need to call timer.start in the onFinish() method.

Categories

Resources