안드로이드 프로그래밍[JAVA Code]/Thread

Thread : Runnable & post AlertDialog 박스

훈츠 2019. 12. 5. 13:37
반응형

,핸들러를 사용해서 메시지를 보내면 조금 코드가 복잡하게 보이는 단점이 있어, 이보다 조금더 간단한 방법인 Runnable 객체를 실행 시키는 법에 대해 기술 해보겠다. 핸들러 클래스는 메시지 전송 방법 이외에 Runnable 객체를 실행 시킬수있는 방법을 제공 한다. 즉 Runnable 객체를 핸들러의 post() 메서드로 전달해주면 이 객체에 정의된 run()메서드 안의 코드들은 메인 스레드에서 실행 된다. 한마디로 별도의 핸들러 정의 할 필요 없이 Handler 객체 만들고, 만든 userThread 안에서 hander.post( new Runnable ) 하면 별도의 핸들러 없이 바로 메인 UI 접근이 가능하다. 

1) hander.post( new Runnable )코드 

public class MainActivity extends AppCompatActivity {
    Handler handler = new Handler(  );
    TextView textValue;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        textValue = (TextView) findViewById( R.id.textValue );
        btn =(Button) findViewById( R.id.btn );
        btn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainBackgroundThread thread = new MainBackgroundThread();
                thread.start();
            }
        } );

    }

    class MainBackgroundThread extends Thread{
        int value = 0;
        public void run(){
            for(int i=0 ;i<1000; i++) {
                try {
                    Thread.sleep( 100 );
                } catch (Exception e) {
                    e.printStackTrace();
                }
                value += 1;

                handler.post( new Runnable() {
                    @Override
                    public void run() {
                        textValue.setText( "value값 "+String.valueOf( value ) );
                    }
                } );
            }
        }
    }
}

2) handler.postDelayed & .postAtTime 메소드 이용하여 지연시간이나 원하는시간데에 시작할수도 있다. 

handler.postAtTime( new Runnable() {
	@Override
	public void run() {

	}
	},1000 );
handler.postDelayed( new Runnable() {
	@Override
	public void run() {

	}
	},1000 );

3) AlertDialog 박스 이용해서, Thread delay 실행 예제

public class MainActivity extends AppCompatActivity {
    Handler handler = new Handler(  );
    TextView textValue;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        textValue = (TextView) findViewById( R.id.textValue );
        btn =(Button) findViewById( R.id.btn );
        btn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = "원격지원요청";
                String msg = "데이터 요청 하시겠습니까?";
                String titleBtnYes = "원격지원요청";
                String titleBtnNo = "원격지원거부";

                AlertDialog alertDialog = makeRequestDialog(title,msg,titleBtnYes,titleBtnNo);
                alertDialog.show();

                MainBackgroundThread thread = new MainBackgroundThread();
                thread.start();
            }
        } );

    }

    private AlertDialog makeRequestDialog(CharSequence title,CharSequence msg, CharSequence titleBtnYes,CharSequence titleBtnNo){
        AlertDialog.Builder requsetDialog = new AlertDialog.Builder( this );
        requsetDialog.setTitle( title );
        requsetDialog.setMessage( msg );
        requsetDialog.setPositiveButton( titleBtnYes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                textValue.setText( "대화 상자 표시중.." );
                handler.postDelayed( new Runnable() {
                    @Override
                    public void run() {
                        textValue.setText( "요청 완료됨." );
                    }
                },1000 );
            }

        } );
        requsetDialog.setNegativeButton( titleBtnNo, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        } );
        return  requsetDialog.create();
    }
    }

결론: Thread에서 Main UI 접근 방법은 두가지 , 첫번째는 MainHandler 같은 별도의 Thread 만들어서 그안에서 Post이용해서 던지는 방법 두번째는 기본 Handler 이용해서 그안에서 post로 던지는 방법. 하지만 요즘은 그냥 Handler 필요없이 Thread 에서 바로 Main UI 접근이 가능한걸로 봐서 업그레이드 된거 같다. 

반응형

'안드로이드 프로그래밍[JAVA Code] > Thread' 카테고리의 다른 글

Thread - AsyncTask  (0) 2019.12.06
Thread : 루퍼 를 이용한 message 보내기  (0) 2019.12.05
Thread : information  (0) 2019.12.05
Thread : 스레드 와 핸들러  (0) 2019.12.05