I have a simple question, how can I stop timer?
Button bCancel = (Button)findViewById(R.id.bt1);
bCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
startActivity(new Intent("com.jom.testcdt2.CANCELCLASS"));
}
});
final Thread logoTimer = new Thread(){
public void run(){
try {
int logoTimer = 0;
while (logoTimer < 10000) {
sleep(100);
logoTimer = logoTimer + 100;
}
startActivity(new Intent("com.jom.testcdt2.CLEARSCREEN"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
}
When I press button bCancel, it starts a new activity, but timer is still running and after 10 seconds it starts CLEARSCREEN. On click I want timer to stop. How can I do that?
I would recommend using a CountDownTimer:
final CountDownTimer myTimer = new CountDownTimer(10000, 5000) {
#Override
public void onFinish() {
//DO SOMETHING AFTER 10 000 ms
}
#Override
public void onTick(long millisUntilFinished) {
//DO SOMETHING EVERY 5 000 ms until stopped
}
}
myTimer.start() //Starts it
myTimer.cancel() //Stops it
And instead of writing
(new Intent("com.jom.testcdt2.CANCELCLASS")
you should use
(new Intent(YOURCLASS.this, CancelClass.class)
Could you try to have a boolean value that you check in the while loop, and set it to true when you press the cancel button?
boolean pressedCancel = false;
....
while (logoTimer < 10000 && !pressedCancel) {
....
Related
I make a timer with a count time of 5 seconds, then when I press the exit button the counter automatically stops?
Here is my timer code:
public void startTimer(final long finish, long tick) {
CountDownTimer t;
t = new CountDownTimer(finish, tick) {
public void onTick(long millisUntilFinished) {
long remainedSecs = millisUntilFinished / 1000;
textTimer.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));// manage it accordign to you
}
public void onFinish() {
textTimer.setText("00:00");
Toast.makeText(FloatingVideoWidgetShowService.this, "Waktu Habis", Toast.LENGTH_SHORT).show();
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
cancel();
}
}.start();
}
And this is my code when pressing the stop / exit button :
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long seek = videoView.getCurrentPosition();
videoView.setKeepScreenOn(false);
stopSelf();
WritableMap args = new Arguments().createMap();
args.putInt("index", index);
args.putInt("seek", (int) seek);
args.putString("url", playingVideo.getString("url"));
args.putString("type", "close");
sendEvent(reactContext, "onClose", args);
onDestroy();
}
});
How so when btn_deny is clicked Cuntdowntimer stops and does not force close?
Thanks.
You can't use onDestroy() to close your activity or fragment. Instead, you need to call finish().
To close the CountDownTimer, you need to make it a class scope variable. Prepare the timer at your startTimer then stop the timer by calling t.cancel() like the following code:
public class YourActivity extends Activity {
// Declare the variable to be accessed later.
CountDownTimer t;
...
public void startTimer(final long finish, long tick) {
t = new CountDownTimer(finish, tick) {
...
}.start();
}
private void yourOtherMethod() {
floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(t != null) t.cancel();
...
}
});
}
}
I am struggling with setting the text of a TextView, so I am now trying to do it with a button push, but when I start the thread from the button readWeight the button updateButton does not work.
Here are my two button onClick methods:
readWeight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
inputWindow.setText("helloooooooo worldddddd");
//connector.run();
System.out.println("********** PRINTING **********");
// readWeight.setVisibility(View.INVISIBLE);
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("!!!!!!!!!!!!!!!"+weight+"!!!!!!!!!!!!!!!");
inputWindow.setText(weight);
}
});
and here is my method that starts the thread, this method is in another class:
public void run() {
new Handler().post(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
//Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");
int counter = 0;
while (true) {
counter++;
try {
output = "";
//read the data from socket stream
//mmInStream != null && counter%10000000 == 1
if (mmInStream != null) {
mmInStream.read(buffer);
for (byte b : buffer) {
char c = (char) b;
if (c >= ' ' && c < 'z') {
// System.out.print(c);
output += c;
}
}
System.out.println();
Intent intent = new Intent();
intent.setAction("com.curie.WEIGHT_RECEIVED");
intent.putExtra("Output",output);
if (counter % 10 == 0) {
System.out.println(counter);
//InputActivity.setInputWindowText(output);
LocalBroadcastManager.getInstance(InputActivity.getContext()).sendBroadcastSync(intent);
}
}
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
Any help would be very appreciated! thank you.
When you use
Handler.post()
It runs in UI thread, so if it is long action it will block all interface.
To avoid it you should run it in another thread. If you don't want to use something complicated you can try this:
mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run () {
mHandler.post(new Runnable() {
#Override
public void run () {
// place your action here
}
});
}
}).start();
I want to send a character with Bluetooth. The code works perfectly when there is only a single character.But I want to use a delay function between the two codes.
I want to enter any number with EditText and the app will take that number and do EditText/44. That is what I want to wait between 2 codes
Finally work.. Thanks guys. :)
I moved a,b,c inside setOnClick.. ;
kileri = (Button) findViewById(R.id.kileri);
final EditText value1 = (EditText) findViewById(R.id.textkont);
assert value1 != null;
value1.setText("0");
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
kileri.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int a = Integer.parseInt(value1.getText().toString());
int b = a / 44;
int c = b * 1000;
sendData("F");
try {
Thread.sleep(c);
} catch (Exception e) {
e.printStackTrace();
}
You can use handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do something
}
}, 2000 );//time in milisecond
try {
//set time in mili
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
edited as your code
kileri.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("F");
try {
//set time in mili
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
sendData("S");
}
});
Use handler like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do something after 2s = 2000 miliseconds
}
}, 2000); //Time in milisecond
You can do like this
kileri = (Button) findViewById(R.id.kileri);
final EditText value1 = (EditText) findViewById(R.id.textkont);
assert value1 != null;
value1.setText("0");
final int a = Integer.parseInt(value1.getText().toString());
final int b = a/22;
final int c = b/2; // It will take a int from Edittext and do this operation on that.
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
kileri.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("F");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendData("S");
}
}, c);
}
});
just use runOnUiThread on button click and post Handler after time delay..
Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("F"); // send
delay(2000);
}
});
UPDATE
delay()..
public void delay(final int c){
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(c);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendData("S"); //send
}
}, c);
}
It's not recommended to use Thread.Sleep because it stops execution of main thread if it is called in main thread execution.So,if we want to set delay we can use CountDownTimer.
In below snippet,we gave 2 seconds delay.So,after 2s onFinish() callback comes and we can have our operation there.
new CountDownTimer(2000, 1000) {
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}.start();
}
I currently have an app which when a button is pressed starts a service and within the service a thread is created.
I then have a second button (which appears once the first it pressed) that should shut down the service and in turn kill the thread, below is my current code however the service seems to stop but the thread keeps going.
public class MainActivity extends Activity {
private static Button lock = null;
private static Button unlock = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock = (Button) this.findViewById(R.id.lock);
unlock = (Button) this.findViewById(R.id.unlock);
lock.setOnClickListener(btn_lock);
unlock.setOnClickListener(btn_unlock);
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
text.setVisibility(View.GONE);
startService(new Intent(this, MainService.class));
}
private OnClickListener btn_lock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
startService(new Intent(MainActivity.this, MainService.class));
}
};
private OnClickListener btn_unlock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.GONE);
lock.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, MainService.class));
}
};
}
And then my service class looks like:
public class MainService extends Service {
Thread 1Thread;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while(true){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TEST", "Thread is still here!");
}
}
};
}
#Override
public void onDestroy() {
1Thread.interrupt();
}
#Override
public void onStart(Intent intent, int startId) {
1Thread.start();
}
}
Hope someone can help and if you need any more info let me know!
boolean mStatus = true;
#Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while (mStatus) {
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
Log.i("TEST", "Thread is still here!");
}
};
}
#Override
public void onDestroy() {
mStatus = false;
1Thread.interrupt();
}
Your thread is not handling interrupt, in while loop in each iteration check if thread is interrupted, if so then do not continue the loop:
while(!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break; //BREAK here, as thread was interrupted
}
Log.i("TEST", "Thread is still here!");
}
Also on click of second button, you should interrupt this thread:
1Thread.interrupt();
I want call CountDownTimer when one countdownTimer finishes it's execution.I tried calling one countdowntimer from another countdown timer's onFinish() method but it giving me nullpointer exception when I run this code.
public void First_Timer(){
Timer_Off =false;
dialog = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setCancelable(false);
dialog.setContentView(R.layout.backwash_timer_dialog);
final ToggleButton togglebtn_BW_timer = (ToggleButton)dialog.findViewById(R.id.togglebtn_BW_timer);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressBar1);
textView1 = (TextView)dialog.findViewById(R.id.textView1);
btn_BW_timer_stop = (Button)dialog.findViewById(R.id.btn_BW_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
textView1.setText("Time Up! ");
cdt.cancel();
Timer_Off =true;
dialog.dismiss();
// Call Second Timer Here
Second_Timer();
}
}.start();
btn_BW_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt.cancel();
bar.setProgress(0);
textView1.setText("0");
Timer_Off=true;
dialog.dismiss();
//onBackwashStopped();
}
});
dialog.show();
}
And Code for another timer is,
public void Second_Timer(){
Timer_Rinse_Off =false;
dialog_Rinse = new Dialog(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog_Rinse.setCancelable(false);
dialog_Rinse.setContentView(R.layout.rinse_timer_dialog);
final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.progressbar_Rinse);
txtRinse_TimerVal = (TextView)dialog.findViewById(R.id.txtRinse_TimerVal);
btn_Rinse_timer_stop = (Button)dialog.findViewById(R.id.btn_Rinse_timer_stop);
/** CountDownTimer starts with 2 minutes and every onTick is 1 second */
cdt_Rinse = new CountDownTimer(twoMin, 1000) {
public void onTick(long millisUntilFinished) {
bar.setProgress((int) ((millisUntilFinished / 1000) ));
messageHandler.sendMessage(Message.obtain(messageHandler,(int) ((millisUntilFinished / 1000) ) ));
}
public void onFinish(){
txtRinse_TimerVal.setText("Time Up! ");
Timer_Rinse_Off =true;
dialog_Rinse.dismiss();
}
}.start();
btn_Rinse_timer_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cdt_Rinse.cancel();
bar.setProgress(0);
txtRinse_TimerVal.setText("0");
Timer_Rinse_Off=true;
dialog_Rinse.dismiss();
//onBackwashStopped();
}
});
dialog_Rinse.show();
}