0

我想在android屏幕上定期顯示一個白色矩形;或更改背景顏色。例如,我希望屏幕顏色每隔500毫秒從黑色變爲白色,大約200毫秒,然後變回黑色。如何定期在Android活動中顯示矩形

這樣做的最好方法是什麼?我確實嘗試了一個asynctask,但得到一個錯誤,只有原始線程可以觸摸視圖。我有一個類似的asynctask,它聽起來是一個週期性的音調,並且工作正常。

SOLUTION:

與我通過創建兩個定時器一個黑人和一個白人解決了我的問題的應答者的幫助。黑色的開始延遲了我想要顯示白色屏幕的時間。兩者具有相同的執行率,因此顯示白色屏幕,然後在持續時間毫秒之後顯示黑色屏幕。例如,屏幕是黑色的,但每秒閃爍白色200毫秒。

@Override 
protected void onResume() { 
    super.onResume(); 

    mBlackTimer = new Timer(); 
    mBlackTimer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        view.setBackgroundColor(Color.parseColor("#000000")); 

       } 
      }); 
     } 
    }, duration, (long) (1000/visionPeriod)); 

    mWhiteTimer = new Timer(); 
    mWhiteTimer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        view.setBackgroundColor(Color.parseColor("#ffffff")); 
       } 
      }); 

     } 
    }, 0, (long) (1000/visionPeriod)); 
} 
+0

您可以從後臺訪問ui屬性,但必須先訪問ui線程,然後調用getActivity()。runOnUiThread();如果你想改變一些東西,並把等待邏輯放在那個線程之外 –

回答

0

AsyncTask主要用於執行後臺線程活動,如從遠程服務器下載數據。它運行在它自己的線程上,這就是爲什麼當從AsyncTask嘗試訪問任何活動視圖時,它會給出錯誤that only the original thread can touch the View

您可以將Timer類或AlarmManager類用於重複性任務。訪問我以前的answer

3

您可以使用定時器類這對重複間隔執行一些任務:

//Declare the timer 
Timer t = new Timer(); 

//Set the schedule function and rate 
t.scheduleAtFixedRate(new TimerTask() { 
    @Override 
    public void run() { 
     //Called each time when 1000 milliseconds (1 second) (the period parameter) 
    }  
}, 
//Set how long before to start calling the TimerTask (in milliseconds) 
0, 
//Set the amount of time between each execution (in milliseconds) 
1000); 
+0

我在run方法中用view.setBackgroundColor(Color.parseColor(「#FFFFFF」))試過了你的建議,但是得到的錯誤只有原始線程可以觸摸視圖。 – PerceptualRobotics

+0

你可以使用runonuithread訪問ui的東西。 – Meenal

0

創建一個定時器任務方法和TimerTask的內部,並給它700毫秒的週期持續時間顯示黑色的背景,然後創建用於顯示白色背景,後推遲其500毫秒

處理程序嘗試所有這一切都在uithread只有

不使用新的線程或的AsyncTask 這樣的:

mTimer = new Timer(); 
    mTtask = new TimerTask() { 
     public void run() { 
      //set your black background here 
      new Handler().postDelayed(new Runnable() { 

       @Override 
       public void run() { 
        // set your white background here 
       } 
      }, 500); 
     } 
    }; 
    mTimer.schedule(mTtask, 1, 700); 
+0

我已經把這段代碼放在onResume中,但得到這個錯誤「不能在沒有調用Looper.prepare()的線程中創建處理程序」。那是什麼意思? – PerceptualRobotics