I ve got this function here:
public void stoprecording()
{
this.recorder.stop();
this.recorder.reset();
this.recorder.release();
}
which stops the recoridng. This is within the class Audio. I also got this function here:
public void recordtimer(final int timer)
{
/*First Part with timer*/
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
CountDownTimer countDowntimer = new CountDownTimer(timer, 100000)
{
public void onTick(long millisUntilFinished) {}
public void onFinish() {
this.stoprecording();
}
};countDowntimer.start();
}
});
thread.start();
this.stoprecording();
}
also within the class Audio. I canĀ“t execute this.stoprecording(); because the class CountDownTimer doesn t have this function. How can I execute this function?
Looking at your code it seems there is no need to call stoprecording() from this, since it does not belong to CountDownTimer class you have defined.
Just call it like
public void onFinish() {
stoprecording();
}
or if you want to definitely use this, follow the #gary111 suggestion thus doing
public void onFinish() {
YourClass.this.stoprecording();
}
Related
I define the countdowntimer here.
Then, new countdowntimer is defined for this variable in an onclick method:
public void showQuestion(int questionNumber){
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
}
}.start();
}
Then i cancel this timer on another button' onclick method;
public void selectOption(View view) {
questionTimer.cancel();
}
In this time, it is succesfully cancelled. Then i am doing the same again. showQuestion method is working in the same way.
public void showQuestion(int questionNumber){
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
}
}.start();
}
It is started succesfully. When i want to cancel this timer on another button onclick method, it is not working. Not any error. I hope it could be clear. Thank you so much.
The issue with your code is the timer can be started multiple times (sometimes not intentional) before the first timer is finished or cancelled. In that case, when you try to cancel it, you can only cancel the first timer. To solve this issue, you only have to check whether the timer is running, if it is running, wait for it to finish or cancel.
Define a global parameter:
Boolean timerRunning = false;
public void showQuestion(int questionNumber){
if (timerRunning) return;
timerRunning = true;
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
timerRunning = false;
}
}.start();
}
Your selection option method can be changed to below: check if the timer is null before cancelling it.
public void selectOption(View view) {
if (questionTimer != null) questionTimer.cancel();
timerRunning = false;
}
public void selectOption(View view) {
questionTimer.cancel();
questionTimer = null;
}
I would like to set an EditText with a timer thanks to CountDownTimer.
My EditText write second by second the number 3 and 2 but for the 1 there is a lag (it take 1,5 to 2 seconds).
Maybe I do it wrong.
This is my code :
CountDownTimer mCountDownTimer = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
txt_timer.setText("GO");
}
};
mCountDownTimer.start();
That is because the UI thread is doing too much work. Try running a new thread on the UI thread itself:
runOnUiThread(new Runnable() {
public void run()
{
//Insert your code
}
});
}
Let me know if you can;t get this to work!
The memory in the device cause the problem. I found a solution running a new thread.
I have to declare int i=4; before and use this code :
new Thread() {
public void run() {
while (i-- > 1) {
try {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txt_timer.setText(String.valueOf(i));
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
txt_timer.setText("GO");
}
}.start();
My Timer doesn't stop running if I cancel it!
The Timer only stops if I shut down the whole app!
I don't know why the Timer is not cancelled. If I print out every try on cancelling the Timer I get hundrets of lines but the Timer does not stop!
My Class:
public class PlayActivity extends AppCompatActivity
implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaplayerEvent {
//region Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Initialize_Layout();
Initialize_Objects();
}
#Override
protected void onResume() {
super.onResume();
MusicService.setMediaPlayerEvent(this);
txvSongtitle.setText(serviceInterface.MP_getActualSong().getTitle());
Start_Timer();
}
#Override
protected void onPause() {
timer.cancel();
MusicService.clearMediaPlayerEvent();
super.onPause();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
//endregion
//region Methods
private void Start_Timer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (serviceInterface.MP_isPlaying()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
seekBar.setMax(serviceInterface.MP_getDuration());
seekBar.setProgress(serviceInterface.MP_getCurrentPosition());
}
});
}
else {
runOnUiThread(new Runnable() {
#Override
public void run() {
timer.cancel();
}
});
}
}
}, 0, 200);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
serviceInterface.MP_seekTo(progress);
Start_Timer();
}
}
//endregion
}
I hope you can help me!
Thanks!
I would suggest using a Thread instead of a Timer. Your Start_Timer()code would change to something like the following:
private Thread mTimerThread;
...
private void Start_Timer() {
mTimerThread = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
if (serviceInterface.MP_isPlaying()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
seekBar.setMax(serviceInterface.MP_getDuration());
seekBar.setProgress(serviceInterface.MP_getCurrentPosition());
}
});
} else {
interrupt();
}
Thread.sleep(200);
}
} catch (InterruptedException e) {
}
}
}
mTimerThread.start();
}
Threads are more efficient and lightweight and perfect for your needs. Plus, by setting the Thread to a global variable, you can make sure to call mTimerThread.interrupt(); during Android lifecycle events, such as onPause().
I hope this fixes your issue. Remember, the Java Thread is your friend!
You're creating and starting a new timer the user moves the seekbar (in onProgressChanged()). That also means you lose the reference to the old one. When isPlaying turns false, all the timers will try to cancel timer -- which only references the most recent one.
In my code I have a thread. You can see the code of thread,
public class MainAsyncHome extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String xml) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
I run this thread in my main activity onCreate method as following way
new MainAsyncHome().execute(null);
But I want to give time out for this thread. It means when main activity run I want late to run this thread. I know it can do using sleep method. But How I can late for running this thread just like that way.
I'm stuck with this problem.
pls give me answer. Thanks
Use Handler class, and define Runnable handleMyAsyncTask that will contain code executed after 3000 msec delay:
mHandler.postDelayed(MainAsyncHome, 1000*3); //Delay of three seconds
The answer is taken from here.
To put it in the code:
private final static int INTERVAL = 1000 * 3; //3 seconds
Handler m_handler;
Runnable MainAsyncHome = new Runnable()
{
#Override
public void run() {
doSomething();
m_handler.postDelayed(MainAsyncHome, INTERVAL);
}
}
void startRepeatingTask()
{
MainAsyncHome.run();
}
void stopRepeatingTask()
{
mHandler.removeCallback(MainAsyncHome);
}
Hope it works.
I normally use CountDownTimer, suppose a 3 seconds of delay:
CountDownTimer timer = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//do things, start your Task
//remember we are still in the main thread!
}
}.start();
Get more info at:
http://developer.android.com/reference/android/os/CountDownTimer.html
Use a CountDownTimer like this.
Start your timer in onCreate.
CountDownTimer timer=new CountDownTimer(Delay,TimeIntervalToCallOnTick) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
//start your asynctask
}
};
I have implemented the timer functionality in android app, I able to finish the timer from other local methods by calling timerObject.cancel() . Its working perfectly.
But when I tried to call same in onTick() method for specific condition, i am not able to cancel the timer, it last till the timer time ends.
How can i cancel the timer?
Looking at the source code for CountDownTimer it is easy to see why it is not working. cancel() merely removes the message for ticking the timer from the queue. But the message handler that gets called at each tick posts a message for the next tick after calling onTick(). So either you have to call cancel() outside of onTick(), via a Handler for example, or switch to using the Timer class instead.
if using RXJava2. this code can help you.
public abstract class CountDownTimer {
private TimeUnit timeUnit;
private Long startValue;
private Disposable disposable;
public CountDownTimer(Long startValue,TimeUnit timeUnit) {
this.timeUnit = timeUnit;
this.startValue = startValue;
}
public abstract void onTick(long tickValue);
public abstract void onFinish();
public void start(){
io.reactivex.Observable.zip(
io.reactivex.Observable.range(0, startValue.intValue()), io.reactivex.Observable.interval(1, timeUnit), (integer, aLong) -> {
Long l = startValue-integer;
return l;
}
).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
#Override
public void onSubscribe(Disposable d) {
disposable = d;
}
#Override
public void onNext(Long aLong) {
onTick(aLong);
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onComplete() {
onFinish();
}
});
}
public void cancel(){
if(disposable!=null) disposable.dispose();
}
}
using:
public class MainActivity extends AppCompatActivity {
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
new CountDownTimer(10L, TimeUnit.SECONDS) {
#Override
public void onTick(long tickValue) {
Log.d("CountDown", "Remaining: " + tickValue);
// cancel();
}
#Override
public void onFinish() {
Log.d("CountDown", "The End!! ");
}
}.start();
}
}
the owner of the code https://gist.github.com/chemickypes/fa3b7fc5b5a00a3ce37fee5815018702