【问题标题】:Bring activity to front itself将活动带到自己面前
【发布时间】:2011-06-19 22:42:53
【问题描述】:

即使活动暂停,我也想在计时器计时时将活动放在前面。

非常感谢..

我的代码如下:

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 这可能很烦人,但也有可能:-)

标签: android android-activity timer


【解决方案1】:

你不能用AlarmManager吗?就我所见,即使您的应用没有运行(在 onPause 之后,也可能在 onDestroy 之后),您也需要它运行。

如果您不需要它,那么您可以尝试使用startActivity 生成相同的活动并使用一些可用的标志。我不清楚您真正需要什么,何时需要,所以请尝试查看以下标志:FLAG_ACTIVITY_REORDER_TO_FRONT、FLAG_ACTIVITY_SINGLE_TOP、FLAG_ACTIVITY_CLEAR_TOP... 你读过all the flags 了吗?我确信其中一个(或一组)会做你想做的。

【讨论】:

    【解决方案2】:

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

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

    MyRootActivity 必须是您应用的根 Activity(ACTION=MAIN 和 CATEGORY=DEFAULT 的那个)。

    重要的是您必须从非活动上下文中执行此操作。这意味着您需要通过BroadcastReceiver 或Service 进行操作。

    另见this answer and the interesting comment thread

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多