2010-09-06 7 views
0

J'utilise ce code:gestionnaire minuterie android

public class newtimer extends Activity { 

    private Timer myTimer; 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.main); 

     myTimer = new Timer(); 
     myTimer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       TimerMethod(); 
      } 

     }, 0, 1000); 
    } 

    int number = 0; 

    private void TimerMethod() 
    { 
     //This method is called directly by the timer 
     //and runs in the same thread as the timer. 

     //We call the method that will work with the UI 
     //through the runOnUiThread method. 

     Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show(); 

     this.runOnUiThread(Timer_Tick); 
    } 

    private Runnable Timer_Tick = new Runnable() { 
     public void run() { 

      //This method runs in the same thread as the UI. 
      //Do something to the UI thread here 

      Toast.makeText(getBaseContext(), "UI Thread Running "+number, Toast.LENGTH_SHORT).show(); 

     } 
    }; 
} 

Quand je le lance je reçois cette exception logcat:

09-06 21: 39: 39,701: ERREUR/AndroidRuntime (1433): java.lang.RuntimeException: Impossible de créer un gestionnaire à l'intérieur fil qui n'a pas appelé Looper.prepare()

+0

Ce code a été complètement mis en forme. S'il vous plaît regardez l'aperçu avant de poster une question. – EboMike

Répondre

0

Je suppose que le problème est avec le Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show(); dans votre fonction TimerMethod - vous ne peut pas appeler les fonctions relatives à l'interface utilisateur à partir des threads de travail. Puisque vous avez déjà un Toast dans la partie qui s'exécute dans le thread UI, pourquoi en avez-vous un autre dans TimerMethod? Pour le débogage, je recommande d'utiliser Log autant que possible au lieu de Toast.