2

我在端口上有一个 UDP 套接字的活动。如果我按下 Home 按钮,活动将进入后台,将调用OnPause()OnStop()方法。现在我想在收到一些 UDP 数据包时恢复我的活动。阅读我理解的其他帖子我必须:

  1. 将活动声明为android:launchMode="singleTask"(或singleInstance
  2. 然后,当我想恢复活动时:
Intent intent = new Intent(this.getApplicationContext(), myActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

开始活动(意图);

这个解决方案对我不起作用。调用startActivity(intent)不会显示我在前台的活动,onResume()也不会被调用。

以下标志可以完成这项工作,但我不想清除任务并重新启动新任务。

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
4

1 回答 1

1

In order to bring your own task to the foreground, you need to call startActivity() on a non-Activity Context, for example:

getApplicationContext().startActivity(intent);

Also, you don't need to use any special launch mode (singleTask or singleInstance) for this to work.

This is an Android bug that was fixed in Android 4.4. Since this question is from 2014, I will assume that OP was seeing this problem.

See How to resume Android Activity programmatically from background and the comment thread.

于 2017-08-04T14:47:44.080 回答