STOP MAINTENANCE!(2017-05-25)
刚在做复习时发现了一个问题,加入了Handler的线程,即使调用了removeCallbacks线程还是存在,而且退出了Activity之后线程还在运行。难道是removeCallBacks无效?还是我哪里写错了?
package cfuture09.handlerProgress; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class HandlerProgressActivity extends Activity { Button start; ProgressBar progressBar; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub progressBar.setProgress(msg.arg1); handler.post(r); } }; Runnable r = new Runnable() { int i = 0; @Override public void run() { // TODO Auto-generated method stub System.out.println("Begin thread"); i += 10; Message msg = handler.obtainMessage(); msg.arg1 = i; try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if ( i < 100) { handler.sendMessage(msg); // } if ( i >= 100) { handler.removeCallbacks(r); System.out.println("end"); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); start = (Button) findViewById(R.id.start); progressBar = (ProgressBar) findViewById(R.id.progress); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub progressBar.setVisibility(ProgressBar.VISIBLE); handler.post(r); } }); } }
刚和一个同学聊天说到这一段,跟他一说,忽然之间自己想明白了。原来还是代码的逻辑错误。这段代码我是看视频写的,可能视频的作者在写这段代码时也没注意到这个问题。在看了之后的视频我才想明白。聊天记录用图片贴上来吧。