0

I have problems on the handler and the timertask When I finished the handler to check the connection and update the UI on two separate threads, it works. But I want to update the network connection regularly. Maybe executing it per 5 second. I use the Timer.schedule to do this. But the application failed. I dont know whether the timer cannot go to the UI thread or not.

Also, I dont know whether there is a better way to do such multi-tasks. I am eager to see whether there is another way to do it, like AsyncTask,Looper. Thank you

public class ViewPostTest extends Activity { private String connection_status = null;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final TextView timer_view = (TextView) findViewById(R.id.result);
    final Runnable runnable = new Runnable(){

        public void run() {
            // TODO Auto-generated method stub
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkinfo = manager.getActiveNetworkInfo();

            if(networkinfo.isConnected())
            {
                connection_status = "Connected";
            }
            else
            {
                connection_status = "Disconnected";
            }
            timer_view.post(new Runnable(){

                public void run() {
                    // TODO Auto-generated method stub
                    timer_view.setText(connection_status);
                }});

        }};
    TimerTask task1 = new TimerTask(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Handler handler = new Handler();
            handler.post(runnable);
        }};
    Timer timer1 = new Timer();
    timer1.schedule(task1, 0,5000);


}

}
user1494052
  • 47
  • 1
  • 7

0 Answers0