public class ThreadKillDemo extends Activity {
private int i = 0;
Thread threadTest;
@Override
public void onStop(){
super.onStop();
if(threadTest != null && threadTest.isAlive())
threadTest.interrupt();
}
@Override
public void onResume(){
super.onResume();
i = 0;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnTest = (Button)findViewById(R.id.btn_thread_start);
btnTest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(threadTest != null && threadTest.isAlive()) //반드시 null검사를 선행.
threadTest.interrupt(); //Thread를 interrupt 한다.
i++;
threadTest = new Thread(new Runnable() {
@SuppressWarnings("static-access")
public void run() {
int j = i;
while(!threadTest.interrupted()){ // interrupt 호출 시 interrupted는 true 반환.
SystemClock.sleep(1);
Log.i("THREADKILL","WORKING "+j);
}
}
});
threadTest.start();
}
});
Button btnNext = (Button)findViewById(R.id.btn_next);
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ThreadKillDemo.this, ActivityTest.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
}
}