我正在設計一款適用於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。如果有任何更多的信息,我需要提供,請問和感謝您的幫助...你們都很棒!
在Eclipse中使用`adb logcat`,DDMS或DDMS透視圖來檢查LogCat並查看與「強制關閉」相關的堆棧跟蹤。 – CommonsWare 2011-02-14 02:04:05