0

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.

1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by ajst
1

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);				    
 		   		}
 	   }
 	};

Edited by ajst: typo

Votes + Comments
Thank you for sharing
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.