开发者

Passing Parameters to Thread

开发者 https://www.devze.com 2023-04-11 05:10 出处:网络
I know this question has been asked and answered here on StackOverflow.. but I just can\'t seem to get the variables to work.Someone advised me to use this code and still no go.The brief explanation i

I know this question has been asked and answered here on StackOverflow.. but I just can't seem to get the variables to work. Someone advised me to use this code and still no go. The brief explanation is I need a function to run while your finger is down on the screen (Obviously can't be done within the UI). Thus a new thread.. x,y,height,width.

//global variables
boolean var = false; 
//instance variable to check if thread has started running for first time 
int x, y, width, height;
// variables as instance variables 
boolean fingerdown;  

Thread myThread = new Thread()
{     
    @Override
    public void run() 
    {            
        while(开发者_StackOverflow中文版fingerdown==true);           
        {                
            // class object = new class() in the activity area              
            object.function(this.x ,this.y , this.height, this.width);             
        }        
    }    
};

// this section is within the UI function that detections MotionEvents 
if (event.getAction() == MotionEvent.ACTION_DOWN) 
{
    this.x = event.getX();    
    this.y = event.getY();    
    this.width = widthf;    
    this.height = heightf; 
    fingerdown = true;     
    if(!var)
    {
        var = true; 
        myThread.start();     
    } 
}

if (event.getAction() == MotionEvent.ACTION_UP) 
{
    fingerdown = false 
} 


private class myThread extends Thread{

        int x, y;
        public myThread(int x, int y) {
            this.x = x;
            this.y = y;
        }
        @Override
        public void run() {
            // your stuff
        }
    }

To call this thread use

        myThread obj = new myThread(100,200);
        obj.start();


Construct the named class instead of anonymous.

public class TestThread implements Runnable
{
  private volatile boolean fingerdown;  
  @Override
  public void run() 
    {            
       ....
    }
  public void stopThread()
   {
    fingerdown=false;
    }    
}

Event handler code :

if (event.getAction() == MotionEvent.ACTION_DOWN) 
{
    this.x = event.getX();    
    this.y = event.getY();    
    this.width = widthf;    
    this.height = heightf; 
    fingerdown = true;     
    if(!var)
    {
        mythread=new TestThread(); 
        myThread.start();     
    } 
}

if (event.getAction() == MotionEvent.ACTION_UP) 
 {
    if(mythread!=null)
     {
      mythread.stopThread();
      mythread=null;
     }
   } 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号