我想知道是什么在我的Android应用程序共享单身的最佳方法。我有一个不依赖于对方的一些活动,但我希望他们有一个单身,他们都可以读/写。
I wanted to know what is the best approach for sharing singleton in my android app. I have a few activities that does not rely on each other, but I want them to have a singleton that they can all read/write.
放在哪里呢?
感谢
推荐答案您的应用程序应该是一个单例。它避免了与共享DATAS或模式等诸多问题。
Your application should be a singleton. It avoids many other problem related to sharing datas or models.
在您的manifest.xml:
In your 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>和Android:名称指的是这个类:
And your android:name refers to this class :
public class MyApp extends Application { //singleton, but use onCreate more than constructor to build shared resources. .... }//class,然后从任何活动中,你可以检索你的单做这个以获得共享资源:
And then, from within any activity, you can retrieve your singleton to get shared resources by doing this :
((MyApp)getApplicationContext()).getSharedResources()....或
MyApp.getInstance().getSharedResources()....有一个单一个应用程序在Android上通常的设计模式,它是非常有用的处理设备旋转(因为它往往会破坏活动并重新创建它们),因为它提供了一个稳定的实体应用程序生命周期内持续。
Having a singleton as a app is a usual design pattern in android, it is especially useful to handle device rotation (as it tends to destroy activities and recreate them) as it provides a stable entity to persist during app lifecycle.
更多推荐
如何共享活动/服务之间的资源
发布评论