I want to have an android app, in which the background is flashing as long as I'm pressing a button. This works, but when I release the button the background doesn't stop flashing. I think the reason is that I'm using a Thread. I don't know exactly how to stop it(and I'm working the first time with Threads). I thought I could write in the Action_Up Event of the Button "threadname.stop()" but Android studio cannot resolve the name. So: how can I stop the Thread so that the the Action_Up case gets performed ? Thank You very much !!!
My MainActivity code:
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Button flash;
RelativeLayout layout;
boolean backgroundisblack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backgroundisblack = true;
layout = (RelativeLayout)findViewById(R.id.layout);
flash = (Button)findViewById(R.id.flash );
//Button
flash.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//button is pressed
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:{
//thread
Thread t = new Thread(){
@Override
public void run(){
while(!interrupted()){
try {
Thread.sleep(1000);
runOnUiThread(new Runnable(){
@Override
public void run(){
//action
if(backgroundisblack){
layout.setBackgroundColor(Color.WHITE);
backgroundisblack = false;
}else if (!backgroundisblack){
layout.setBackgroundColor(Color.BLACK);
backgroundisblack = true;
}
}
});
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
t.start();
break;
}
//button is released
case MotionEvent.ACTION_UP:{
layout.setBackgroundColor(Color.BLACK);
break;
}
}
return false;
}
});
}
}