제가 작성하고 있는 앱의 경우 service를 이용하고 있기 때문에


종료되지 않고 폰이 켜져있는 한 계속 실행되고 있습니다.


여기서 Thread를 동작시키고, 앱을 이용하고 있을 때만 Thread를 동작시키고 앱이나 화면이 꺼지면 Thread를 중지시키려 합니다.


하지만 Thread.stop() 기능이 deprecated되었기 때문에 (더 이상의 API에서 지원을 하지 않는 기능이기 때문에)


다른 방법을 찾아보았습니다.



- while( )의 조건을 이용

=> 쓰레드가 동작하는 조건을 결정하는 boolean변수를 하나 만들어 쓰레드의 동작을 제어합니다.


private boolean condition = true;


@Override

public void onDestroy( ) {

super.onDestroy( );

condition = false;

}


MyThread th = new MyThread( );

th.start( );


class MyThread extends Thread( ) {

public void run( ) {

while(condition) {

 . . .

}

}

}


- Thread.interrupt( )를 이용

=> 앞의 방식과 기능은 유사하나 쓰레드의 인터럽트 함수를 사용하는 경우입니다.


MyThread th = new MyThread( );

th.start( );


@Override

public void onDestroy( ) {

super.onDestroy( );

th.interrupt( );

}


class MyThread extends Thread( ) {

public void run( ) {

while(!isInterrupted()) {

 . . .

try {

. . .

} catch (InterruptedException e) {

Thread.currentThread( ).interrupt( );

} catch (Exception e) {

e.printStackTrace( );

}

}

}

}

+ Recent posts