2012-12-07 8 views
1

내 프로그램이 진정한 내 동안에 10 초를 기다리는 것이 원하는,하지만 그것은 내가 Thread.sleep(10000);를 사용하려고 작동하지 않습니다하지만 내가 할 수있는 방법 10 초시간 대기 - 안드로이드

while (true) { 
    for (int i = 0; i < 2; i++) { 
     for (int j = 0; j < 5; j++) { 
      if (matrixVacancy[i][j] == 1) { 
       completeParking(i, j, R.color.vaga_ocupada); 
      } else { 
       completeParking(i, j, R.color.cor_chao); 
      } 
     } 
    } 
    try { 
     Thread.sleep(10000); 
    } catch (InterruptedException ex) { 
    } 

    int a, b, c, d, e, f, g, h, i; 

    a = (int) (Math.random() * 2); // indice i 
    b = (int) (Math.random() * 5); // indice j 
    c = (int) (Math.random() * 2); // tem ou nao carro 

    d = (int) (Math.random() * 2); // indice i 
    e = (int) (Math.random() * 5); // indice j 
    f = (int) (Math.random() * 2); // tem ou nao carro 

    g = (int) (Math.random() * 2); // indice i 
    h = (int) (Math.random() * 5); // indice j 
    i = (int) (Math.random() * 2); // tem ou nao carro 

    matrixVacancy[a][b] = c; 
    matrixVacancy[d][e] = f; 
    matrixVacancy[g][h] = i; 
} 

아니다 ? 10 초를 기다리는 동안?

+2

정확히 언제 기능을 기다리시겠습니까? 좀 더 문맥하시기 바랍니다. – stealthjong

+0

정확히 어떻게했는지. 어떻게 작동하지 않는거야? 앱이 잠시 응답하지 않으면 Android에서 강제 종료하도록 제안합니다. 어쩌면 별도의 (UI가 아닌) 스레드에서 해당 루프를 실행해야합니까? – nullpotent

+1

https://developer.android.com/reference/android/os/CountDownTimer.html https://developer.android.com/reference/java/util/Timer.html –

답변

12

당신이 쓰려고하는 스레드에 달려 있습니다. 메서드를 별도의 스레드에 넣고 거기에서 메서드를 수행 할 수도 있습니다. 할

catch (InterruptedException ex) { 
     ex.printStackTrace(); 
    } 

확인 로그 캣 :

catch (InterruptedException ex) { 
    } 

에 : 앱이 정지되지 않습니다이 방법/수면

private class TimeoutOperation extends AsyncTask<String, Void, Void>{ 

    @Override 
    protected Void doInBackground(String... params) { 

     try { 
      Log.i(TAG, "Going to sleep"); 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     Log.i(TAG, "This is executed after 10 seconds and runs on the main thread"); 
     //Update your layout here 
     super.onPostExecute(result); 
    } 
} 

이 작업을 사용

new TimeoutOperation().execute(""); 
+0

내 함수 completeParking이 LinearLayout의 배경을 설정하고이 작업을 원래 스레드에서 수행해야하므로 다른 스레드에서 수행 할 수 없습니다. –

+0

override 메서드 onPostExecute (void 결과)는 기본/UI 스레드에서 실행됩니다! :)이 코드를 원래 스레드 클래스에 붙여 넣으면 선형 레이아웃에 액세스 할 수 있습니다. 작업을 실행하려면 다음을 사용해야합니다. new TimeoutOperation(). execute (""); – Oritm

+0

완벽한! 나는 onPostExecute에서 그것을 얻었다. 이제 작동 중입니다. 감사 –

0

처음에는 수면이 불려지는지 확인하기 위해 지점을 나눕니다. 둘째, InterruptException을 잡을 때 예외가 인쇄됩니다. 귀하의 수면이 정확하므로 누군가가 당신을 방해하거나 잠을 자지 못하는 이유가 없습니다.

0

변경을 실행하려면 수면이 방해 받고 있지 않은지 확인하십시오.

또한 Thread.sleep을 호출하기 전후에 몇 가지 Log 문을 넣어 경과 시간을 출력하십시오.

Logcat은 (는) 친구입니다. :)