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();
}
Related
I am programming a metronome for Android and use a thread for playing the sound in the rythm the user says but somehow my setOnClickListener won't work. The button doesn't even click when clicked. What is wrong with my code?
startb = (Button) findViewById(R.id.start_but);
stopb = (Button) findViewById(R.id.stop_but);
startb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
running = true;
bpm_val = findViewById(R.id.metr_input);
value = bpm_val.getText().toString();
int beat = Integer.parseInt(value);
Soundplay(beat / 60); //The beats per second
}
});
stopb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
running = false;
}
});
}
public void Soundplay(final long bps) {
startb = (Button) findViewById(R.id.start_but);
stopb = (Button) findViewById(R.id.stop_but);
running = true;
new Thread() {
#Override
public void run() {
super.run();
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.metronome_klack);
int i = 0;
while (running) {
if(i == 1000) {
mp.start();
i = 0;
}
try {
sleep(bps);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
You have initialized the button twice in your code.
First in onCreate() method and second time in Soundplay(final long bps) method. You can remove the initialization from Soundplay method. As it seems that button is initialized on its click listner itself. I think that's the issue.
public void Soundplay(final long bps) {
//Remove this portion
**startb = (Button) findViewById(R.id.start_but);**
**stopb = (Button) findViewById(R.id.stop_but);**
...
}
Hope it helps.
I want complete code to disable a Button for some time for example 2 minutes in Android Studio. Thank you for help.
protected void onclick(View v){
bwasta = (Button) findViewById(R.id.btDes);
new CountDownTimer(10000, 10) { //Set Timer for 10 seconds
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
bwasta.setEnabled(true);
bwasta.setEnabled(false);
}
}.start();
This might help you out.
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2*
60*
1000);//min secs millisecs
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YourActivityName.this.runOnUiThread(new Runnable() {
#Override
public void run() {
bwasta.setEnabled(true);
}
});
}
}).start();
DO NOT RELY ON Thread.sleep()
Actually, there is already a Question and an Answer on SO regarding the inaccuracy of Thread.sleep()(as per the OP's experience) here.
The answer then favors the accuracy of a ScheduledThreadPoolExecutor using the schedule() method.
Do the following:
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new new Runnable() {
#Override
public void run() {
YourActivityName.this.runOnUiThread(new Runnable() {
#Override
public void run() {
bwasta.setEnabled(true);
}
});
}
}, 2, TimeUnit.MINUTES);
You can use mHandler.postDelayed(mRunnable, mTime) function to achieve this
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
bwasta.postDelayed(new Runnable() {
public void run() {
bwasta.setEnabled(true);
}
}, 2*60*1000);
At the below code i try to take the user's current location each second as x and y axises.At the first time of loop,the code works.But second and so on it doesnt work.What is the missing thing on this code.What should i do.Thanks..
new Thread(new Runnable(){
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
public void run() {
textViewXAltitude.setText(String.valueOf(gps.getLatitude()));
textViewYAltitude.setText(String.valueOf(gps.getLongitude()));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
you should do this by Handler;for example:
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
textViewX.setText(String.valueOf(i++));
textViewY.setText(String.valueOf(j++));
}
}
};
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
handler.sendEmptyMessage(0x123);
}
}, 0, 1000);
}
});
In my application I have a button and when it gets clicked I start a new thread and change the text of button. If I press the button again it will start changing its text faster.
I would like to interrupt the thread when the button is pressed in the second time. What's the correct way to do it?
public class TestActivity extends Activity {
Button btn;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
In this case, just keep a reference to your thread and use Thread.interrupt():
private Thread runThread() {
return new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Then:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myThread != null) myThread.interrupt();
myThread = runThread();
myThread.start();
}
});
Read this post for more info and options:
How to properly stop the Thread in Java?
In my opinion, the best way would be using a variable to control this.
Something like:
while(i++ < 1000 && keepRunning)
I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.
extra--
As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes
Also it is a good practice to give thread a name (setName()) to make it easy on debugging.
Right now you start a new Thread each time you press the button.
Something like this should work.
public class TestActivity extends Activity {
Button btn;
int i = 0;
Thread countThread = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countThread = new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread() {
if(countThread != null) {
if(countThread.isAlive()) {
countThread.stop();
} else {
countThread.start();
}
}
}
I only had a text editor so I can't guarantee if this solves your problem.
You can use thread.interrupt() to interrupt the thread.
Try this, Just take another variable j and it will handle your code:-
public class TestActivity extends Activity {
Button btn;
int i = 0,j=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
j=1;
runThread();
}
});
}
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(j==1){
btn.setText("#" + i);
j=0;
}
else
Thread.interrupted();
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
You can use normal Thread in Android (and call interrupt() for your use case) but frameworks provides other better options by providing helper classes around Threads. You can refer to official documentation page for other options.
HandlerThread is preferred option. You can call quitSafely() or quit() for your use case if you go for HandlerThread
Related post:
Why use HandlerThread in Android
I'm new to android and I want to do a simple example where I click on a start button and another Activity is open, there a simple number starting in one and counting upwards, but I'm facing a problem, after I initialize some variables on onCreate method (In the second activity), where should I actually start the while statement to count and modify the text view?.
I wrote this class:
public class Counter extends Thread{
private TextView tv;
private int i;
public Counter( TextView tv ){
this.tv = tv;
}
#Override
public void run() {
while( true ){
tv.setText(i);
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
And started the thread over here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
counter = new Counter( (TextView) findViewById(R.id.textView2) );
counter.start( );
}
#SuppressLint("UseValueOf")
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// change your text here
if (condition) {
i++;
txt_TimeRecord.setText("" + i);
} else {
i = 0;
}
handler.postDelayed(this, 1 * 1000L);
}
});
[Formatted the code properly]
//In first activity
//set onclick method to that button.
public void onclick(view v)
{
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
}
// in second activity in
// initi i value.
while(i<10)
{
i++ ;
// sleep statement
//print that i in textview
}
I've found what I need from a similar post, the handler was needed since only the UI Thread can update the user interface.
private void countNumbers() {
final TextView numbers = (TextView) findViewById(R.id.textView2);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
int i = 0;
while (i++ < 500) {
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
final int j = i;
handler.post(new Runnable(){
public void run() {
numbers.setText(Integer.toString(j));
}
});
}
}
};
new Thread(runnable).start();
}
The method countNumbers() is called in onCreate().