2014-02-26 3 views
0

다음 코드는 두 개의 배열에서 문자열을 가져 와서 임의로 표시합니다. 이 프로그램에 TimerTask를 적용하여 배열의 문자열이 몇 초 후에 임의로 변경되도록하려면 어떻게해야합니까?TimerTask가 안드로이드에서 작동하지 않습니다

어떤 이유로 문자열 MainActivity

public class MainActivity extends Activity { 
    private TextSwitcher mSwitcher, mSwitcher1; 
    private int mCounter = 0; 
    String textToShow[]={"Main HeadLine","Your Message","New In Technology","New Articles","Business News","What IS New"}; 
    String textToShow1[]={"Main HeadLine","Your Message","New In Technology","New Articles","Business News","What IS New"}; 
    int messageCount=textToShow.length; 
    // to keep current Index of text 
    int currentIndex=-1; 


    public void schedule(TimerTask task,long delay,long period){ 
Timer timer = new Timer(); 
timer.schedule(new MyTimerTask(), 0, 1000); 
} 
    public class MyTimerTask extends TimerTask { 

     @Override 
     public void run() { 
      updateTextView(); 
     } 
    } 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.example_layout); 

    } 
       @Override 
     protected void onStart() { 
      super.onStart(); 
      updateTextView();  
     } 

     private void updateTextView() { 
      mSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher); 
      mSwitcher1 = (TextSwitcher) findViewById(R.id.textSwitcher01); 
      // BEGIN_INCLUDE(setup) 
      // Set the factory used to create TextViews to switch between. 
      mSwitcher.setFactory(mFactory); 
      mSwitcher1.setFactory(mFactory); 
      Random random = new Random(); 
      Animation in = AnimationUtils.loadAnimation(this, 
        android.R.anim.fade_in); 
      Animation out = AnimationUtils.loadAnimation(this, 
        android.R.anim.fade_out); 
      mSwitcher.setInAnimation(in); 
      mSwitcher1.setInAnimation(in); 
      mSwitcher.setOutAnimation(out); 
      mSwitcher1.setOutAnimation(out); 
      int maxIndex = textToShow.length; 
      int generatedIndex = random.nextInt(maxIndex); 
      mSwitcher.setText(textToShow[generatedIndex]); 
      mSwitcher1.setText(textToShow1[generatedIndex]); 
     } 


    private ViewFactory mFactory = new ViewFactory() { 

     @Override 
     public View makeView() { 

      // Create a new TextView 
      TextView t = new TextView(MainActivity.this); 
      t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); 
      t.setTextAppearance(MainActivity.this, android.R.style.TextAppearance_Large); 
      return t; 
     } 
    }; 
} 

것은

답변

0

전화를 runOnUiThread 내부 updateTextView(); 방법을 업데이트하지 않기 때문에 비 UI 스레드에서의 TimerTask 실행 방법 실행 :

public class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 
     MainActivity.this.runOnUiThread(new Runnable() { 

     @Override 
     public void run() { 
     updateTextView(); 
     } 
     }); 
    } 
} 
관련 문제