【发布时间】:2012-01-18 07:11:24
【问题描述】:
我的应用上有一个带有图标的通用菜单。单击一个图标将启动一个活动。有没有办法知道一个活动是否已经在运行并阻止它多次启动(或从多个条目开始)?我也可以将处于 onPause 状态的 Activity 放在前面吗?
【问题讨论】:
-
我已经有一段时间没有进行 Android 开发了,但我很确定 Android 会启动您的
Activity的现有实例,而不是启动一个新实例。
我的应用上有一个带有图标的通用菜单。单击一个图标将启动一个活动。有没有办法知道一个活动是否已经在运行并阻止它多次启动(或从多个条目开始)?我也可以将处于 onPause 状态的 Activity 放在前面吗?
【问题讨论】:
Activity 的现有实例,而不是启动一个新实例。
使用这个:
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
在启动Activity时。
如果在传递给 Context.startActivity() 的 Intent 中设置,此标志将 导致启动的活动被带到其任务的前面 历史堆栈(如果它已经在运行)。
【讨论】:
在 Manifest 文件中的活动声明中,添加标签 android:launchMode="singleInstance"
【讨论】:
我通过执行以下操作使其完美运行。 在调用者活动或服务中(甚至来自另一个应用程序)
Intent launchIntent = getPackageManager().getLaunchIntentForPackage(APP_PACKAGE_NAME);
//the previous line can be replaced by the normal Intent that has the activity name Intent launchIntent = new Intent(ActivityA.this, ActivityB.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
并在接收器活动的清单中(我想防止打开两次)
<activity android:name=".MainActivity"
android:launchMode="singleTask"
>
【讨论】:
将此添加到您在Androidmanifest.xml 中的Activity 定义...
android:launchMode = "singleInstance"
【讨论】:
这对我有用:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
如果设置,并且正在启动的活动已经在 当前任务,而不是启动该任务的新实例 活动,其之上的所有其他活动都将关闭,并且 此 Intent 将作为 新意图。
另外,你可以使用FLAG_ACTIVITY_NEW_TASK。
那么代码将是:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
【讨论】:
随便用
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
【讨论】:
创建一个你不想多次启动的活动实例
Class ExampleA extends Activity {
public static Activity classAinstance = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
classAinstance = this;
}
}
现在你想在哪里交叉检查我的意思是防止它多次启动,像这样检查
if(ExampleA.classAinstance == null) {
"Then only start your activity"
}
【讨论】:
请将此添加到清单文件中
<activity
android:name=".ui.modules.profile.activity.EditProfileActivity"
android:launchMode="singleTask" // <<this is Important line
/>
【讨论】: