将活动带到前台

4
我希望当计时器触发时,即使活动已暂停,也能将活动置于前台。
非常感谢。
以下是我的代码:
package cem.examples.wsAct;

import something....

public class main extends Activity {

TextView tvResult, tvCount;
Button btn;
Timer timer;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

// setviews ....
// (find on the layout and bind them to the fields)

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
         // bring activity to front
                    f_UpdateUI(); 
                }
            });
        }

    }, 1000, 3000);
}

void f_UpdateUI() {
    String result = f_RetrieveFromWebService();

    // ??? Code... ???
    // If the activity is sended to back (how can I get it's state?)
    // Bring the activity even if it is paused or stopped (here is the lost part)
}

private String f_RetrieveFromWebService() {
// connect to web service and return string
    return "ta ta taaaaa";
}

}

我认为这是不可能的,而且有很好的理由,因为当某些活动没有预期时,它会变得相当烦人。 - Noel
@Noel 这可能有点烦人,但也是可以做到的 :-) - David Wasser
2个回答

2

你不能使用 AlarmManager 吗?从我看到的来看,你需要它在你的应用程序暂停后甚至是销毁后仍然运行。

如果你不需要它,那么你可以尝试使用一些可用的标志通过 startActivity 生成相同的活动。我不清楚你真正需要什么,以及何时需要,因此请尝试查看以下标志:FLAG_ACTIVITY_REORDER_TO_FRONTFLAG_ACTIVITY_SINGLE_TOPFLAG_ACTIVITY_CLEAR_TOP... 你是否阅读了所有标志?我相信其中一个(或一组)将实现你想要的功能。


0

要将您的Activity带到前台,您需要执行以下操作:

Intent intent = new Intent(context, MyRootActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

MyRootActivity 必须是您的应用程序的根 Activity(具有 ACTION=MAIN 和 CATEGORY=DEFAULT)。

重要的是,您必须从非 Activity 上下文中执行此操作。这意味着您需要从 BroadcastReceiverService 中执行此操作。

另请参见 此答案和有趣的评论线程


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接