Mar 12, 2013

Detect if it's running in UI thread

To detect if it the code is running in ui thread, use the code:

Looper.getMainLooper().getThread() == Thread.currentThread()

Example:

detect if it the code is running in ui thread
detect if it the code is running in ui thread


package com.example.androidrunnable;

import android.os.Bundle;
import android.os.Looper;
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);

        display_in_ui(String.valueOf("Hello"));
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     display_in_ui(String.valueOf(counter));
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };
    
    private void display_in_ui(final String txt){
     if (Looper.getMainLooper().getThread() == 
       Thread.currentThread()) {
      //currently run on UI thread
      prompt.setText("on ui thread: " + txt);
     } else {
      //not on UI thread
      runOnUiThread(new Runnable(){

    @Override
    public void run() {
     prompt.setText("NOT on ui thread: " + txt);
    }
    
   });
     }
     
    }

}


No comments:

Post a Comment

Infolinks In Text Ads