Right way way to implement Singleton in Android for data Sharing between activities? [closed]

懵懂的女人 提交于 2019-12-06 09:58:54

问题


I have been struggling with this issue for a long long time, actually I've checked a lot of post in stackoverflow talking about the same but nothing definitive.

How to implement the Singleton pattern to achieve data sharing between Android activities? I am talking between activities, not classes, which one is the right way?

This is all the info I found:

1- The ones who recommend the standard Singleton form, the one that you might implement in Java, C, etc, here you got an example:

http://es.wikipedia.org/wiki/Singleton

2- The ones that suggest to implement it in the OnCreate method, like this:

http://androidcookbook.com/Recipe.seam?recipeId=1218

3- The ones that uses the Application implementation approach (not so sure about this one):

Is it acceptable practice to use Singleton Objects to save state or share data between Activities?

4- The ones that uses the "singleTask" approach, defining it in the manifest:

http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

5- And more exoteric ways like this one (Actually this is not a Singleton I think):

http://www.jameselsey.co.uk/blogs/techblog/android-implementing-global-state-share-data-between-activities-and-across-your-application/

Suggestions? Comments? Examples?

Google Android people recommends it as one way to share complex information between activities, but no clue about the best approach in Android.

http://developer.android.com/guide/faq/framework.html#3

Please help me to clarify this.


回答1:


I've used both the Application to hold a "Singleton" instance as well as a static final variable. In the framework I work on, Transfuse, Singletons are scoped via the @Singleton annotation. These hold the given singleton in a static final map:

@Singleton
public class SingletonExample{
    ...
}

http://androidtransfuse.org/documentation.html#singleton

And this is the map that holds the given singleton instance:

public class ConcurrentDoubleLockingScope implements Scope {

    private final ConcurrentMap<Class, Object> singletonMap = new ConcurrentHashMap<Class, Object>();

    @Override
    public <T> T getScopedObject(Class<T> clazz, Provider<T> provider) {
        Object result = singletonMap.get(clazz);
        if (result == null) {
            Object value = provider.get();
            result = singletonMap.putIfAbsent(clazz, value);
            if (result == null) {
                result = value;
            }
        }

        return (T) result;
    }
}


来源:https://stackoverflow.com/questions/15164144/right-way-way-to-implement-singleton-in-android-for-data-sharing-between-activit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!