My problem is... I have 2 events.. onCreate and Onclick. I have a thread running inside onCreate and i have to stop it inside onClick. Is this possible? If yes, please provide me with some hints/ code snippets how to implement this.
My code inside onCreate event is this:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(this);
try{
bright = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS);
}catch(Exception ex){
ex.printStackTrace();
bright = 1.0f;
}
lp = getWindow().getAttributes();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
lp.screenBrightness= dim;
getWindow().setAttributes(lp);
// SLEEP 2 SECONDS HERE ...
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
lp.screenBrightness=bright;
getWindow().setAttributes(lp);
}
});
}
}, 2000);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
this activity is running inside a loop. And i want to stop this wen i click on the button. It seems that i cannot call the Thread.interrupt() method inside the button onclick event. How do i proceed with this?