handler or timer android
38,222
Solution 1
Try this code -
public class TimertestActivity extends Activity {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
afficher();
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
runnable.run();
}
public void afficher()
{
Toast.makeText(getBaseContext(),
"test",
Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 1000);
}
}
Solution 2
// Timer using Handler
private final int SPLASH_TIME = 3000;
// Handling splash timer.
private void startSplashTimer() {
new Handler().postDelayed(
new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
}, SPLASH_TIME);
}
Solution 3
You can use TimerTask
for this.But when your device goes sleep it will not working so i think you can use AlarmManager
for this.
Anyway refer this link for TimerTask
,
AlarmManager code,
AlarmManager am = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), interval, pendingIntent);
Author by
manita marwa
Updated on April 16, 2020Comments
-
manita marwa about 4 years
i'm tryin' to display a msg every 1 min!! non stop! i found exemple that display the msg just one time after a fixed delay!! can you help how can set it?? or if using timer is better how it works i need an exemple!!
public class TimertestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Handler handler = new Handler(); handler.postDelayed( new Runnable() { public void run() { afficher(); } }, 1000L); } public void afficher() { Toast.makeText(getBaseContext(), "test", Toast.LENGTH_SHORT).show(); } }
Thanks!
-
Ramindu Weeraman over 12 yearsBut in alarm manager you cant show toast message.It will show new activity.but this will helpful to you.
-
anujprashar over 12 yearsGreat that it helps you. Please also accept answer if it helps.
-
manita marwa over 12 yearsdone but i just need ur help for sthing i want to call another function that insert values in database if i launch the function alone it work but in the time it doesn't work can u help me plzzz?
-
manita marwa over 12 yearssolved thnx that i meant is to excute 2 fuction not just afficher()!! so i just called the second function simpally! thanks anyway :)