gpt4 book ai didi

java - 如何在一定数量的不活动后关闭窗口/Activity

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:27 26 4
gpt4 key购买 nike

我正在为 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。如果我需要提供更多信息,请询问并感谢您的帮助...你们太棒了!

最佳答案

根据@CommonsWare 的建议,切换到处理程序。完美运行。非常感谢!

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);
}
};

关于java - 如何在一定数量的不活动后关闭窗口/Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4988222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com