Timer that run every seconds on android eclipse - android

Hi every one can you help to create a 5 seconds timer that runs for every 3 or 5 seconds.. im new in android pls help me
i have only created a 5 seconds timer but it only run once.. i want it to run for every 5 seconds..
and here is my code :
txt1 = (TextView)findViewById(R.id.textView1);
final Handler handler = new Handler();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// pos=rand.nextInt(10);
//txt1.setText(""+pos);
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
Thx :)

You can do it using below code, handler calls itself again and again.
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
handler.postDelayed(this, 3000);
}
catch (Exception e) {
// handle exception
}
}
};
handler.postDelayed(runable, 5000);

Related

a good way to check if timer already run repeatedly

I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}

How to handle handler again enter into same activity?

I created one handler for calling AsyncTask in background when I start the application its working fine when I re-enter into the application it will call two times in for first one and present one, how can I handle that
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
checkandsave();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 300000); //execute in every 60000 ms = 1 minute

TimerTask / Handler with Delay getting called Multiple times

I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice
Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);

How to resolve ANR while invoking a list

I am developing an app in which a thread will run in main thread and it will call a list of users in every 1 sec,but i am getting the pop up that ANR. please suggest. How To Resolve?
Below is my code
super.onCreate(savedInstanceState);
System.setProperty("java.net.preferIPv4Stack", "true");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mHandler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
listofUsers = GcmIntentService.getListOfUsers();
if (listofUsers.size() > 0) {
for (int index = 0; index < listofUsers.size(); index++) {
if (index == 0) {
startTime = listofUsers.get(0).getLoggedinDateTime();
} else {
Calendar calender1 = Calendar.getInstance();
calender1.setTime(startTime);
calender1.add(Calendar.SECOND, i);
newTime = calender1.getTime();
listofUsers.get(index).setLoggedinDateTime(newTime);
i = i + 72;
}
///user time is checked with the current system time.
Iterator<UserInformation> userDetailsIter = listofUsers.iterator();
Calendar calender2 = Calendar.getInstance();
while (userDetailsIter.hasNext()) {
UserInformation newUserInfo = userDetailsIter.next();
Date userTime=newUserInfo.getLoggedinDateTime();
Date systemTime=calender2.getTime();
if ( userTime.compareTo(systemTime) < 0 ) {
userDetailsIter.remove();
}
}
}
}
mHandler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
mHandler.postDelayed(this, 100);
}
}
};
mHandler.postDelayed(runable, 100);
}
Please help me by guiding me about what I have done wrong
You can't make a while loop or any kind of long running operation on main queue
why don't you make a normal thread inside a repeated timer
like the below code
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
check();
}
}, 0, 100);
and inside check make a thread and do what ever you want
public void check(){
new Thread(new new Runnable() {
#Override
public void run() {
// do what you want here
}
}).start();
}

Why doesn't this update the screen after it is fired?

I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});

Categories

Resources