android countdown timer cancel vs timeup - android

I am just wondering when timeout occurs, onFinish() method is called and we can execute further code there. But for some reason if timer is cancelled either manually or because of error does onFinish() get called? Or it just cancels the timer without calling any method.
Here are My two Counters.
Counter1:
class Counter1 extends CountDownTimer {
public Counter1(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
Log.d(TAG, " Timer1 Finished");
//Add 2min to second timer
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
/
}
}
class Counter2 extends CountDownTimer {
public Counter2(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
Log.d(TAG, "Timer2 Finished");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}
I have to add 2 min to second timer is its values is less than add 2minutes to its existing else it will continue with its timer.

OnFinish() will not called at timer cancel you have to start it again, You can store time value in shared preference when application get crashed you have start time from saved time.
like
CountDownTimer countDownTimerFixed = new CountDownTimer(Time, Tick) {
#Override
public void onTick(long millisUntilFinished) {
RTSharedPrefUtils.saveStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, millisUntilFinished+ "");
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
RTSharedPrefUtils.saveStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, 0 + "");
this.start();
}
};
if timer is canceled,
Timer=Long.parseLong(RTSharedPrefUtils.fetchStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,RTSharedPrefUtils.DEFAULT_DOWNLOAD_TIMER));
countDownTimer = new CountDownTimer(Timer, Tick) {
#Override
public void onTick(long millisUntilFinished) {
RTSharedPrefUtils.saveStringPrefernce(
RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,millisUntilFinished + "");
Log.d(TAG," Normalcount:\t"+ (Long.parseLong(RTSharedPrefUtils.fetchStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,RTSharedPrefUtils.DEFAULT_DOWNLOAD_TIMER)))/ 1000);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
RTSharedPrefUtils.saveStringPrefernce(
RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, 0 + "");
countDownTimerFixed.start();
}
};
countDownTimer.start();

Related

schedule timer for dialog in android

I am in a situation where I need to display the Rate dialog based on the following flow
Open the app (First time )--> display dialog every 2 minutes
If rated --> display dialog next month
If clicked on later button --> display dialog next week.
String rate_value=myPref.getString("rate_value", "later");
Log.e("rate", String.valueOf(rate_value));
if (rate_value=="later") {
initCalendarNextWeek();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextWeekDate);
}
else if (rate_value=="now") {
initCalendarNextMonth();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextMonthDate);
}
else if (rate_value=="no_thanks") {
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, 120000, 120000);
}
public void initCalendarNextMonth(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextMonthDate=new Date();
nextMonthDate.setDate(cal_day);
nextMonthDate.setMonth(cal_month+1);
nextMonthDate.setYear(cal_year);
}
public void initCalendarNextWeek(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextWeekDate=new Date();
nextWeekDate.setDate(cal_day+7);
nextWeekDate.setMonth(cal_month);
nextWeekDate.setYear(cal_year);
}
Ok, so maybe look at Calendar class. The set methods of Date are deprecated so instead of using
nextMonthDate = new Date()
rather maybe use
nextMonthDate = new Calendar();
because then you can use the methods stated in the Calendar documentation such as add instead of using the setDate or setMonth. I hope this helps.

android, song controller and seek bar in media player

in my music player how I can let my seek bar back to the starting point after I clicked stop button? and set the text field of total duration and current position to zero ?? the problem happen when I click stop and then click play button ?in my log cat the error is "Attempt to call getDuration without a valid mediaplayer"
#Override
protected void onCreate(Bundle savedInstanceState) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton play_btn= (ImageButton) findViewById(R.id.iv_play);
ImageButton backward_btn=(ImageButton)findViewById(R.id.imageView_backward);
ImageButton forward_btn= (ImageButton) findViewById(R.id.imageView_forward);
ImageButton stop_btn= (ImageButton) findViewById(R.id.imageView_stop);
ImageButton pause_btn= (ImageButton)findViewById(R.id.imageView_pause);
ImageButton shuffle_btn = (ImageButton) findViewById(R.id.imageView_shuffle);
song = MediaPlayer.create(getApplicationContext() ,R.raw.adele);
songProgressBar= (SeekBar) findViewById(R.id.seekBar1);
songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = song.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
song.seekTo(currentPosition);
UpdateProgressBar();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PauseSong(); }
private void PauseSong() {
// TODO Auto-generated method stub
song.pause();
}
});
stop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StopSong();
}
private void StopSong() {
// TODO Auto-generated method stub
song.stop();
}
});
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlaySong();
}
private void PlaySong() {
// TODO Auto-generated method stub
song.start();
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
UpdateProgressBar();
}
});
}
private void UpdateProgressBar() {
// TODO Auto-generated method stub
mHandler.postDelayed(mUpdateTimeTask, 100);
}
Runnable mUpdateTimeTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
totalDuration = song.getDuration();
currentDuration = song.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
protected void onPause() {finish();}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Retrieve the duration from the onPrepared callback...this will ensure the music(audio) is properly loaded before you attempt to get it's duration.
song.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer song) {
int duration = song.getDuration();
song.start();
controller.show();
}
});
StopSong():
private void StopSong() {
if (song != null) {
song.stop();
song.release();
}
}
for the duration text field, i will used global variable to access from all functions.
#Override
protected void onCreate(Bundle savedInstanceState) {
int totalDuration 0;
.
.
.
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
totalDuration = song.getDuration(); // here
.
.
.
private void StopSong() {
if (song!=null) {
song.stop();
song.release();
totalDuration = 0; // here
}
i hope this helps!

CountDownTimer's OnFinish() fires when the timer is Halfway in its countdown

I've used a CountDownTimer in an android project, and what happens, is, my OnFinish() fires while the CountDown is in its half way stage.
Here is the code :
public void ShowNotice(){
cdt = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(con,"Game Starts In :"+String.valueOf(millisUntilFinished/1000),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
RemoveButtonText();
}
};
cdt.start();
}
RemoveButtonText();// This method gets executed even when the count down isn't finished i.e Toast shows '5'.
Note : cdt is declared as a private member variable inside a class of type CountDownTimer.
Need help :)
I've solved the problem.
public void ShowNotice(){
cdt = new CountDownTimer(20000, 2000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(con,"Game Starts In :"+String.valueOf(millisUntilFinished/2000),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(con,"Game Starts Now!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
RemoveButtonText();
}
};
cdt.start();
}
The catch was in getting this
cdt = new CountDownTimer(20000, 2000)
right.
Thank you :)

Create A session timeout for application

I have many activities in my application(eg A->B->C->D)...A is a login activity...i have a countdowntimer that i am using for a session timeout.. What i want to do is....logout the user.. i.e put him back to activity A if there is no user interaction in the activities B,C,D... i have extended my application class and instantiated my timer in that...But in this activity i cant clear the stacktop of the previous activities i.e the line
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Throws a exception..Any idea how will i solve this problem...Here is my code...
public class MyApp extends Application {
MyCount count;
#Override
public void onCreate() {
// reinitialize variable
count = new MyCount(5000, 1000);
}
public void startcounter() {
count.start();
}
public void cancelcounter() {
count.cancel();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
try{
Intent my = new Intent(getApplicationContext(), Login.class);
my.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(my);
Toast.makeText(getApplicationContext(), "Finsihed",
Toast.LENGTH_LONG).show();
}
catch(Exception e )
{
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), String.valueOf(millisUntilFinished/1000),
// Toast.LENGTH_LONG).show();
}
}
}

How to cancel CountDownTimer after an OnPause?

Hey im trying to add countdown timers to an arraylist but it is crashing. It is crashing once I try to add one countdowntimer . Was wondering is there anything I could do to fix it?
ArrayList<CountDownTimer> timers;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
toggleLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Checker = new CountDownTimer(1200000, 60000)
{
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
//does stuff
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
Checker.start();
timers.add(Checker);
}
}
});
}
I think you need to initialize the arraylist, so might be throwing null pointer exception.
timers=new ArrayList<CountDownTimer>();
You need to initialize your timers arraylist.
ex.
ArrayList<CountDownTimer> timers = new ArrayList<CountDownTimer>();

Categories

Resources