在线等,一下代码的运行原理,以及为撒当i=100时,还在执行??

KKL 2011-08-03 09:51:38
public class TestActivity extends Activity {
private Button startButton = null;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

startButton = (Button)findViewById(R.id.startButton);

startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateBarHandler.post(updateThread);
}
});

}

Handler updateBarHandler = new Handler(){
public void handleMessage(Message msg){
updateBarHandler.post(updateThread);
}

};

Runnable updateThread = new Runnable() {
int i = 0;
public void run() {
i = i + 10;

Message msg = updateBarHandler.obtainMessage();
msg.arg1 = i;

try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}

updateBarHandler.sendMessage(msg);
Log.i("updateThread", ""+i);
if (i == 100) {
updateBarHandler.removeCallbacks(updateThread);
}
}
};

}
...全文
114 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wenlin56 2011-08-04
  • 打赏
  • 举报
回复
4楼应该是正确的。
domonate 2011-08-04
  • 打赏
  • 举报
回复
mark 学习一下吧
FLYUP_CHEN 2011-08-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 kkl510331367 的回复:]

Java code
ActivityManager: Warning: Activity not started, its current task has been brought to the front
好几次抱这种错,不知怎么回事
[/Quote]

报这样的错误时因为你已经把当前的线程休眠了。
redoffice 2011-08-04
  • 打赏
  • 举报
回复
mark 学习
fontlose 2011-08-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 kkl510331367 的回复:]
Java code
ActivityManager: Warning: Activity not started, its current task has been brought to the front
好几次抱这种错,不知怎么回事
[/Quote]

退出模拟器中运行的程序,或project->clean一下。
fontlose 2011-08-04
  • 打赏
  • 举报
回复
执行到100还会加是由于updateBarHandler.removeCallbacks(updateThread);代码运行到这里消息列队里已没updateThread了,虽然前面有updateBarHandler.sendMessage(msg)但是这只是往消息列队加消息,不会马上执行消息处理。等于100时你应该调用updateBarHandler.removeMessages(msg.what);
或者小于100才发消息。

Runnable updateThread = new Runnable() {
int i = 0;
public void run() {
i = i + 10;

Message msg = updateBarHandler.obtainMessage();
msg.arg1 = i;

try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}


Log.i("updateThread", ""+i);
if (i < 100) {
updateBarHandler.sendMessage(msg);
}
}
};
浪中云 2011-08-03
  • 打赏
  • 举报
回复
按键点击一下,触发线程执行run方法, msg.arg1 = i;updateBarHandler.sendMessage(msg);执行之后
updateBarHandler.post(updateThread);再次会到run方法
报错的意思是。模拟器当前运行的程序就是你这个程序
KKL 2011-08-03
  • 打赏
  • 举报
回复
ActivityManager: Warning: Activity not started, its current task has been brought to the front
好几次抱这种错,不知怎么回事
KKL 2011-08-03
  • 打赏
  • 举报
回复

80,360

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧