2013-07-31 5 views
2

저는 사용자 정의 날짜 시간 문자열을 textView에 인쇄하는 매우 간단한 작업을 수행하고 있습니다. MainActivity 자체에서 실행 가능한 인터페이스를 구현하고 ThreadonCreate 메서드 끝에 만들었습니다. 내가 로그 캣의 시스템을 볼 수있는 에뮬레이터에서 실행하면 MainActivity에서 Runnable 구현하기

Thread thread = new Thread(this); 
thread.run(); 

는 실행 방법

public void run() { 

     while (true) { 
      try { 
       Thread.sleep(1000); 
       localTime.setText(LocalTime.getTime().format2445()); 
       System.out.println(LocalTime.getTime().format2445()); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 

    } 

입니다. 그러나 에뮬레이터는 약 5 초 후에 ANR을 표시합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까. 이 방법이 적합하지 않습니까? Async Task는 여기로가는 길입니까? 매 초마다 시계를 업데이트해야하므로 AsyncTask를 영원히 돌리는 것이 허용되는 패턴입니까?

+2

사용할 필요가

localTime.setText(LocalTime.getTime().format2445()); // update ui from thread is not possible 

DoctorDrive합니다. 'thread.start()'. – Raghunandan

+0

무엇을하려고합니까? 'CountDownTimer'를 구현합니까? – gunar

+0

또한'localTime'은'TextView'입니까? – gunar

답변

2

당신은

가있는 문서에서 인용 thread.start()

http://developer.android.com/reference/java/lang/Thread.html

를 시작해야 나쁜 방법 새 스레드에서 코드를 실행하는 두 가지 방법. Thread를 서브 클래스 화해 run() 메소드를 오버라이드 (override)하거나 새로운 Thread를 구축해, Runnable를 constructor에 건네 줄 수가 있습니다. 두 경우 모두 새 스레드를 실제로 실행하려면 start() 메서드를 호출해야합니다..

당신은 thread.run()로 전화를 걸고 있습니다. 당신은 또한 잠을 자고 있습니다. UI 스레드를 차단하면 안됩니다.

http://developer.android.com/training/articles/perf-anr.html

당신은 카운트 다운 타이머

http://developer.android.com/reference/android/os/CountDownTimer.html

Countdowntimer in minutes and seconds을 찾고 있습니다.

처리기 타이머 작업을 사용할 수도 있습니다. 타이머 작업을 사용하는 경우 UI 스레드에서 UI를 udate해야합니다.

Android Thread for a timer

편집 :이 발견하지 못했습니다. 그래서 위의 의견에서. 크레딧은 당신이 호출 할 필요가 runOnUiThread

runOnUiThread(new Runnable() //run on ui thread 
      { 
       public void run() 
       { 
       localTime.setText(LocalTime.getTime().format2445()); 

       } 
      }); 
+0

감사합니다 Raghunandan, :-) 나는 당신의 대답을 받아 들일 수 없다. 그러나 나는 7 분을 기다려야 만한다. 덕분에 다시 많이 – DevZer0

+0

@ DevZer0 아무런 문제가 포럼의 규칙을 appriciated. 몇 분 정도 기다려야합니다. – Raghunandan

2

다음과 같이 시도해보십시오.

new Thread(new Runnable() { 
public void run() { 
    Thread.sleep(1000); 
    localTime.setText(LocalTime.getTime().format2445()); 
    System.out.println(LocalTime.getTime().format2445()); 
} 
}).start(); 
2

아마 대신

thread.start는 새로운 스레드를 생성하고 새 스레드에서 코드를 실행() thread.run의) (thread.start 사용해야합니다.

thread.run는

3

내가 시계를 업데이트해야 새 스레드를 만들지 않습니다, 부모 스레드에서 코드를 실행하는 모든 초 그래서 허용 패턴 영원히 AsyncTask를 실행 을 갖는입니까?

아니요, 권장하지 않습니다. AsyncTask Documentation에 따르면, 이들은 단시간 동안 만 실행되어야합니다. 이 경우 TimerTimerTask을 사용하는 것이 좋습니다.

Timer timer; 

public void onStart() { 

    timer = new Timer(); 

    //this will update each second 
    timer.scheduleAtFixedRate(new UpdateTask(), 0,1000); 
} 

class UpdateTask extends TimerTask { 
    public void run() { 
     //update TextView 
    } 
} 

public void onStop(){ 

    timer.cancel(); 
} 
1

UI 스레드에서 절전 모드를 호출하기 때문입니다. UI 스레드에서 sleep을 호출하지 마십시오. 핸들러를 사용하여 UI 스레드에서 작업을 실행할 수 있습니다.

private static final Handler handler = new Handler(); 

@Override 
protected void onCreate(Bundle state) { 
    super.onCreate(state); 
    handler.postDelayed(textRunnable, 1000); 
} 

private final Runnable textRunnable = new Runnable() { 
    @Override 
    public void run() { 
     localTime.setText(LocalTime.getTime().format2445()); 
     System.out.println(LocalTime.getTime().format2445()); 
    } 
} 

아니면 작동 당신은 할 수 있지만

@Override 
protected void onCreate(Bundle state) { 
    super.onCreate(state); 
    new Thread() { 
     @Override 
     public void run() { 
      try { 
       Thread.sleep(1000); 
       System.out.println(LocalTime.getTime().format2445()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         localTime.setText(LocalTime.getTime().format2445()); 
        } 
       }); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }.start(); 
} 
관련 문제