Skip to content Skip to sidebar Skip to footer

Handler Or Timer Android

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 bett

Solution 1:

Try this code -

publicclassTimertestActivityextendsActivity {
    Handlerhandler=newHandler();
    Runnablerunnable=newRunnable() {
        publicvoidrun() {
            afficher();
        }
    };

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle icicle) {   
        super.onCreate(icicle);   
        setContentView(R.layout.main);  
        runnable.run();
      }   

      publicvoidafficher()
      {
          Toast.makeText(getBaseContext(),
                     "test",
                     Toast.LENGTH_SHORT).show();
          handler.postDelayed(runnable, 1000);
      }
}

Solution 2:

// Timer using Handlerprivate final int SPLASH_TIME = 3000;

// Handling splash timer.privatevoidstartSplashTimer() {
    new Handler().postDelayed(
    new Runnable() {
    @Override
    publicvoidrun() {
        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,

AlarmManageram= (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(), interval, pendingIntent);

Post a Comment for "Handler Or Timer Android"