Working with delay in Java - java

I'm trying to create a speech recognition app where the app recieves voice and sends out stuff. I'd like everything that the onEndOfSpeech method to be called to wait a second and then do the entire voice recognition intent to start over again.
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
Not sure that I am doing this correctly.
Thanks!

This is how it should be
try {
Thread.sleep(3000);
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} catch (InterruptedException e) {
// it depends on your app logic what to do with InterruptedException, you can process it or rethrow or restore interrupted flag
}

Try this code
protected boolean _active = true;
// time to display the splash screen in ms
protected int _splashTime = 1000;
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
e.printStackTrace();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}

Related

Flash not being turned off on button press(Flashlight App)

I have 3 buttons on the UI. On, Off and SOS(flash at repeated intervals). If I press On and then the Off button the flash turns off as expected.But if I press SOS(it flashes as expected at regular intervals) and then Off it refuses to stop flashing. The code is as follows:
SOSbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SOSon = true;
startSOS();
onSOSPress();
} catch (Exception ex) {
throw ex;
}
}
});
void onSOSPress() {
try {
Flashlight flashlight=new Flashlight();
SOSon = true;
flashlight.Flashthread = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < System.currentTimeMillis(); i++) {
while (!FlashThreadStop) {
if (FlashOn) {
myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
try {
myCamera.setParameters(myParameters);
}
catch (Exception ex)
{
//logger.log(Level.SEVERE, "an exception was thrown", ex);
}
myCamera.stopPreview();
FlashOn = false;
} else {
TurnOnFlash();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
flashlight.Flashthread.start();
} catch (Exception ex) {
throw ex;
}
}
and the TurnOff mechanism is as follows:
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FlashOn) {
// turn off flash
TurnOffFlash();
}
}
});
private void TurnOffFlash() {
if (FlashOn) {
if (myCamera == null || myParameters == null) {
return;
}
myParameters = myCamera.getParameters();
myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(myParameters);
myCamera.stopPreview();
FlashOn = false;
}
}
void endSOS(){
FlashThreadStop=true;
}
void startSOS(){
FlashThreadStop=false;
}
EDIT: The method onSOSPress() has been updated to reflect the working SOS mode(OFF button works now)
Your TurnOffFlash method does not cover flash blinking very well. You are not stopping the thread so it continues flashing back and forth. You need to add one line to cover that part as well:
Flashthread.interrupt();
This way you'll keep your functionality turning off the flash, and if the thread is running the SOS mode, you'll stop it as well.
Side note: You're failing to follow the common Java nomenclature where methods and variables start with a lowercase letter and use camelCase.

my apps call over and over again (tel: + phoneNumber)

My Apps need to make a call several time according to the user need.
public class callDelay implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
for(int count = 0 ; count < (Integer.parseInt(myGate.getNumberOfAttempts().toString())); count++){
try {
Intent openGateNow = new Intent(Intent.ACTION_CALL);
openGateNow.setData(Uri.parse("tel:" + myGate.getGatePhoneNumber().toString()));//to call a phone number must use "tel:"+ the number
startActivity(openGateNow);
} catch (Exception e) {
// TODO: handle exception
}
try {
Thread.sleep(Integer.parseInt(myGate.getCallDelay().toString())*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
callNowFlag = false;
speedVerification = false;
}
}
The problem is that when i call this thread, it ignore the counter and calls over and over again without delays and with no counter limits (i have to stop it my self).
I would like it to call just X number of times and with delay between the calls.
what is wrong with my code?
what reset the counters and delay?

How to leave the program successfully

Today I write a program.It works successfully and is almost finished.But I found when I close the Socket,BufferedReaderandPrintWriter,the program always shows ANR.I feel confused about that.Is there any sequence to close the program??
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
try {
mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
mPrintWriter.close();
mBufferedReader.close();
mSocket.close();
net_.interrupt(); //This is the thread to send and receive data.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my question and I want to eliminate this bug to keep my program perfect.Thanks
Read this Android - how do I investigate an ANR?
And maybe try something like that
#Override
public void onClick(DialogInterface dialog, int which) {
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
} catch (IOException e) {
e.printStackTrace();
} finally{
mPrintWriter.close();
mBufferedReader.close();
}
try{
net_.interrupt();
}catch (IOException e) {
e.printStackTrace();
}finally{
mSocket.close();
}
}
});
thread .start();
}
And at the end of your app you should join that thread
thread.join();

progress dialog in for into a thread

I have a problem, I have a for loop and a ProgressDialog and would like to see something like (10/5) where 10 is the total items to be processed by and for the 5 elements are currently being developed. I have this code.
new Thread(new Runnable() {
public void run() {
for(int i=0; i<adapter.getTotalItems().size(); i++) {
try {
index = i;
progressDialog = ProgressDialog.show(MyClass.this,adapter.getTotalItems().size()+"/"+index, );
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.cancel();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(1*2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
}
});
}
}).start();
Don´t cancle the ProgressDialog every Time, just Change the Title like:
mProgressDialog.setTile(adapter.getTotalItems().size()+"/"+index);
That´s it.

Creating a slidshow in android

I am creating an application in which user can start slideshow (auto-play) of images by clicking a specific button. I have started a thread in which a new image is set to my imageView after a 1 sec. Problem is that my app stop responding and crashes after few seconds.
Please check my code and help me to resolve this issue. (variables are correctly initialized)
playThread = new Runnable() {
#Override
public void run() {
synchronized (this) {
for (int i=pos;i<mImageIds.length;i++){
//pos++;
selectedImage.setImageResource(mImageIds[i]);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(playThread);
}
});
}
my logcat while app freezes!
The runOnUiThread() method is meant to update the user interface. Any other logic shouldn't happen there. So I would suggest something like this:
Thread t = new Thread() {
for (int i=pos;i<mImageIds.length;i++){
runOnUiThread(new Runnable() {
#Override
public void run() {
selectedImage.setImageResource(mImageIds[i]);
}};);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t.start();
}
});
Please note, I didn't test this code.

Categories