当前位置: 代码迷 >> Android >> 关于线程!解决办法
  详细解决方案

关于线程!解决办法

热度:71   发布时间:2016-04-28 04:48:57.0
关于线程!!
关于线程方面,我的代码如下,找不出什么不妥的地方,但虚拟器报错:”unfortrunly,XXX中止运行。”
求解!谢谢!
public class Start extends Activity  implements Runnable{
private Thread thread; //声明线程对象
private int imgNum=1;
@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.start);
thread=new Thread(Start.this); //创建一个线程
thread.start(); //开启线程
    }
public void run() {
//获取动画资源
Animation anim_start=AnimationUtils.loadAnimation(this, R.anim.a_startalpha);
while(!Thread.currentThread().isInterrupted()&& imgNum<=3){
  switch(imgNum){
case 1:
ImageView iv1=(ImageView)findViewById(R.id.start1);//获取要应用动画效果的ImageView
    iv1.setBackgroundResource(R.drawable.start1);//取得第一幅背景图
iv1.startAnimation(anim_start); //开始播放第一幅
try {
 thread.sleep(2000);
} catch (InterruptedException e) {
 // TODO 自动生成的 catch 块
 e.printStackTrace();
}
break;
case 2:
ImageView iv2=(ImageView)findViewById(R.id.start2);//获取要应用动画效果的ImageView
iv2.setBackgroundResource(R.drawable.start2);//取得第二幅背景图
iv2.startAnimation(anim_start); //开始播放第二幅
try {
  thread.sleep(2000);
} catch (InterruptedException e) {
  // TODO 自动生成的 catch 块
e.printStackTrace();
}
break;
case 3:
ImageView iv3=(ImageView)findViewById(R.id.start3);//获取要应用动画效果的ImageView
iv3.setBackgroundResource(R.drawable.start3);//取得第三幅背景图
iv3.startAnimation(anim_start); //开始播放第三幅
try {
thread.sleep(2000);
} catch (InterruptedException e) {
 // TODO 自动生成的 catch 块
  e.printStackTrace();
}
break;
            default:
}
imgNum++;
     }
}

protected void onDestroy() {
if(thread!=null){
thread.interrupt(); //中断线程
thread=null;
}
super.onDestroy();
}
}
------解决方案--------------------
你在线程里面 执行各种UI操作。

Only the original thread that created a view hierarchy can touch its views.
------解决方案--------------------
你不要 implements Runnable, 自己去类里面 Runnable runnable = new Runnable(){ ...}
不能在主线程里面更新UI, 必须要一个新的线程
可以用new Thread()
也可以用 Handler handler = new Handler();
handler.post(Runnable runnable) OR handler.postDelay(runnable, int i);
------解决方案--------------------
建议用AsyncTask来做
------解决方案--------------------
你更新UI不应该这样写
应该跳出来写个handler到主线程进行UI更新
------解决方案--------------------
在子线程里面是不允许更新主线程(UI线程)的,可以有几种解决方案:
(1)Handler
(2)AsyncTask<..>
(3)Acivity.runOneUiThread(Runnable)
   (4) View.post(Runnable)
   (5)View.postDelayed(Runnable,long)
一般使用的是前面2中,你自己去网上找找资料,学习一下,没人会什么都帮你做好的。
------解决方案--------------------
你在run对ui界面进行操作。你可以使用Handler
------解决方案--------------------
你这是定时设置背景?
在android里最好不用Thread的sleep方法,这个方法并不准时,可以使用Timer和TimerTask加上Handler来实现

  相关解决方案