Android 如何在活动/服务之间共享资源

Android 如何在活动/服务之间共享资源,android,Android,我想知道在我的android应用程序中分享单身的最佳方法是什么。 我有一些相互不依赖的活动,但我希望它们都有一个可以读/写的单例 我应该把它放在哪里 谢谢您的应用程序应该是单例的。它避免了与共享数据或模型相关的许多其他问题 在manifest.xml中: <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="false" android:

我想知道在我的android应用程序中分享单身的最佳方法是什么。 我有一些相互不依赖的活动,但我希望它们都有一个可以读/写的单例

我应该把它放在哪里


谢谢

您的应用程序应该是单例的。它避免了与共享数据或模型相关的许多其他问题

在manifest.xml中:

<application android:icon="@drawable/icon"
    android:label="@string/app_name" android:debuggable="false"
    android:name="<class of your application see below>" 
            android:launchMode="singleTop">
 ..... all activities/services/receivers/etc... as usual

</application>
然后,在任何活动中,您都可以通过以下操作检索您的单例以获取共享资源:

((MyApp)getApplicationContext()).getSharedResources()....


在android中,将单例作为应用程序是一种常见的设计模式,处理设备旋转(因为它往往会破坏活动并重新创建活动)特别有用,因为它提供了一个稳定的实体,可以在应用程序生命周期中持续存在。

我相信
android:launchMode=“singleTop”
没有必要,因为launchMode是,不
((MyApp)getApplicationContext()).getSharedResources()....
MyApp.getInstance().getSharedResources()....