Mar 12, 2013

Access UI thread in Handler

Last example demonstrate how to implement Thread and Runnable. You cannot access UI elements directly in background thread. Handler can be used to access UI elements.

package com.example.androidrunnable;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 static TextView prompt;
 static int counter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);
        
        prompt.setText("Hello");
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }
    
 static Handler myHandler = new Handler(){

  @Override
  public void handleMessage(Message msg) {
   prompt.setText(String.valueOf(counter));
  }
     
    };

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     myHandler.sendMessage(myHandler.obtainMessage());
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };
    
}


No comments:

Post a Comment

Infolinks In Text Ads