如何在特定时间后将应用程序发送到后台

时间:2012-01-26 12:07:25

标签: java android android-intent alarmmanager

我使用以下代码来最小化我的应用

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

但现在我希望在特定时间后尽量减少我的应用。我的意思是我的应用程序应该在40-60秒等后自动最小化。我试图通过AlarmManager实现这一点,但它无法正常工作。

如何将活动发送到后台?

1 个答案:

答案 0 :(得分:0)

将以下代码放在MainActivity.java中

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                test();
            }
        });
    }              
}, 0, 20000);

以上代码将在20秒后调用test()函数。现在编写以下函数...

public void test()
{ 
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}

希望这会有所帮助。