-2

I have a timer in my android program:

 timer1= new Timer();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }

        }, 0, 3000);


private void TimerMethod()
{
    this.runOnUiThread(Timer_Tick);
}


private Runnable Timer_Tick = new Runnable() {
        public void run() {
            //my code
}}

I want to send a parameter to Timer_Tick from TimerMethod , in other word I want an input parameter for Timer_Tick ,

I changed my code to:

int input1=10;
 timer1= new Timer();
            timer1.schedule(new TimerTask() {
                @Override
                public void run() {
                    TimerMethod(input1);
                }

            }, 0, 3000);



  private void TimerMethod(int myinput)
    {
        this.runOnUiThread(Timer_Tick);
//How pass myinput to Timer_Tick????????????

    }

what should I do?

Mary
  • 41
  • 8

1 Answers1

0

You can create a new class (MyTimerTask) that implements the Runnable interface, and has the run method. In this class add your parameter as one of the class fields and set in the constructor of that with the desired value. The rest would really easy and straightforward :

public class MyTimerTask implements Runnable
{
    private String param ;

    public MyTimerTask(String param)
{
 this.param = param
}

@Override
public void run()
{
//your code
}
}

MyTimerTask mytimertask = new MyTimerTask(myparameter);

timer1.schedule(mytimertask,0,3000) ;
Farhad
  • 12,178
  • 5
  • 32
  • 60
  • 1
    thanks, but I do not want write another class, is there other way? – Mary Feb 20 '16 at 10:00
  • You can make your parameter a static member of the current class so that the run method will have access to it – Farhad Feb 20 '16 at 10:03
  • Then you shoud take my solution and make four different objects of MyTimerTask. I can't get why you don't want to create another class. – Farhad Feb 20 '16 at 10:52