do while with android button - android

Can you please help me some in this simple task? please see the attachment. you can do the task there.
I want to start a do-while loop by pressing a button to print some numbers,
in the mean time the button will be ready for take next touch, (I mean one button will work for two task.)
in the next touch the button will stop to print those numbers.
if again I touch the same button then it will start print the numbers from the beginning.
Like: I press the button...its prining 1,2,3,4,5,6,7 then I press the button again then it stoped. then again I press the same button the its start to print 1,2,3...and so on.
means The process will run one the back of the interface.
I hope you can understand me.
can you please hep me on that?

Something like this should work. No need for multithreading really.
{
Handler mHandler = new Handler();
private boolean running;
myButton.setOnClickListener(this);
}
public void onClick(View v) {
if(!running) {
mHandler.post(numberPrinter);
} else {
mHandler.removeCallBacks(numberPrinter);
running = false;
}
}
Runnable numberPrinter = new Runnable() {
int i = 0;
public void run(){
running = true;
System.out.println(i++);
mHandler.postDelayed(this, 1000);
};

hey u can do it with multi threading .
create a thread that will do printing .
and on onClick event of button call the method that will call the Thread and Start and Stop the same.

Related

How to wait button clicks for a while in android

I am developing an application for blinds.
I have 4 screen sized buttons (overlapped). Every step of program one button will be clickable and every button has more than one job.
My program starts with a voice (Android TTS engine). Like "please touch screen to do x". After this step I want to wait 3 seconds for button click, if button is not clicked vocalize "please touch screen to do y" and wait 3 seconds again for job y. (x and y is first button's jobs).
Button should do one of them according to touching screen. But how can I wait 3 seconds for button click and continue to vocalize next options and wait 3 seconds again.
If first button is clicked, it will disappear-button 2 will be clickable- and TTS engine will start to vocalize second buttons options. Application will be work like this but I am stuck in waiting button clicks part.
I would advise you to use android.os.Handler instead. In your case you could do something like this:
public void onCreate() {
this.handler = new Handler()
playTheVoiceOfThingX()
viewToTap.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
doThingX();
}
});
handler.postDelayed(new PrepareThingYTask(), 3000);
}
class PrepareThingYTask() implements Runnable {
viewToTap.setOnClickListener(new OnClickListener(){
#Override
public void onClick() {
doThingY();
}
});
handler.postDelayed(new PrepareThingZTask(), 3000);
}
class PrepareThingZTask() implements Runnable {
....
}
A good reminder, the runnable executed by the handler can be executed in UIThread, so no heavy work on it, or create a different looper to run it.
Regards
You could solve your problem with busy wait.
So after you first vocalized "please touch screen..." you would start a background thread which waits for a specific amount of time, like so:
new Thread(new Runnable() {
public void run() {
Thread.sleep(3000);
runOnUiThread(new Runnable() {
#Override
public void run() {
//vocalize
}
});
}
}).start();
As you can see, from within the thread a new runnable is started after 3 seconds which again runs on the UI Thread. This, because I think I remember that you should make such sound-things (depending on your method of how to play the file / sound) only from the UI Thread.
However, this is just an idea and I could not test-run my code!
But I hope I inspired you!
Regards
Me

Android postDelayed does not delay

I have the Problem that my Android app does not delay a second (or 10 seconds), if I use the postDelayed method..
Basically I would like my program to wait one second after I clicked the button, then update the text on my textview ("READY"), wait another 2 seconds, then update the textview again ("SET") and then it should start another activity (not yet implemented :-) ).
With my code, the programm starts and after I click the button the textview shows the last text ("SET") immediately.. It just does not wait.
What am i doing wrong?
Here is my code:
public class MyCounterActivity extends Activity {
private long mInternval = 100000;
private Handler mHandler;
private Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateInterval(); //change interval
startRepeatingTask();
}
};
void startRepeatingTask(){
mHandler.postDelayed(mStatusChecker, mInternval);
//mStatusChecker.run();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gym_counter);
final TextView tv1 = (TextView) findViewById(R.id.fullscreen_content);
final Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final long up;
EditText textUp = (EditText) findViewById(R.id.editTextUp);
up = Integer.parseInt(textUp.getText().toString());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
}
},1000);
Log.d("after 1 runnable", "whaaat");
tv1.setText("Ready");
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
}
}, 2000);
Log.d("after 2nd runnable", "whaaat 2");
//startRepeatingTask();
tv1.setText("SET");
}
});
}
I also tried to run it with the runOnUiThread() (within the onClick(View v) but with with the same result). I expected it to wait 1 second (startRepeatingTask()) and then runs the loop and waits several seconds...
runOnUiThread(new Runnable() {
#Override
public void run() {
startRepeatingTask();
for (int u = 0; u < up; u++){
startRepeatingTask();
}
}
}
});
Hope my description makes sense :-).
Thank you for your help!
EDIT:
I was now able to find a solution for my first problem. The answer from #mad in this post helpded me: How to start a different activity with some delay after pressing a button in android?
(Thats probably the same thing that #laalto tried to tell me. Thanks for the hint!)
In the onClick()
tv1.setText("READY");
mHandler.postDelayed(mDelay1, 2000);
And then the Runnable
private Runnable mDelay1 = new Runnable() {
#Override
public void run() {
if (tv1.getText()=="READY")
tv1.setText("SET");
}
};
BUT:
If i want to refresh the text on my Textview after every second, how do i do that? I cant just call mHandler.postDelayed() several times.. Any help is appreciated.
When you call postDelayed(), it just places the Runnable in a queue and returns immediately. It does not wait for the runnable to be executed.
If you need something to happen after a delay, put the code in the run() method of the runnable.
Whenever you call something like Thread.start(), handler.postDelayed, view.postDelayed, AsynchTask, TimerTask .. you enter the world of threading or you might call it parallel computing.
So there can be multiple threads ("codes") running at the same time.
When you are inside your Activity it is running in a Thread that is calld UI-thread or main thread. All graphics is handled in that thread and that thread alone.
Do NEVER wait in the UI-thread!
Example: you have a button that switches color from say gray to yellow on pressing it. Now you enter a Thread.sleep(10000); - waiting 10 seconds at the start of your onClick.
You will then see that the button stays yellow (=pressed) for 10 seconds even if you only pressed very shortly. Also: if you overdo it android os will become angry and post the user if he wants to force-close your app.
So what happens on handler.postDelayed?
Android will very quickly open a thread that runs in the background parallel to your UI thread. So in some nanoseconds it has done that and will execute the next command in UI thread (in the example above it is Log.d). In the background it will wait and count the millis until time is up. Then any code that is inside the runnable.run method will again be executed in the ui-thread after the wait.
Note also: postDelayed will not be super precise with the wait time as usually the ui-thread is quite buisy and when the wait time is up it may have something else to do. Your runnable code will be added to a queue and executed when ui-thread is ready again. All this happens without you having anything to do about it.
Also:
Remember to work with try/catch inside the runnable.run as many things can happen while waiting - for example user could press Home button closing your app - so the ui-element you wanted to change after the wait could already been destroyed.

ProgressBar running faster after each onclick in android

I am Stuck here with this application in android. In my application i am trying to implement a progressbar which shows timer for certain seconds. When the Button is clicked the timer should refresh and again start from 0 in progressBar. For this I am using Thread.
The Problem is, When I Click the button the Thread calls the timer function and each time the thread is getting faster and faster. I couldn't resolve it and not having any idea what is going in background.
This is my code for Timerfunction
public void setTimer()
{
prog=0;
progress.setProgress(prog);
if(flag){
t= new Thread(new Runnable(){
public void run()
{
while(prog<100)
{
prog+=1;
handle.post(new Runnable(){
public void run()
{
progress.setProgress(prog);
if(prog==progress.getMax()&& flag){
call_fun();
}
}
});
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
Log.i("Error", null);
}
}
}
});
t.start();
}
}
I called this function in another function called RandomGeneration. If the button is clicked the randomgeneration is called and the set timer is activated everytime. But the progressbar is running faster after every click. It is constantly running in the same specific time. For example if it runs for 3 seconds in the first click, its running 2 seconds in the second click and getting faster considerably.
Can anyone please try to find what is happening in this code.
Thanks in advance..!!
From what I see a new Thread is being created everytime you click the button.
Maybe try to check if t is already running and if so update it's logic to set progress to 0?
Also, what does if(flag) do?

slowing down a user's ability to button mash in Android

I have an activity that runs some ASCII control over a network port to a remote device.
Every single button push on the interface will trigger an AsyncTask to handle the communication, and (finally) works great.
However, if a user starts button mashing like a chimp on crack, the system will crash with way too many calls on the same socket, so I've come up with a little timer function to slow down the reaction to their excitement.
I'm wondering if somebody has come up with a better way to do this?
First off, inside the onCreate:
btn_pwrtoggle = (Button)findViewById(R.id.pwr_btn);
btn_pwrtoggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!buttonMasher){
if(powerstat.equals("OFF")){
String[] commandToSend = {"POWER","ON"}
}else{
String[] commandToSend = {"POWER","OFF"};
}
deviceControl(commandToSend);
}
startButtonMashTimer();
}else{
Log.w("button masher","slow down there, monkey.");
}
}
});
Then, in the actual Activity:
Timer buttonTimer;
TimerTask buttonMonitorThread;
int chimpCrackCounter;
protected void startButtonMashTimer() {
chimpCrackCounter = 0;
buttonTimer = new Timer();
buttonMonitorThread = new TimerTask(){
#Override
public void run(){
buttonMasher = true;
if(chimpCrackCounter == 1){
buttonMasher = false;
buttonTimer.cancel();
}
chimpCrackCounter++;
}
};
buttonTimer.schedule(buttonMonitorThread, 0, 500);
}
It seems to be working just fine, (and may help somebody having the same difficulty) but I'm open to suggestions.
An easy way to prevent a user from pushing a button too often is to save the time when a button was pushed, and then next time compare the last time with the current time and if the difference is too small, ignore the action.
final static long minTimeBetweenClicks = 1000;
long lastTime;
onClick(View v){
if( System.currentTimeMillis() < lastTime + minTimeBetweenClicks ) return;
//Handle the click
lastTime = System.currentTimeMillis();
}
The beauty of this is that it doesn't require any new threads or timers, and your AsyncTasks won't have to know about the buttons.
Disable the Button after a click (setEnabled(false), perhaps in onPreExecute, and enable after the task is done, in onPostExecute.
Also, be sure to pay attention to lifecycle changes. Your AsyncTask may be killed if the Activity is paused, so be sure to check the state in onResume.

Click Listener in Android, How to check if no Button is clicked for particular time period?

I am having 10 different buttons in my application for different task to perform. I want to develop one service which continuously check (listens) and if user is not clicking any button for particular time let say for 5sec than i wish to perform some other task. How can I check that user has not clicked any button? If anyone having any idea please kindly let me know.
You could simply set a Timer to the desired length. When a button is clicked, just reset the timer. Start the timer in onResume so it starts even if the user is coming back from a phone call or other activity. You should probably stop the timer in onPause of the activity too.
In each of your click listeners save off the time the last button was clicked:
private long lastClickTimestamp;
private Handler handler = new Handler();
public void onCreate( Bundle saved ) {
BackgroundJob job = new BackgroundJob();
handler.postDelayed( job, SECONDS_TO_WAIT * 1000 );
button1.setClickListener( new OnClickListener() {
public void onClick( View view ) {
lastClickTimestamp = System.currentTimeInMillis();
// do the listener logic for button 1 here.
}
});
button2.setClickListner( new OnClickListener() {
public void onClick( View view ) {
lastClickTimestamp = System.currentTimeInMillis();
// do the listener logic for button 2 here.
}
});
// repeat that for all 10 buttons.
}
Now the smarter developer would create a reusable base class that handled setting the timestamp once, then reuse that base class in each of the 10 buttons. But, that's left up to you. Then the background job would look like:
public class BackgroundJob implements Runnable {
private boolean done = false;
// meanwhile in job:
public void run() {
if( lastClickTimestamp > 0 && System.currentTimeInMillis() - lastClickTimestamp > SECONDS_TO_WAIT * 1000 ) {
// let's do that job!
}
if( !done ) {
// reschedule us to continue working
handler.postDelayed( this, SECONDS_TO_WAIT * 1000 );
}
}
}
If you have to use a service you can send a notification to the service saying a button was clicked, then the service can keep track of the time when that occurred. I wouldn't use a service for this because playing an animation or sound doesn't need to survive if the app is put into the background or killed. Services are meant for things like playing music when someone is doing something else, chat applications, or things that need to run in the background when the user isn't interacting with the application. What you're describing could be done as I've shown because when the user gets a phone call or text message they'll leave your application, and the animation or sound you're playing probably should stop too. Pretty easy to do with the Handler option I showed. More difficult, but doable, with a service.
On each button click, update some Calendar object to a new Calendar instance and then you can check what the time is of that Calendar and see if it's more than 5 minutes ago.
//this is a field
Calendar calendar;
public void onClick(View v) {
calendar = Calendar.getInstance();
//etc
switch(v.getId()) {
}
}

Categories

Resources