我想听听关于使用以下方法从其他活动或服务中确定活动是否可见的其他意见:该方法是关于使用 static boolean
s 作为标志,其值取决于活动生命周期。我已经实施了这个解决方案,它似乎工作正常。但是我怀疑这是否是一个可靠的解决方案,因为据我了解,活动生命周期包含在该 Activity 类的实例中,但静态方法或字段适用于所有实例。对于活动,需要确定可见性状态,我使用了singleTask
启动模式,因此不应有多个实例。考虑到这一点,假设静态布尔值将 100% 代表我的活动的实际状态是否安全?
2 回答
Well, for sure you can use static boolean flags. However, if you have more options then true/false, I recommend to use enum
instead.
If your Application has more then 2 Activities, using booleans only leads to hard maintenance.
So for clear code use enum flags like:
public enum EActivityState{
UNKNOWN,
VISIBLE,
NOT_VISIBLE,
LAUNCHED,
// ....
}
After you can use:
private EActivityState mActivityState = EActivityState.UNKNOWN;
....
if(EActivityState.LAUNCHED == mActivityState ){
// do something
}
What you said is correct:
static methods or fields applies to all instances
Check out the Activity Lifecycle here: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
and make sure you set your flag correctly, then your solution should be just fine.