android开发 进度条出现死循环


public class MainActivity extends Activity implements OnClickListener{


 private Button startBtn = null;
ProgressBar bar = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bar = (ProgressBar)findViewById(R.id.bar);
    startBtn = (Button)findViewById(R.id.startbtn);
    startBtn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    bar.setVisibility(View.VISIBLE);
    handler.post(updateThread);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        bar.setProgress(msg.arg1);
        if (msg.arg1<40)
            handler.post(updateThread);
    }
};
Runnable updateThread = 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) {
            e.printStackTrace();

        }
        handler.sendMessage(msg);
        if ( i == 20 ) {
            System.out.println("errrrrrrrr");
            handler.removeCallbacks(updateThread);
        }
    }
};

}

上面这段代码为什么会在进度条到40时才终止呢?按说到20的时候,handler线程队列里面就清除了运行的线程不会继续执行了的啊?

编程 Android

一张床创业 11 years, 7 months ago

Your Answer