线程 - while循环 - [Android]

时间:2011-07-31 02:42:47

标签: android multithreading while-loop

因此,在我进一步尝试在android中实现while循环时,我提出了以下代码:

private boolean connected = false;
private Thread loop = new Thread() {
    public void run() {
        Looper.prepare();
        while (connected) {
            do_Something();
        }
        Looper.loop();
    }
};

onCreate() {
    //.....
    ok = (Button) findViewById(R.id.button1);
    ok.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (connected) {
                try {
                    loop.start();
                }
                catch (Exception e) {
                    Toast.makeText(getBaseContext(), "Exception caught", Toast.LENGTH_LONG).show();
                }
            }
            return true;
        }
    });
    stop = (Button)findViewById(R.id.button2);
    stop.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //disconnects current connection
                connected = false;
            }
            return true;
        }
    });
}

也就是说,我试图触摸第一个按钮让我的UI线程切换到将反复执行的线程,直到触摸第二个按钮,在这种情况下,布尔变量k将关闭并从按下第一个按钮的按钮完全停止新创建的线程。我有google'd“线程/处理程序/ android循环”但无济于事。任何对我想要做的事情的帮助都将非常感激

简单地说,如何通过按第二个按钮来杀死创建的线程?

1 个答案:

答案 0 :(得分:1)

您是否尝试过AsyncTask?您可以做什么...在firstButton上单击启动一个新的AsyncTask,然后在secondButton上单击取消它。

//define global variable
private DoSomething doSomething;

//register firstButton onClickListener
firstButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        //start your asynctask
        if(doSomething == null || doSomething.isCancelled()){
            doSomething = new DoSomething();
            doSomething = doSomething.execute();
        }
    }
});

//register secondButton onClickListener
secondButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        doSomething.cancel();
    }
});

//Inner AsyncTask class
class DoSomething extends AsyncTask<Void, Void, Void>{
    @Override
    protected Void doInBackground(Void... params) {
        //doSomething();
        while(true){
            System.out.println(1);
            if(isCancelled()){
                break;
            }
        }
        return null;
    }
}

注意:这是伪代码...可能包含错误...只是想给你概述。希望这有帮助。