如何共享活动/服务之间的资源 [英] How to share resources between activities/services

查看:140
本文介绍了如何共享活动/服务之间的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是什么在我的Andr​​oid应用程序共享单身的最佳方法。
我有一个不依赖于对方的一些活动,但我希望他们有一个单身,他们都可以读/写。

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.

这篇关于如何共享活动/服务之间的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆