我在点击暂停按钮pauseb时使用两个线程只显示暂停文本我需要暂停线程直到再次点击按钮
handler1=new Handler();
j=new Runnable(){
public void run() {
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams) b2.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
absParams.x = r.nextInt(width);
absParams.y = r.nextInt(height);
b2.setLayoutParams(absParams);
Animation animation = AnimationUtils.loadAnimation(page2.this, R.anim.fade);
b2.startAnimation(animation);
handler1.postDelayed(j, 870);
}};
handler1.postDelayed(j, 50);
final Button pauseb = (Button) findViewById(R.id.pauseid);
pauseb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (pause == false) {
pauseb.setText("Pause");
pause = true;
}
else{
pauseb.setText("Play");
pause = false;
}
}
});
handler = new Handler();
t = new Runnable() {
public void run() {
Intent d = new Intent(getApplicationContext(), Page3.class);
d.putExtra("count", count);
d.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(d);
}
};
handler.postDelayed(t, 8000);
}
当单击暂停按钮时,线程正在工作8秒,它应该暂停整个活动直到重新开始
答案 0 :(得分:0)
调用handler.removeCallbacks(j或t)删除j或t。
并调用handler.postDelayed(j或t,time)继续你的东西。
顺便说一句,Handler在你创建Handler的线程上运行Runnable。在你的情况下,它的UI线程。
答案 1 :(得分:0)
使用布尔标志....
boolean pause = false;
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
customHandler.removeCallbacks(updateTimerThread);
button.setVisibility(View.VISIBLE);
pause = true;
}
});
private Runnable updateTimerThread = new Runnable() {
int secs;
@Override
public void run() {
// TODO Auto-generated method stub
timeInMillisecond = SystemClock.uptimeMillis()- startTime;
updatedTime = timeSwapBuff+timeInMillisecond;
secs = (int)(updatedTime/1000);
int mins = secs/60;
secs = secs % 60;
int milliseconds = (int)(updatedTime % 10000);
textView.setText( String.format("%02d", secs));
if(!pause)
customHandler.postDelayed(this,1000);
imageView1 = (ImageView)findViewById(R.id.imageView4);
}};