Mar 12, 2013

Simple example of using Thread and Runnable

package com.example.androidrunnable;

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

public class MainActivity extends Activity {
 
 static TextView prompt;

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

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {

   while(true){
    //do something in background thread
   }
  } 
    };
    
}


You cannot access UI elements directly in background thread. Handler or runOnUiThread() can be used to access UI elements.

No comments:

Post a Comment

Infolinks In Text Ads