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

编程入门 行业动态 更新时间:2024-10-23 12:24:51
本文介绍了如何共享活动/服务之间的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是什么在我的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.

更多推荐

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

本文发布于:2023-08-01 12:28:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268339.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!