I have a tune in my android app. I have added a feature that if user selects a time then the tune will repeat until the time ends. I have also added the feature of infinite time but when I run my app goes in ANR (not responding) mode.
if(tinydb.getString("timer").equals("infinity"))
{
boolean valid = true; //Here i want to play the tune for infinite time
while(valid)
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
}
else
{
while(!timerText.equals("0h: 0m: 1s")) //Here i want to play the tune until the timer gets zero
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
you can use setLooping for the first case
and for the second case
final Runnable r = new Runnable() {
public void run() {
water_player.stop();
}
};
handler.postDelayed(r, 1000); //your time in millisecond
with your code :
if(tinydb.getString("timer").equals("infinity"))
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.setLooping(true);
water_player.start();
}
else
{
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
final Runnable r = new Runnable() {
public void run() {
water_player.stop();
}
};
handler.postDelayed(r, 1000); //your time in millisecond
}
Use countdownTimer to complete your goal in which you can set countdown timer till x seconds manually. when countdown finish process it will go to finish method and execute finish method code
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//code fire after finish
mp_xmPlayer2.stop();
}
};cntr_aCounter.start();
If you have only 2 cases, use a boolean.
boolean infinitely;
if(infinitely == true){
water_player = MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
}
else {
water_player = new MediaPlayer.create(MainActivity.this, R.raw.water);
water_player.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
water_player.stop();
}
}
, 2000);
The handler method will be executed when 2sec passed. (put your own desired time).
Related
I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}
I want to implement a timer in my application if user click clock in button timer should start from device time and the timer should run when giving pause timer should pause when user click stop timer should stop, Please help me.
for example, now time is 13:20:10 user click means timer should run on this time not from 00, normal timer code I have, but based on the current time it should run.
you can try this. call start()/stop() when you want to start/stop timer. if you want to update UI (Main)Thread use runOnUiThread(https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)) or handler for update UI Thread
import java.util.Calendar;
int hou=0;
int min=0;
int sec=0;
boolean stopTimer=false;
private void initTimer()
{
Date currentTime = Calendar.getInstance().getTime();
hou=currentTime.getHours();
min=currentTime.getMinutes();
sec=currentTime.getSeconds();
Log.e("Initial Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
private void startTimerThread()
{
new Thread()
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTimer();
}
}.start();
}
private void updateTimer()
{
if(!stopTimer)
{
sec=(((++sec)%60)==0)?0:sec;
min=(sec==0)?(((++min)%60==0)?0:min):min;
hou=(min==0)?((++hou)):hou;
/*hou%=12;*/
Log.e("Update Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
}
public void start()
{
initTimer();
}
public void stop()
{
stopTimer=false;
}
you can try this using by using countdowntimer like this :
CountDownTimer timer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
Calendar c = Calendar.getInstance();
Log.v(TAG , "CountDownTimer : " + c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
timer.start();
on pause you can cancel it like this:
timer.cancel();
i have take three button, first start button click on device time show in textview and it update as per device time. when click on paused button stop time update. and when click on restart time device time when start to stop.
mBtnStartTime?.setOnClickListener {
val someHandler = Handler(mainLooper)
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
mBtnPaused?.setOnClickListener {
someHandler.removeCallbacksAndMessages(null)
}
mBtnRestart?.setOnClickListener {
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
}
first of all, I'm a beginner to android world so please apologize me if it is stupid question..
I'm trying to do following:
Enable Mobile Data
Wait for 10 seconds
a. check if Mobile got IP address (data connected sucessfully)
b. if Not connected,Disable Data
c. Go to step 1
And these steps 1 to 3 are getting executed in For loop for User Given number of retries.
Now my problem is: I'm stuck at step No. 2. I'm unable to make waitfor(int seconds) function. I tried using Runnable PostDelayed method but it is not giving me required output.
for(retry = UserChoice; retry > 0 && !isDataAvailable ; retry -- ){
enableInternet()
delay(10)
isDataAvailable = GetInternetAvailibility()
if(!isDataAvailable){
disableInternet()
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement in postDelayed of handler but it is causing enableInternet() disableInternet() to execute at the same time while isDataAvailable = GetInternetAvailibility() gets executed after delay.
I can see from logs, that enableInternet() executes for UserChoice number of times without any delay.
Thread.sleep(10000) just freezes the UI for 10 seconds... How do I achieve this?
EDIT : Let me clear :
public void onClick(View v) {
// Perform action on click
for(i=0; i<3; i++ ){
System.out.println("Before..");
delay(5);
System.out.println("after..");
}
}
public void delay(int seconds){
milliseconds = seconds * 1000;
runOnUiThread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXX"); //add your code here
}
}, milliseconds);
}
});
}
Now whenever I click button I can see in logs that System.out prints message as:
Before
afterBefore
afterBefore
after
XXXXXXXXX
But I want:
Before
XXX
After.Before
XXX
After.Before
XXX
After.
try this:
public void check() {
isDataAvailable = GetInternetAvailibility()
if (!isDataAvailable) {
disableInternet();
enableInternet();
if (retry > 0) {
retry--;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
check();
}
}, 10000);
}
}
}
This way may help you.
http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Try Below code.Hope that it will help
int i = 0;
int j = 3;
method() {
if (i < j) {
System.out.println("Before..");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("XXXXXX");
i++;
System.out.println("after");
method();
}
}, 1000);
}
}
I tried to put isDataAvailable = GetInternetAvailibility() statement
in postDelayed of handler but it is causing enableInternet()
disableInternet() to execute at the same time while isDataAvailable =
GetInternetAvailibility() gets executed after delay.
Put the if statement and disableInternet() in the postDelayed. enableInternet will get called, 10 seconds later it will check to see if the internet is available, if not it will disableInternet.
I'm looking for a way to get a callback when a VideoView is playing, indicating the video progress. Something like described here, but for a VideoView. Polling the current progress every fixed duration seems a bad solution…
Is there any listener existing for this that I missed?
You can use a thread to get the progress.
mRunnable = new Runnable() {
public void run() {
Log.i(TAG, "::run: getCurrentPosition = " + mVideoView.getCurrentPosition());
if(mVideoView.isPlaying()){
mHandler1.postDelayed(this, 250);
}
}
};
mHandler1.post(mRunnable);
Runnable onEverySecond=new Runnable() {
public void run() {
if(seekbar != null) {
seekbar.setProgress(mPlayer.getCurrentPosition());
}
if(mPlayer.isPlaying()) {
System.out.println("inside runnable :::::: is playing ");
seekbar.postDelayed(onEverySecond, 10);
}
}
};
seekbar.postDelayed(onEverySecond, 10);
How to call record method after 5 millisecond playing audio with MediaPlayer. I tried something like that but i don't know and i didn't find any good examples to end this.
while(mp.isPlaying()){
if(record=0){
for(int i=0; i<5millisec; i++){ //how to define 5 millisec or is any better solution
}
startRecord();
record=1;
}
}
mp.stop();
mp.release();
mp=null;
5 milliseconds is a very short time period and you can't limit audio output to such duration.
you can use Handler to execute a delayed function but it will not ensure execution at 5 milliseconds after scheduling.
a code for doing that:
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
startRecord();
mp.stop();
mp.release();
}
}, 5);
You can use the method postDelayed.
In the example below I run my routine 100 millis after to call the method.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
barVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}
},
100);
try this:
//Auto Start after 2 seconds
if(ENABLE_AUTO_START) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 2 seconds
doThis();
}
}, 2000);
}
Perhaps you want to use Thread.sleep?
Like so:
if(record == 0){
Thread.sleep(5);
}
Notice that I used == in the if statement to check for equality, rather than assigning the value of 0 each time, I assume this is what you want.
It is worth mentioning that putting a Thread to sleep will stop it doing anything for the duration that you specify. If this is a UI Thread, then you will effectively "freeze" the UI for that duration, so make sure you are using it appropriately. Hwoever, you example for loop indicates this is exactly the kind of thing you are attempting to do.
You could try using Thread.sleep(5), or, if you don't want to use the UI thread for this, you could use a Timer, or an AsyncTask which triggers a callback after waiting 5ms in the doInBackground() method.
Here is a pretty good example for using Timer:
https://stackoverflow.com/a/4598737/832008
You can also use ScheduledExecutorService
Using an ExecutorService, you can schedule commands to run after a given delay, or to execute periodically. The following example shows a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
public static MediaRecorder mRecorder = new MediaRecorder();
public void startRecording(String fileName) {
if(mRecorder != null) {
try {
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(fileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(StartPhoneCallService.class.getSimpleName(), "prepare() failed");
}
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
public void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
Now you can call the Handler to play 5 millisecond
private final int recording_time = 5;
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
startRecording("YOUR FILE NAME");
// Stop your recording after 5 milliseconds
stopRecording();
}
}, recording_time );