2014-11-24 97 views
1

所以我们正在做一个创建android应用程序的项目,我们已经完成了,但由于我们有一些时间,我想实现一些额外的东西。我想要实现的一件事情,但我似乎无法找到任何地方是如何让应用程序闲置一段时间后返回到主要活动。我打算让用户能够从设置中选择这个时间,但是我想知道如何让这个功能在任何其他事情之前先工作。所有帮助赞赏。空闲后返回mainActivity Android

回答

7

得到参考您可以做到这一点使用处理程序如下所示。

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(); 
} 
+0

您还可以使用的AsyncTask,虽然不是真的需要在这种情况下 – Arnab 2014-11-24 05:00:48

+0

@Arnab在AsyncTask会调用Thread.sleep(miliSeconds)吗? – SilentKiller 2014-11-24 05:06:27

+0

我已经使用了上面的代码,但由于某种原因,即使有用户交互,它仍然超时。我为超时值创建了一个60的全局整数,并在一分钟之后完成,它返回到主要活动。 – user2989280 2014-11-24 05:40:47

0

1]在您的设置中添加屏幕超时。

2]使用一个BroadcastReceiver来触发屏幕上& OFF situations.You将从here

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 
      } 

    } 
};