Dan*_* L. 15 android android-lifecycle android-activity
我有一个由单个组成的Android应用程序Activity.我怎样才能确保Activity在给定时间内只存在一个应用程序实例(== )?我遇到了一种情况,我通过多次点击应用程序图标成功打开了我的应用程序的多个实例(这不会一直重现).
Foa*_*Guy 28
像这样改变你的清单:
<activity
android:name="com.yourpackage.YourActivity"
android:label="@string/app_name"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)
包括,android:launchMode="singleTask"并且不可能同时启动您的Activity的多个实例.有关更多信息,请参阅活动文档.
Hun*_*r S 13
接受的答案符合其目的,但这不是最好的方法.
相反,我建议AtomicInteger在每个活动中使用静态内容,如下所示:
//create a counter to count the number of instances of this activity
public static AtomicInteger activitiesLaunched = new AtomicInteger(0);
@Override
protected void onCreate(Bundle pSavedInstanceState) {
//if launching will create more than one
//instance of this activity, bail out
if (activitiesLaunched.incrementAndGet() > 1) { finish(); }
super.onCreate(pSavedInstanceState);
}
@Override
protected void onDestroy() {
//remove this activity from the counter
activitiesLaunched.getAndDecrement();
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)
声明应该使用该singleInstance模式启动您的活动会开始弄乱活动和任务的默认行为,这可能会产生一些不必要的影响.
在Android的文档时,建议使用有必要(这不是在这种情况下),你只能破坏这种行为:
警告:大多数应用程序不应该中断>活动和任务的默认行为.如果您确定您的活动需要修改默认行为,请谨慎使用并确保在启动期间以及使用"返回"按钮从其他活动和任务导航回活动时测试活动的可用性.请务必测试可能与用户预期行为冲突的导航行为.
| 归档时间: |
|
| 查看次数: |
15421 次 |
| 最近记录: |