我正在为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
}
Run Code Online (Sandbox Code Playgroud)
应该关闭窗口的代码
//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();
}
};
Run Code Online (Sandbox Code Playgroud)
上面的代码对我来说很有意义,但强制关闭任何用户交互.然而,如果我不移动,它会正常关闭,如果我删除第二个时间表,则不会在交互后关闭,所以这似乎是问题所在.另请注意,我想我会将此计时任务移动到另一个线程,以帮助保持UI的快节奏.我需要先让它工作:D.如果我需要提供更多信息,请询问并感谢您的帮助......你们真是太棒了!
ste*_*fin 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);
}
Run Code Online (Sandbox Code Playgroud)
和其他方法......
//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);
}
};
Run Code Online (Sandbox Code Playgroud)