2011-02-14 21 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状态的文档:“请注意,这个回调将被调用的触地降落的行动,开始触摸手势,但不得援引为后面的触摸感动,触摸式的操作。”

实际实施证明,它确实忽略了平板电脑上的所有移动,这意味着在不释放手指的情况下绘制时钟不会被重置。另一方面,这也意味着时钟不会太频繁地重置,这限制了开销。

相关问题