views:

126

answers:

4

If an Activity is a singleton in practice, I think I can gain some efficiency by declaring appropriate members "static", with zero risk. Yes?

A: 

No. The same Activity can be started multiple times in the same process. For example, you can try starting an Activity from itself, when clicking a button.

Felix
you can declare activity's property in manifest as singleInstance/singleTop/singleTask to ensure one instance only.
Ankit Jain
A: 

Yes, an Activity can be a "singleton" if you ensure that an instance of Activity A isn't started while another instance of Activity A is in the activity stack (an instance of Activity A could technically start another instance of itself).

Andy Zhang
That's basically saying an `Activity` is a singleton if you ensure it is one. That doesn't make it a singleton.
Felix
That's true, but the ultimate question is if it can be a singleton in practice, which it can be. So in all practicality, static members can be safely used if the developer maintains a maximum of 1 instance, even without a singleton design pattern. (Personally I prefer practicality over technicality, but both of our answers are valid :) )
Andy Zhang
Thanks Felix and Andy.. seems Ankit has this one :)
DJC
+3  A: 

The Android documentation says -

there's never more than one instance of a "singleTask" or "singleInstance" activity, so that instance is expected to handle all new intents.

This means you can use static members.

Besides, a standard or singleTop should have thread-safe static members only. Suppose the current activity stack is A-B-C-D. If the arriving intent is for an activity of type B which is in "standard" or "singleTop" mode. A new instance of B would be launched as (since B is not at the top of the stack), so the resulting stack would be A-B-C-D-B.

Ankit Jain
Tyvm Ankit! This will do it for me..
DJC
interesting -- I always wondered why sharing state via static fields doesn't work, sometimes a field would suddenly turn null. I didn't declare these fields volatile, is that the reason? But why? I thought there's only a single UI thread?
Matthias
+1  A: 

One thing please DO NOT use singleTask or singleInstance for this purpose. The activity launch flags are there to control how activity stacks behave. They have visible impact on the user interaction with your activity (making it non-standard). Those modes are intended to be used when you want that kind of user interaction, they should NOT be used to change the implementation details of your app.

hackbod
So, Activities should NOT use static members except where they would be appropriate in multi-instance operation...I'd hoped that "that kind of user interaction" would be made clear to me by the Android documentation (ref Ankit's post up top) but it seems I'm a bit thick.. guess I'll post a new question.
DJC