Skip to content Skip to sidebar Skip to footer

Thread -while Loop- [android]

So in my further attempts to implement a while loop in android I have come up with the code below : private boolean connected = false; private Thread loop = new Thread() { publ

Solution 1:

Did you tried AsyncTask ? What you can do...start a new AsyncTask on firstButton click and cancel it on secondButton click.

//define global variableprivateDoSomething doSomething;

//register firstButton onClickListener
firstButton.setOnClickListener(newOnClickListener() {
    @OverridepublicvoidonClick(View arg0) {
        //start your asynctaskif(doSomething == null || doSomething.isCancelled()){
            doSomething = newDoSomething();
            doSomething = doSomething.execute();
        }
    }
});

//register secondButton onClickListener
secondButton.setOnClickListener(newOnClickListener() {
    @OverridepublicvoidonClick(View arg0) {
        doSomething.cancel();
    }
});

//Inner AsyncTask classclassDoSomethingextendsAsyncTask<Void, Void, Void>{
    @OverrideprotectedVoiddoInBackground(Void... params) {
        //doSomething();while(true){
            System.out.println(1);
            if(isCancelled()){
                break;
            }
        }
        returnnull;
    }
}

Note: This is pseudocode...might contain error...just want to give you overview. hope this help.

Post a Comment for "Thread -while Loop- [android]"