大家好,
atm我正面临着当前应用程序的一个小问题。正如您在下面的代码示例中所看到的,我在longTask Thread的末尾调用了shortTask Thread。但这不符合要求。此时ui不会每2000毫秒更新一次 - 在任务结束时一次完成更改。
所以现在我有点失落 - 我可能做错了什么或遗失了什么 - 我希望你能给我建议下一步去哪里。
public class ThreadActivity extends Activity{
private final Handler myHandler = new Handler();
private Button shortTaskRun;
private Button longTaskRun;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
shortTaskRun = (Button)findViewById(R.id.but1);
shortTaskRun.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0){
Thread t = new Thread(shortTask);
t.start();
}
});
longTaskRun = (Button)findViewById(R.id.but2);
longTaskRun.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0){
Thread t = new Thread(longTask);
t.start();
}
});
}
/********************* TIMER TASKS *************************/
final TimerTask shortTask = new TimerTask(){
@Override
public void run(){
try{
myHandler.post(calcAnim1);
myHandler.post(updateUi);
// make the changes in the ui visible for 2000 ms
Thread.sleep(2000);
myHandler.post(calcAnim2);
myHandler.post(updateUi);
// and again
Thread.sleep(2000);
// and so on
}catch(InterruptedException e){e.printStackTrace();}
}
};
final TimerTask longTask = new TimerTask(){
@Override
public void run(){
try{
while(true){
myHandler.post(calcAnim1);
myHandler.post(updateUi);
// make the changes in the ui visible for 2000 ms
Thread.sleep(2000);
if(somecondition)
break;
myHandler.post(calcAnim2);
myHandler.post(updateUi);
// and again
Thread.sleep(2000);
if(somecondition)
break;
}
// AT THIS POINT: i need to start the shortTask
myHandler.post(shortTask);
}catch(InterruptedException e){e.printStackTrace();}
}
};
/********************* RUNNABLES ***************************/
final Runnable calcAnim1 = new Runnable(){
// calculation 1 and ui animation
};
final Runnable calcAnim2 = new Runnable(){
// calculation 2 and ui animation
};
final Runnable updateUi = new Runnable(){
// update views in ui
};
}
修改
谢谢你的帮助! - 我建议我选择AsyncTask并进行以下更改:public class ThreadActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
longTaskRun = (Button)findViewById(R.id.but2);
longTaskRun.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0){
new LongOperation().execute("");
}
});
}
/********************* ADDED ASYNC TASK ********************/
private class LongOperation extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... arg0){
// longTask code here
return "Executed";
}
@Override
protected void onPostExecute(String result){
// shortTask code here
}
}
}