Increment an integer ever 30 seconds after button press Android - android

I'm looking for a way to increment an integer every 30 seconds after a button is pressed. The problem I am having is that my code currently waits 30 seconds to increment the integer by 1 but then only one second for every integer after. this is my code.
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(ammo_remaining<10){
update_ammo();``
}
}
});
}
}, delay, period);

Moving the recursive postdelayed call into your (ammo<10) if statement should give you the behavior you want.
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
int ammo_remaining = 10;
boolean reloading = false;
Handler handler=new Handler();
protected void shoot()
{
ammo_remaining--;
update_ammo();
if( ! reloading) //if not reloading
{
reloading = true;
handler.postDelayed(r, delay);
}
}
Runnable r=new Runnable()
{
public void run()
{
if(ammo_remaining<10)
{
ammo_remaining++;
update_ammo();
handler.postDelayed(r, period);
}
else{reloading=false;}
};
};
edit:
when shooting multiple times, you are creating many instance of the runnable through the handler, that all flood in after the first 30 seconds... you just need to create a boolean flag to keep track of the first request to reload
that 'reloading' flag and check should do the trick...

Button btn = (Button)findViewById(R.id.your button);
// first get your button;
final Handler hand = new Handler();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
hand.post(new Runnable(){
#override public void run(){
(your int)++; // this will increase your int on step;
hand.postDelayed(this,30*1000); // this will do the same thing after 30 seconds again;
}
}
}
});

Try using handler:
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
Handler handler=new Handler();
protected void your_calling_method()
{
handler.postDelayed(r, delay);
}
Runnable r=new Runnable()
{
public void run()
{
if(ammo_remaining<10)
{
update_ammo();
}
handler.postDelayed(r, period);
};
};

Related

Some times Toast is not visible in activity or inside fragment when added inside handler

Requirement is that toast will be show some delay in fragment so add inside the handler.
But sometime that toast is not visible. There are some loader operations and fragment transaction action before toast.
final Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms\
Toast.makeText(getActivity,message,Toast.LENGTH_SHORT).show();
}
}, 100);
You can achieve this using Handler, Timer Task, CountDownTimer, and using for loop too. My favorite is CountDownTimer which is very easy and fast solution.
private long duration = 30000; // 30 seconds
private long interval = 1000; // 1 seconds
CountDownTimer cd = new CountDownTimer(duration, interval) {
#Override
public void onTick(long l) {
// This method call every seconds.
}
#Override
public void onFinish() {
// When 30 seconds completed this method is called.
Toast.makeText(Activity.this, "Hello", Toast.LENGTH_SHORT).show();
}
};
cd.start();
You can change duration and interval according to your need.
Use Log tag.
final Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms\
Log.d("MyLogTag", message);
}
}, 100);

I need a simple incrementation over time function

I want to do a cookie clicker like app and i need a simple incrementation over time function.
But i would only want the int to start increasing once i have pressed a button.
I tried this but does not work properly.
int delay = 5000;
int period = 1000;
int count = 0;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
count++;
score.setText(String.valueOf(count));
}
}, delay, period);
The reason its not working is because run() is running on separate Thread, not on UIThread. You need to run setText in UIThread. see the code below
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
count++;
score.setText(String.valueOf(count));
}
});
}
}, delay, period);

Stop repeating timer android

I want to create 10 ImageViews with a delay of 5 seconds between, I created this code:
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (counter <= 10)
newimg();
else
// here I want to stop the timer so it will not try to create any more `ImageViews` (the array contains only 10).
}
}, 0, 5000);
private void newimg() {
ball[counter] = new ImageView(this);
ball[counter].setTag(counter);
ball[counter].setBackgroundResource(R.mipmap.ball);
int randomx = rand.nextInt(layoutwidth);
int randomy = rand.nextInt(layoutheight);
ball[counter].setX(randomx);
ball[counter].setY(randomy);
rlt.addView(ball[counter]);
counter++;
}
How can I stop the timer inside the else statement?
Call Timer cancel to stop the timer.
Call cancel() on timer
My Solutions is :
Handler handler = new Handler();
handler.postDelayed(createImageView, 5000);
Runnable createImageView=new Runnable() {
#Override
public void run() {
if (counter <= 10){
handler.postDelayed(this,5000);
newimg();
}
}
};

Repeat a Method for specific times in android

Here is a code which I want to repeat 50 times after every 3 seconds. if I am calling this function with 'for' loop or 'while' loop it is not working properly Please give me suggestion.
for (int i = 0; i < 50; i++) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Generate_Ballon();
}
}, delay);
}
You can use CountDownTimer
See Example,
new CountDownTimer(150000, 3000)
{
public void onTick(long millisUntilFinished)
{
// You can do your for loop work here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here onTick() method will get executed on every 3 seconds.
You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Generate_Ballon();
if (--count > 0) {
handler.postDelayed(r, delay);
}
}
};
handler.postDelayed(r, delay);

android - How to repeat a function every contant time?

How to schedule a function every defined time with the option to change this time?
I found that I can do it using timer & timerTask or handler. The problem that it dosen't repeats the time I defined, it repeats randomaly...
runnable = new Runnable() {
#Override
public void run() {
//some action
handler.postDelayed(this, interval);
}
};
int hours = settings.getIntervalHours();
int minutes = settings.getIntervalMinutes();
long interval = (hours * 60 + minutes) * 60000;
changeTimerPeriod(interval);
private void changeTimerPeriod(long period) {
handler.removeCallbacks(runnable);
interval = period;
runnable.run();
}
Use a Handler object in the onCreate method. Its postDelayed method causes the Runnable parameter to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 millis in this example).
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable()
{
public void run()
{
//write here whaterver you want to repeat
customHandler.postDelayed(this, 1000);
}
};
I used the solution here
But in the code where the handler was initialized, I used
mHandler = new Handler(getMainLooper);
instead of
mHandler = new Handler();
which worked for me

Categories

Resources