Hi Guys and Girls,

I'm having some trouble getting a timer to work on my android 2.1 app.

I want it so once a button is clicked it trys to connect to my server
every 60 seconds.

my code for connecting to server is working, but I don't understand why my timer wont.

Timer timer = new Timer();

TimerTask timerConnect = new TimerTask() {
        public void run() {
        	tryconnecting();
        	if(Globals.socket10400.isConnected())
        	{
        		this.cancel();
        	}
        }
    };

//this is the method called once button is clicked
private void connectClick()
    {
        Globals.timer.schedule(timerConnect, 5000, 60000);
    }

//working server connect code.
   public void tryconnecting()
    {
    	boolean connecting = false;    	
    	LblWelcomeMessage.setText("connecting");
    	while (!connecting)
    	{
    		try {
    			if(Globals.sendTCP.ConnectToServer())
    			{
    				LblWelcomeMessage.setText("connected");
    				connecting = true;
    			}
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			LblWelcomeMessage.setText("Not Connected");
    		}
    	}
    }

Thanks in advance.

Just incase someone else comes across the problem is that
the Timer class in java can not be initialised at run time with Android so you need to use to use output handler and post by a delay.

//make sure outputHandler is is set
outputHandler = Globals.outputHandler;		
//call your method with a delay of 60 seconds
outputHandler.postDelayed(mServerResponeTimer, 60000);

private Runnable mServerResponeTimer = new Runnable() {
 	   public void run() {
                              //do code
                              // then remove the current task from the schedule.
                               outputHandler.removeCallbacks(mServerResponeTimer);
                               //re add the event if needed and call it again in 60secs time
                                outputHandler.postDelayed(mServerResponeTimer, 60000);				    
 		   		}
 	   }
 	};
commented: Thank you for sharing +16
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.