2011-02-14 52 views
4

我正在設計一款適用於Android的音樂播放器應用程序,該應用程序將具有彈出式控件。我目前正試圖讓這些控件在一段時間不活動後關閉,但似乎沒有一個明確記錄的方法。到目前爲止,我已經設法將以下解決方案拼湊在一起,使用本網站和其他網站的一些建議。如何在一定的閒置時間後關閉窗口/活動

private Timer originalTimer = new Timer(); 

@Override 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.playcontrols); 

    View exitButton = findViewById(R.id.controls_exit_pane); 
    exitButton.setOnClickListener(this); 
    View volUpButton = findViewById(R.id.controls_vol_up); 
    volUpButton.setOnClickListener(this); 
    View playButton = findViewById(R.id.controls_play); 
    playButton.setOnClickListener(this); 
    View volDownButton = findViewById(R.id.controls_vol_down); 
    volDownButton.setOnClickListener(this); 

    musicPlayback(); 

    originalTimer.schedule(closeWindow, 5*1000); //Closes activity after 10 seconds of inactivity 

} 

和代碼應該關閉該窗口

//Closes activity after 10 seconds of inactivity 
public void onUserInteraction(){ 
    closeWindow.cancel(); //not sure if this is required? 
    originalTimer.cancel(); 
    originalTimer.schedule(closeWindow, 5*1000); 
} 

private TimerTask closeWindow = new TimerTask() { 

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

上面的代碼讓我感覺良好,但力時關閉任何用戶交互。但是,如果不改動,它會正常關閉,如果我刪除了第二個時間表,則不會在關聯後關閉,所以這似乎是問題所在。另外請注意,我想我會將此計時任務移至另一個線程以幫助保持UI快速。我需要先讓它工作:D。如果有任何更多的信息,我需要提供,請問和感謝您的幫助...你們都很棒!

+0

在Eclipse中使用`adb logcat`,DDMS或DDMS透視圖來檢查LogCat並查看與「強制關閉」相關的堆棧跟蹤。 – CommonsWare 2011-02-14 02:04:05

回答

11

基於@ CommonsWare的建議,切換到Handler。完美的作品。非常感謝!

private final int delayTime = 3000; 
private Handler myHandler = new Handler(); 

@Override 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.playcontrols); 

    View exitButton = findViewById(R.id.controls_exit_pane); 
    exitButton.setOnClickListener(this); 
    View volUpButton = findViewById(R.id.controls_vol_up); 
    volUpButton.setOnClickListener(this); 
    View playButton = findViewById(R.id.controls_play); 
    playButton.setOnClickListener(this); 
    View volDownButton = findViewById(R.id.controls_vol_down); 
    volDownButton.setOnClickListener(this); 

    musicPlayback(); 

    myHandler.postDelayed(closeControls, delayTime); 

} 

和其他方法...

//Closes activity after 10 seconds of inactivity 
public void onUserInteraction(){ 
    myHandler.removeCallbacks(closeControls); 
    myHandler.postDelayed(closeControls, delayTime); 
} 

private Runnable closeControls = new Runnable() { 
    public void run() { 
     finish(); 
     overridePendingTransition(R.anim.fadein, R.anim.fadeout); 
    } 
}; 
0

要完成上面的回答,請注意Activity.onUserInteraction()是足夠只有當你在乎點擊。

http://developer.android.com/reference/android/app/Activity.html#onUserInteraction%28%29狀態的文檔:「請注意,這個回調將被調用的觸地降落的行動,開始觸摸手勢,但不得援引爲後面的觸摸感動,觸摸式的操作。」

實際實施證明,它確實忽略了平板電腦上的所有移動,這意味着在不釋放手指的情況下繪製時鐘不會被重置。另一方面,這也意味着時鐘不會太頻繁地重置,這限制了開銷。

相關問題