Call method after 5 millisecond - android

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 );

Related

TimerTask / Handler with Delay getting called Multiple times

I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice
Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);

Callback on VideoView progress

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);

Turn ON Flash light every second in Android?

I trying to turn ON the phone flash light every second. I have been searching but nothing found useful.
This is the code that I am using:
Thread t = new Thread() {
#Override
public void run() {
seconds = 0;
try {
while (seconds<11) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Put code here!
seconds++;
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
I will really appreciate your help! Thanks.
Creating the loop is bad idea.
Try to use handler http://developer.android.com/reference/android/os/Handler.html
handler.postDelayed(Runnable r, long delayMillis)
use this at the and of runnable code.

how to create a thread to refresh data in 3 second interval

I need a thread (it does httppost ,and parse the answer xml and refresh listview to set the changes from parsed xml) in 3 sec interval
I have already tried this code
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try {
httpPostList(url);
saxParseList();
list.invalidateViews();
Thread.sleep(1000);
} catch (Exception ie) {
}
}
}, 1000, 1000 * 30);
I would appreciate you to create a Service with an AsyncTask in it.
Async Tasks are the Android Synonym to normal Java Tasks, Documentation finding here: http://developer.android.com/reference/android/os/AsyncTask.html
Services are Background Processes, seeing this Doc:
http://developer.android.com/reference/android/app/Service.html
Try using handlers:
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
updateUI();
}
};
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
Message msg = new Message();
handler.sendMessage(msg);
try {
sleep(3*1000); // 3 seconds
} catch (InterruptedException e) {
}
}
}
};
thread.start();
}
private synchronized void updateUI() {
// ...
}
Finally I made it using "Async task".

How to run a method every X seconds

I'm developing an Android 2.3.3 application and I need to run a method every X seconds.
In iOS, I have NSTimer, but in Android I don't know what to use.
Someone have recommend me Handler; another recommend me AlarmManager but I don't know which method fits better with NSTimer.
This is the code I want to implement in Android:
timer2 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/20.0f)
target:self
selector:#selector(loopTask)
userInfo:nil
repeats:YES
];
timer1 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/4.0f)
target:self
selector:#selector(isFree)
userInfo:nil
repeats:YES
];
I need something what works like NSTimer.
What do you recommend me?
The solution you will use really depends on how long you need to wait between each execution of your function.
If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.
// Some time when you want to run
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}
If you are waiting for shorter than 10 minutes then I would suggest using a Handler.
final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//your method
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds. One second = 1000 milliseconds.
#Override
protected void onResume() {
//start handler as activity become visible
handler.postDelayed( runnable = new Runnable() {
public void run() {
//do something
handler.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
// If onPause() is not included the threads will double up when you
// reload the activity
#Override
protected void onPause() {
handler.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(new Function<Long, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull Long aLong) throws Exception {
return getDataObservable(); //Where you pull your data
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
With RxAndroid, you can handle threads in just 2 lines of code.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(...) // polling data code
.subscribeOn(Schedulers.newThread()) // poll data on a background thread
.observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
.subscribe(...); // your UI code
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
With Kotlin, we can now make a generic function for this!
object RepeatHelper {
fun repeatDelayed(delay: Long, todo: () -> Unit) {
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
todo()
handler.postDelayed(this, delay)
}
}, delay)
}
}
And to use, just do:
val delay = 1000L
RepeatHelper.repeatDelayed(delay) {
myRepeatedFunction()
}
new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
txtcounter.setText(" " + millisUntilFinished / 1000);
}
public void onFinish() {
txtcounter.setText(" TimeOut ");
Main2Activity.ShowPayment = false;
EventBus.getDefault().post("go-main");
}
}.start();
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
Thread t = new Thread() {
#Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(10000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
#Override
public void run() {
SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("chat_list", "");
GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
String sam = "";
ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
listview.setAdapter(adapter);
// listview.setStackFromBottom(true);
// Util.showMessage(Chat.this,"Merhabalar");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
In case it needed it can be stoped by
#Override
protected void onDestroy() {
super.onDestroy();
Thread.interrupted();
//t.interrupted();
}
I do it this way and it works fine (the code is written in Kotlin):
private lateinit var runnable: Runnable
private var handler = Handler(Looper.getMainLooper())
private val repeatPeriod: Long = 10000
Then reinit the runnable from inside your function
runnable = Runnable {
// Your code goes here
handler.postDelayed(runnable, repeatPeriod)
}
handler.postDelayed(runnable, repeatPeriod)
Note that if you don't postDelay twice the handler, the loop is not going to be intinity!
In Kotlin, you can do it this way with a Runnable:
private lateinit var runnable: Runnable
private var handler = Handler(Looper.getMainLooper())
private val interval: Long = 1000
private var isRunning = false
val runnable = object : Runnable {
override fun run() {
// Do something every second
function()
// Call your runnable again after interval
handler?.postDelayed(runnable(this, interval))
}
}
// Call your function once
if (!isRunning) {
handler?.postDelayed(runnable, interval)
isRunning = true
}
// Remove your repeatedly called function
if (isRunning) {
handler?.removeCallbacks(runnable)
isRunning = false
}

Categories

Resources