栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Android动画的简单线程问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android动画的简单线程问题

如果实现Thread或HandlerThread,请确保在等待辅​​助线程完成时UI线程不会阻塞-
不要调用

Thread.wait()
Thread.sleep()

http://developer.android.com/training/articles/perf-
anr.html

您的主线程应该为

Handler
其他线程在完成后回发,而不是在等待工作线程完成时阻塞。

使用处理程序

   Handler m_handler;   Runnable m_handlerTask ;     m_handler = new Handler();   m_handlerTask = new Runnable()   {     @Override      public void run() {    // do something     m_handler.postDelayed(m_handlerTask, 1000); // instad of 1000 mention the delay in milliseconds     }   };   m_handlerTask.run();

当您需要取消处理程序时,请使用m_handler.removeCallbacks(m_handlerTask);。

例:

 public class MainActivity extends Activity {RelativeLayout rl;int x = 0,y=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    rl = (RelativeLayout) findViewById(R.id.rl);    CustomView cv = new CustomView(this);    rl.addView(cv);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;}public class CustomView extends View {    Bitmap bball;     Random randX, randY;    double theta;    Handler m_handler;    Paint p ;    int width;    int height;    Runnable m_handlerTask;    public CustomView(Context context) {        super(context);        // TODO Auto-generated constructor stub        p= new Paint();        bball = BitmapFactory.depreResource(getResources(), R.drawable.ic_launcher);          //randX = 1 + (int)(Math.random()*500);         //randY = 1 + (int)(Math.random()*500);        randX = new Random();        randY = new Random();        theta = 45;        m_handler = new Handler();       }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        // TODO Auto-generated method stub        super.onSizeChanged(w, h, oldw, oldh);        width =w;        height=h;     }    public void move()    {        m_handlerTask = new Runnable(){  @Override   public void run() {      //theta = theta + Math.toRadians(2);       if(x<300)        { x= x+10; invalidate();        }          else if(x>300){    x=0;    m_handler.removeCallbacks(m_handlerTask);}          // canvas.drawBitmap(bball, x, y, p); m_handler.postDelayed(m_handlerTask, 3000);  }};m_handlerTask.run();    }    public void onDraw(final Canvas canvas){        super.onDraw(canvas);       canvas.drawBitmap(bball, x, y, p);         if(x<300){move();}       else        {m_handler.removeCallbacks(m_handlerTask);       }    }} }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号