954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Timer Trouble

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.

ajst
Junior Poster
121 posts since Nov 2010
Reputation Points: 30
Solved Threads: 3
 

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);				    
 		   		}
 	   }
 	};
ajst
Junior Poster
121 posts since Nov 2010
Reputation Points: 30
Solved Threads: 3
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: