所以我们正在做一个创建Android应用程序的项目,我们已经完成但是因为我们有一些时间,所以我想实现一些额外的东西。有一件事我想实现,但我似乎无法找到任何地方是如何让应用程序在闲置一段时间后返回主要活动。时间,我计划允许用户从设置中选择,但我想知道如何在此之前首先使用此功能。所有帮助表示赞赏。
答案 0 :(得分:9)
您可以使用此处所示的处理程序来实现此目的。
private Handler handler;
private Runnable runnable;
//call in onCreate
setAppIdleTimeout()
private void setAppIdleTimeout() {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
@Override
public void run() {
// Navigate to main activity
}
});
}
};
handler.postDelayed(runnable, timeoutValue * 1000);
}
//reset timer on user interaction and in onResume
public void resetAppIdleTimeout() {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, timeoutValue * 1000);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
resetAppIdleTimeout();
}
@Override
public void onUserInteraction() {
// TODO Auto-generated method stub
Log.i(TAG, "interacted");
resetAppIdleTimeout();
super.onUserInteraction();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
handler.removeCallbacks(runnable);
super.onDestroy();
}
答案 1 :(得分:1)
您可以尝试以下方式:
- > ScreenLight ON和OFF广播
BroadcastReceiver myScreenLightBroadcast = new BroadcastReceiver() {
// This will fire whenever Screen Light will be ON or OFF
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Screen Light is On so you can close your all Activity Except your MainActivity
// Or you can move user to MainActivity by starting a NewActivity or Restarting Application
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// this will call whenever your Screen will OFF
}
}
};
答案 2 :(得分:0)
1]在您的设置中添加屏幕超时。
2]使用BroadcastReceiver触发Screen ON&关闭情况。您将从here
获得参考