How to create Timer Task OUTSIDE onCreate in Android Studio? - android

So I have a very stupid problem. I am able to create a simple timer task that ticks every second:
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (counter == 0) {
//Reload Map...
timer.cancel();
Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
startActivity(intent);
} else {
TimeLabel.setText(Integer.toString(counter));
counter = counter - 1;
}
}
});
}
}, 0, 1000);
After one minute, it will reload my google map. But when I try to open other activity, and try to go back to Map, my MapsActivity is not killed, (even though I used finish();). That's is why my timer is overlapping.
I have a guess that I should create the timer OUTSIDE onCreate, but didn't success in doing so. Can you help me guys?

Try this
public class MainActivity extends Activity {
//Global Variables
Timer timer;
TimerTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Make a method to make it cleaner
setTimer();
}
private void setTimer() {
timer = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (counter == 0) {
//Reload Map...
timer.cancel();
Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
startActivity(intent);
} else {
TimeLabel.setText(Integer.toString(counter));
counter = counter - 1;
}
}
});
}
};
}
#Override
protected void onResume() {
super.onResume();
//This will be called after onCreate or your activity is resumed
timer.schedule(task, 0, 1000);
}
#Override
protected void onPause() {
super.onPause();
//This will be called if the app is sent to background or the phone is locked
//Also this prevent you from duplicating the instance of your timer
timer.cancel();
}
}

Related

Button to trigger every 5 seconds

My app needs tracking of real time so I need a button that needs to trigger every 5 seconds but I have no idea how to do it. Can you teach me how?
I want that in every 5 seconds that AsyncTask will be triggered.
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postLoc = new HashMap();
postLoc.put("txtLat", tvLat.getText().toString());
postLoc.put("txtLng", tvLong.getText().toString());
postLoc.put("txtOwner", pref.getString("username","").toString());
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
});
I think this code might be useful to trigger the code every 5 second
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//code to run after every 5 seconds
}
});
}
};
}
Create a method like this and call the method on button click and also call the method by using a handler like this:
mRunnable = new Runnable() {
public void run() {
public void toBecalled_Every_5_Second();
mHandler.postDelayed(mRunnable, 5000);
}
};
mHandler.postDelayed(mRunnable, 5000);
public void toBecalled_Every_5_Second(){
PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});
taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
so it will call the method every 5 second and the a sync task will execute....
I would like to have a CountDownTimer which will trigger the button click function after every 5 seconds.
CountDownTimer mTimer = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
btnStart.performClick();
this.start(); // Restart
}
}.start();
You can use Timer with TimerTask and Handler to update the result to main thread i.e your UI.
Something like this:
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run process
handler.post(new Runnable() {
public void run() {
/**************************/
/** Do your process here **/
/**************************/
}
});
}
};
}
private void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, start run TimerTask then run every 5000ms i.e 5 seconds.
timer.schedule(timerTask, 0, 5000); //
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
Insert your processing code in Handler.post(). Then start the trigger by calling startTimer(). To stop the trigger, just call stopTimerTask().

Run method from time to time and cancel in asyntask method

I need to run an action every 5 minutes, but in a particular part I need to run another action to cancel and when finished, resuming action. Is there any way to do this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_evento);
cronTimerTask = new TimerTask() {
#Override
public void run() {
startService(new Intent(getBaseContext(), CronPush.class));
}
};
cron = new Timer();
cron.schedule(cronTimerTask, 0, 30000);
}
#Override
protected Void doInBackground(Void... arg0) {
cron.cancel();
Sincronizacion s = new Sincronizacion();
s.sincronizarBD(MenuEvento.this, codigoEvento);
resume();
return null;
}
public void resume() {
cron = new Timer();
cron.schedule(cronTimerTask, 0, 30000);
}

Android Splash Screen Timer Does not Work Properly

In my app i set the splash screen timer to 5 sec and later on think that 5 sec is too long so i change it back to 1 sec and my splash screen doesn't seen on the screen and keep me waiting for more than 5 sec i couldn't find what is wrong so here is my Splashscreen code
public class Splash extends Activity
{
private Timer_Countdown timer_Countdown = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
timer_Countdown = new Timer_Countdown(5000, 1000);
timer_Countdown.start();
}
class Timer_Countdown extends CountDownTimer
{
public Timer_Countdown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
timer_Countdown.cancel();
Intent startIntent;
startIntent = new Intent("android.intent.action.MAINMENU");
startActivity(startIntent);
}
#Override
public void onTick(long millisUntilFinished) {
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
And one last thing if I change it back to 5 sec it shows up on the screen again.
Why you are using this much of code just to use splash screen. Make it simple, you can use below code.
public class Splash extends Activity {
Timer timer = new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
timer.schedule(new TimerTask() {
public void run() {
Intent intent = new Intent(Splash.this, NewActivity.class);
startActivity(intent);
finish();
}
}, 2000);
}
}
You can use Handler also
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
startActivity(new Intent(SplashActivity.this, YourNewActivity.class));
finish();
}
}, 3000);
or Using Timer with Timer Schedule
public class Splash extends Activity {
Timer t= new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
t.schedule(new TimerTask() {
public void run() {
Intent n= new Intent(Splash.this, YourNewActivity.class);
startActivity(n);
}
}, 3000);
}
}
Use this instead of Timer
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//code for starting new activity
}
}, 5000);

Invalidate() is not happening from Activity in Timer

This is my code on Activity to Invalidate the canvas it is not invalidating. Means onDraw() is not getting called even once;
public GraphView view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = GraphView(this,null);
runplotTimer();
}
public void runplotTimer()
{
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
InvalidateTimer();
}
},1000,40);
}
public void InvalidateTimer()
{
this.runOnUiThread(new Runnable() {
#Override
public void run()
{
//Log.d(ALARM_SERVICE, "Timer of 40 miliseconds");
view.InvalidateGraph();
}
});
}
on View class this is method which is gettting called from Activity. other OnDraw declaration is same as required.
public void InvalidateGraph()
{
m_bCalledPlotRealTimeGraph = true;
invalidate(chanX_count1, 0, chanX_count1+7, graphheight);
}
Any help please ?
You are attempting to make changes to the View on a Timer Thread, which will not work. You need to call invalidate on the main (UI) thread:
((Activity) view.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate(chanX_count1, 0, chanX_count1+7, graphheight);
}
});
you need to Start the Timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
InvalidateTimer();
}
},1000,40);
t.start()
Instead of Timer use Handler.
class UpdateHandler implements Runnable {
#Override
public void run(){
handler.sendEmptyMessageAtTime(0, 1000);
handler.postDelayed(this, 1000);
}
}
private Handler handler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//Call your draw method
}
}
};
Inside onCreate and onResule write
if( mupdateTask == null )
mupdateTask = new UpdateHandler();
handler.removeCallbacks(mupdateTask);
Call your handler using
handler.postDelayed(mupdateTask, 100);

changing image s for 1 second in android imageview

I am trying to change image after 1 second for image view.but its doesn't show any image on screen. following is code.please help.thank you.
code-
public class Shapes extends Activity {
Timer timer = new Timer();
int flag;
String images[]={};
ImageView iv;
static int v[]={R.drawable.round,R.drawable.rectangle};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.shapes);
iv=(ImageView) findViewById(R.id.imageView1);
timer.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (flag > 1) {
timer.cancel();
timer = null;
} else
iv.setImageResource(v[flag++]);
}
});
}
}, System.currentTimeMillis(), 1000);
}
}
how can i check resource image and change it
Use Handler instead of Timer
Handler handler = new Handler();
Runnable changeImage = new Runnable(){
#Override
public void run(){
if(flag>1)
handler.removeCallbacks(changeImage);
else{
iv.setImageResource(v[flag++]);
handler.postDelayed(changeImage, 1000);
}
}
};
start the first time from oncreate()
public void onCreate(Bundle b){
handler.postDelayed(changeImage, 1000);
}
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
flag++;
if (flag > 1) {
timer.cancel();
timer = null;
}
else
iv.setImageResource(v[flag]);
}
});
}
}, 1000, 1000); // wait 1 second before start.. then repeat every second..
It's because you put System.currentTimeMillis() as delay.
Try replacing that with 0, because the time should start after 0 ms.

Categories

Resources