package com.ScrollBallActivity3;
import android.app.Activity;
 
 
import android.os.Bundle;
  
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Semaphore; 
 import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
 
  class Q { 
 
         
        static Semaphore semCon = new Semaphore(1);  //Creates a Semaphore with 0 permit
        static Semaphore semProd = new Semaphore(0); //Creates a Semaphore with 1 permit
 
       
        void pop() {//definition of pop()
  
     try { 
         semCon.acquire(); // Acquires a permit from this semaphore, blocking until one is available
       } catch(InterruptedException e) { 
         System.out.println("InterruptedException caught"); 
       } 
    
      
      //添加要执行的函数
       
       
       ScrollBallActivity3. animation = new TranslateAnimation(ScrollBallActivity3.width/2-20,ScrollBallActivity3.width/2-20, ScrollBallActivity3.h1 ,ScrollBallActivity3.h2);
// animation.setInterpolator(getApplicationContext(), INTERPOLATORS[2]);
       ScrollBallActivity3. animation.setDuration(2000);
       
       ScrollBallActivity3.animation.setFillAfter(true);
       ScrollBallActivity3.iv.startAnimation(ScrollBallActivity3.animation);//运行动画
      
       
      //ScrollBallActivity3.Drawball();//执行动画
 
        semProd.release();//Releases a permit 
        
   }//end of pop()  
  
 
  void push() {//definition of push()
     try { 
       semProd.acquire(); // Acquires a permit from this semaphore, blocking until one is available
     } catch(InterruptedException e) { 
       System.out.println("InterruptedException caught"); 
  
     } 
       
 
      
      ScrollBallActivity3. h1-=40;//上移动30个像素
      ScrollBallActivity3. h2-=40;//上移30个像素
 
      
      try {
        Thread.sleep(3000);// 暂停3秒等待动画结束 
   } catch (InterruptedException e) {
e.printStackTrace();
   }
        
     /*
 
       try {
       ScrollBallActivity3.is = new BufferedInputStream(ScrollBallActivity3.socket.getInputStream());
       ScrollBallActivity3.is.read(Q.y);
  } catch (IOException e) {
  // TODO Auto-generated catch block
     e.printStackTrace();
 }
 */
  
     semCon.release(); //Releases a permit     }//end of push()  
  
  } //end of Class Q
 
class Producer implements Runnable { //Class Producer get the Object of Q and run the push() 
    Q q; 
 
      Producer(Q q) { 
         this.q = q; 
          //new Thread(this).start(); 
        } 
      
      public void run() { 
       while(true){
       q.push();  
         }   
       }
     }//end of Class Producer  
 class Consumer implements Runnable { //Class Consumer get the Object of Q and run the pop() 
     Q q; 
 
      Consumer(Q q) { 
          this.q = q; 
          //new Thread(this).start(); 
         } 
 
     public void run() { 
      
      while(true){
         q.pop(); 
      }
      }  
   } //end of Class Consumer
public class ScrollBallActivity3 extends Activity {  //Main Class
/** Called when the activity is first created. */

public static  int[] INTERPOLATORS = {//定义动画类型数组
android.R.anim.accelerate_interpolator,
android.R.anim.decelerate_interpolator,
android.R.anim.accelerate_decelerate_interpolator,
android.R.anim.anticipate_interpolator,
android.R.anim.overshoot_interpolator,
android.R.anim.anticipate_overshoot_interpolator,
android.R.anim.bounce_interpolator };

 //static Socket socket;
// static BufferedInputStream is;
 static int width ;
  
 static int h1  ;//高度1
 static int h2  ;//高度2
 

 static Button  btnDrawBall; 
 static ImageView iv ;
 static Animation animation;
 

  Q q = new Q(); 
  Thread C = new Thread( new Consumer(q));
  Thread P = new Thread( new Producer(q));
 
  
  
/***
 * 主函数
 */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隐藏标题栏  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置成全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
setContentView(R.layout.main);
btnDrawBall = (Button) this.findViewById(R.id.Button01);//加入DrawSin按钮
width = getWindowManager().getDefaultDisplay().getWidth();

h1 = getWindowManager().getDefaultDisplay().getHeight();//定义高度h1
h2=h1-40;//定义高度h2
        
        
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);        ImageView iv=new ImageView(this);
 iv.setImageResource(R.drawable.blueball);
 
 animation = new TranslateAnimation(width/2-20,width/2-20, h1 ,h2);//初始化animation
layout.addView(iv,new LayoutParams(40, 40));
           iv.setVisibility(View.INVISIBLE);
       
       
        
     
btnDrawBall.setOnClickListener(new Button.OnClickListener() {//设置按钮监听器并设置按下按钮之后的动作
            


public void onClick(View v)
   {
 
/*
              //创建socket
        
        try {
         socket = new Socket("192.168.1.11",4700);
 
            } catch (Exception e) {
          e.printStackTrace();
        }
              
       */ 
               Thread C = new Thread( new Consumer(q) );
       Thread P = new Thread( new Producer(q));
      
        C.start();
        P.start();
 
   }
  });
  
  

}//主函数结束
 

static void Drawball( ) {//画球函数

animation = new TranslateAnimation(width/2-20,width/2-20, h1 ,h2);
// animation.setInterpolator(getApplicationContext(), INTERPOLATORS[2]);
 animation.setDuration(2000);
iv.startAnimation(animation);//运行动画
animation.setFillAfter(true);
 
}
 

}//end of class ScrollBallActivity3  

解决方案 »

  1.   

    上面的程序使用了java.util.concurrent.Semaphore实现了双线程,这个机制在别的程序上运行很好,比如下面的程序:package com.ScrollBallActivity;
     
    import android.app.Activity;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
     
    import android.os.Bundle;
     
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.View;
    import android.widget.Button;
     
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.net.Socket;
     
    import java.util.concurrent.Semaphore; 
     
      class Q { 
     
             
            static Semaphore semCon = new Semaphore(1);  //Creates a Semaphore with 0 permit
            static Semaphore semProd = new Semaphore(0); //Creates a Semaphore with 1 permit
     
            static byte[] y =new byte[4];//定义用来接收数据的byte
            void pop() {//definition of pop()
      
         try { 
             semCon.acquire(); // Acquires a permit from this semaphore, blocking until one is available
           } catch(InterruptedException e) { 
             System.out.println("InterruptedException caught"); 
           } 
        
          
            ScrollBallActivity.Drawball();//画圆圈
         
        
        
             try {
            Thread.sleep(1000);//drwan Canvas still for 1 second
       } catch (InterruptedException e) {
    e.printStackTrace();
       }
       
       // ScrollBallActivity.x1+=ScrollBallActivity.bytesToInt(y,0); 
           

          
            semProd.release();//Releases a permit 
            
       }//end of pop()  
      
     
      void push() {//definition of push()
         try { 
           semProd.acquire(); // Acquires a permit from this semaphore, blocking until one is available
         } catch(InterruptedException e) { 
           System.out.println("InterruptedException caught"); 
      
         } 
          
         ScrollBallActivity.x1+=10; 
        /*
           try {
           ScrollBallActivity.is = new BufferedInputStream(ScrollBallActivity.socket.getInputStream());
           ScrollBallActivity.is.read(Q.y);
      } catch (IOException e) {
      // TODO Auto-generated catch block
         e.printStackTrace();
     }
     */
      
         semCon.release(); //Releases a permit     }//end of push()  
      
      } //end of Class Q
     
    class Producer implements Runnable { //Class Producer get the Object of Q and run the push() 
        Q q; 
     
          Producer(Q q) { 
             this.q = q; 
              //new Thread(this).start(); 
            } 
          
          public void run() { 
           while(true){
           q.push();  
             }   
           }
         }//end of Class Producer  
     class Consumer implements Runnable { //Class Consumer get the Object of Q and run the pop() 
         Q q; 
     
          Consumer(Q q) { 
              this.q = q; 
              //new Thread(this).start(); 
             } 
     
         public void run() { 
          
          while(true){
             q.pop(); 
          }
          }  
       } //end of Class Consumer
    public class ScrollBallActivity extends Activity {  //Main Class
    /** Called when the activity is first created. */

     static Socket socket;
     static BufferedInputStream is;

    Button  btnDrawBall;
    static SurfaceView sfv;
    static SurfaceHolder sfh;
        
    public static float x1 =  0;   
    public static float y1 = 100;  
    static Paint paint  = new Paint();
     
     Q q = new Q(); 
     Thread C = new Thread( new Consumer(q) );
     Thread P = new Thread( new Producer(q));
     
     static Canvas canvas=new Canvas();/***
     * 主函数
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {//onCreate开始

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    paint .setColor(Color.GREEN);// green pen
    sfv = (SurfaceView) this.findViewById(R.id.SurfaceView01);
    sfh = sfv.getHolder();
     
      
     
    btnDrawBall = (Button) this.findViewById(R.id.Button01);//加入DrawSin按钮
    btnDrawBall.setOnClickListener(new Button.OnClickListener() {//设置按钮监听器并设置按下按钮之后的动作
                 public void onClick(View v)
       {
                 /*
              //创建socket
            
            try {
             socket = new Socket("192.168.1.11",4700);
     
                } catch (Exception e) {
              e.printStackTrace();
            }
                   */
                   Thread C = new Thread( new Consumer(q) );
           Thread P = new Thread( new Producer(q));
          
            C.start();
            P.start();
     
           }
      });
      
        

    }//主函数结束
     


    /*
     * 定义绘画函数DrawSin
     */
    static void Drawball( ) {//画球函数
     

      canvas = sfh.lockCanvas();// specify a rectangle which will be drawn
     
       paint .setAntiAlias(true);
      
      canvas.drawColor(Color.BLACK);// clean up the canvas  
      
      canvas.drawCircle(x1,y1 ,10, paint);   
              sfh.unlockCanvasAndPost(canvas);// unlock the canvas and show the drawn picture 

    //canvas.drawColor(Color.BLACK);// clean up the canvas  

    }//end of DrawSin()

       static int bytesToInt(byte[] data, int offset) {
       int num = 0;
       for (int i = offset; i < offset + 4; i++) {
        num <<= 8;
        num |= (data[i] & 0xff);
       }
       return num;
    }}//end of class AndroidSinFinal上面这个程序实现的是一个绿色小球一点一点地向右侧移动,完全可以正常运行。但是帖子开始处贴出来的代码却无法运行,这是为什么,有谁知道?
      

  2.   

    线程内不能操作UI作动画的 用handler发消息给主线程处理动画
      

  3.   

    试试这个package com.ScrollBallActivity;
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.ImageView;
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.concurrent.Semaphore; 
    import android.view.animation.Animation;
    import android.view.animation.TranslateAnimation;
    import android.widget.LinearLayout;
    import android.widget.LinearLayout.LayoutParams;
     
      class Q { 
         int i=0;
            static Semaphore semCon = new Semaphore(1);  //Creates a Semaphore with 0 permit
            static Semaphore semProd = new Semaphore(0); //Creates a Semaphore with 1 permit
            void pop() {//definition of pop()
            try { 
             semCon.acquire(); // Acquires a permit from this semaphore, blocking until one is available
             } 
            catch(InterruptedException e) { 
             System.out.println("InterruptedException caught"); 
             } 
            ScrollBallActivity3.hDraw.sendEmptyMessage(1);
            semProd.release();//Releases a permit 
       }//end of pop()  
      
     
       void push() 
       {//definition of push()
         try 
          { 
           semProd.acquire(); // Acquires a permit from this semaphore, blocking until one is available
          } 
         catch(InterruptedException e) { 
           System.out.println("InterruptedException caught"); 
          } 
         ScrollBallActivity3. h1-=40;//上移动30个像素    
         ScrollBallActivity3. h2-=40;//上移30个像素
         try {
            Thread.sleep(2000);// 暂停3秒等待动画结束 
         } 
         catch (InterruptedException e) {
            e.printStackTrace();
          }
         semCon.release(); //Releases a permit 
        }//end of push()  
      } //end of Class Q
     
    class Producer implements Runnable { //Class Producer get the Object of Q and run the push() 
        Q q; 
          Producer(Q q) { 
             this.q = q; 
            } 
          public void run() { 
              while(true){
              q.push();  
             }      
           }
         }//end of Class Producer  
     
    class Consumer implements Runnable { //Class Consumer get the Object of Q and run the pop() 
         Q q; 
           Consumer(Q q) { 
              this.q = q; 
             } 
          public void run() { 
             while(true){
             q.pop(); 
             }
          }  
       } //end of Class Consumer
    public class ScrollBallActivity3 extends Activity {  //Main Class
        /** Called when the activity is first created. */
        public static  int[] INTERPOLATORS = {//定义动画类型数组    
            android.R.anim.accelerate_interpolator,
            android.R.anim.decelerate_interpolator,
            android.R.anim.accelerate_decelerate_interpolator,
            android.R.anim.anticipate_interpolator,
            android.R.anim.overshoot_interpolator,
            android.R.anim.anticipate_overshoot_interpolator,
            android.R.anim.bounce_interpolator };
        
         //static Socket socket;
        // static BufferedInputStream is;
         static int width ;
          
         static int h1  ;//高度1    
         static int h2  ;//高度2
         static Button  btnDrawBall; 
         static ImageView iv ;
         static Animation animation;
         static Handler hDraw;
         
          Q q = new Q(); 
          Thread C = new Thread( new Consumer(q));
          Thread P = new Thread( new Producer(q));
     
    /***
     * 主函数
     */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //隐藏标题栏  
            requestWindowFeature(Window.FEATURE_NO_TITLE);  
            //设置成全屏  
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);  
            setContentView(R.layout.main);
            hDraw=new Handler(){
    @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    if(msg.what==1)
    {
    Drawball();
    }
    else
      super.handleMessage(msg);
    }
            };
            btnDrawBall = (Button) this.findViewById(R.id.Button01);//加入DrawSin按钮
            width = getWindowManager().getDefaultDisplay().getWidth();
            h1 = getWindowManager().getDefaultDisplay().getHeight();//定义高度h1
            h2=h1-40;//定义高度h2
            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            iv=new ImageView(this);
            iv.setImageResource(R.drawable.icon);
            animation = new TranslateAnimation(width/2-20,width/2-20, h1 ,h2);//初始化animation
            layout.addView(iv,new LayoutParams(40, 40));
            iv.setVisibility(View.INVISIBLE);
            btnDrawBall.setOnClickListener(new Button.OnClickListener() {//设置按钮监听器并设置按下按钮之后的动作
                public void onClick(View v)
                   {
                          Thread C = new Thread( new Consumer(q) );
                          Thread P = new Thread( new Producer(q));
                              
                           C.start();
                           P.start();    
     
                   }
                  });
        }//主函数结束
     
        void Drawball( ) {//画球函数
          if(h1<0) 
          {
            h1 = getWindowManager().getDefaultDisplay().getHeight();//定义高度h1
              h2=h1-40;
             }
            animation = new TranslateAnimation(width/2-20,width/2-20, h1 ,h2);
            animation.setInterpolator(this, INTERPOLATORS[2]);
            animation.setDuration(1000);
            iv.startAnimation(animation);//运行动画
            animation.setFillAfter(true);
        }
    }//end of class ScrollBallActivity3