Singletons and Services and Shutdowns Oh My

本文探讨了Android应用中数据传递的方法,特别是如何通过Singleton模式跨活动和服务共享数据。介绍了使用Intent、SharedPreferences、Application类、静态字段等方法,并强调了考虑Android生命周期的重要性。

Passing data back and forth between activities on the Android platform is one of the more challenging aspects of understanding Android. Understanding how this data is managed by the OS is the difference between getting flooded with Error Reports and bad reviews and getting  glowing praise and eternal gratitude. Well maybe not to that extent, but having a good background in passing data can make your code much easier to manage and cleaner to read (and for that you have my gratitude) So in passing the data there are essentially two types Persistent and strangely enough, Non-Persistent data types. The Persistent types are best handled by preferences, files, databases or content providers and they are pretty detailed in their operation. If you need to keep data over the length of more that one session consider using Persistent data stores. On the other hand, there are often times where transient data needs to be stored for one session and passed between activities. To handle that there are a couple of ways to handle it. This page details some of the methods, and it is repeated here for convenience;

How do I pass data between Activities/Services within a single application?

It depends on the type of data that you want to share:

Primitive Data Types

To share primitive data between Activities/Services in an application, use Intent.putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism.

Non-Persistent Objects

For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:

The android.app.Application class

The android.app.Application is a base class for those who need to maintain global application state. It can be accessed via getApplication() from any Activity or Service. It has a couple of life-cycle methods and will be instantiated by Android automatically if your register it in AndroidManifest.xml.

A public static field/method

An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.

A HashMap of WeakReferences to Objects

You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key.

A Singleton class

There are advantages to using a static Singleton, such as you can refer to them without casting getApplication() to an application-specific class, or going to the trouble of hanging an interface on all your Application subclasses so that your various modules can refer to that interface instead. But, the life cycle of a static is not well under your control; so to abide by the life-cycle model, the application class should initiate and tear down these static objects in the onCreate() and onTerminate() methods of the Application Class [my emphasis]

Being as I come from a java EE background the first decision was to use the singleton class and allow the instance to be available across the VM. The singleton design pattern is fairly well-known and is a good easy way to manage control across many activities. In some previous projects I have used them to manage HTTP connections, image caching and global application configuration to much success. However, this is the important part to consider when using singletons which is very important; Android OS can and will terminate your singleton and not even tell you about it. I highlighted that in bold because if your design depends on singleton patterns you naturally assume they are going to stay persistent through the VM. These are frustrating errors and difficult to track down and even more frustrating for your users. For instance consider this piece of code: In your main activity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SuperSingletonManager.create(this);
}

And your singleton;

private static SuperSingletonManager instance;
private SuperSingletonManager(Context context)
{
// do stuff once
}
protected static SuperSingletonManager create(Context context) {
instance = new SuperSingletonManager(context);
}
protected static SuperSingletonManager getInstance() {
if (instance == null)
throw new NastyException(“Oh God Why?”);
return instance;
}

Seemingly you should be able to call  SuperSingletonManager.getInstance() at any time and get access to the static instance. However, this isn’t the case. If the launching  activity is removed by the OS (it happens, a lot) while you are on another activity, that static instance will be gone. So when you make that  SuperSingletonManager getInstance() call you are only going to get a nasty exception. This also means that if any of your functions in SuperSingletonManager make use of the Context those will throw errors. Ack. But I really, really like singletons. So do I. And far be it from me to tell you how to architect your code. The only stipulation is that the singleton should abide by the lifecycle model. We can do this by launching the singletons from a service and binding that service to the launching activity. To the Android purists, and common-sensists out there you might just say “Why not just use a service instead of a singleton?”.  Sure, makes sense but this post is about singletons and how to get them working and not common-sense. So here is the class that will do all that;

public class SingletonService extends Service {

private final ISingletonService.Stub mBinder = new ISingletonService.Stub() {

public void startSingletons() throws RemoteException {

initializeSingletons();

}

public void stopSingletons() throws RemoteException {

shutdownSingletons();

}

};

public IBinder onBind(Intent intent) {

return mBinder;

}

protected void initializeSingletons() {

SuperSingletonManager.initialize(getApplicationContext());

}

private void shutdownSingletons() {

SuperSingletonManager.shutdown();

}

}

When you start your main activity bind the service using bindService() , and make a call to the startSingletons() method. This will launch your singletons under the lifecycle of the service. This will ensure they are active for the life of your application session. Also, make sure to unbindService when you are finished. Nobody likes developers that don’t clean up after themselves. Good luck and if you actually use this method let me know! John

Posted via email from John Carpenter

http://www.2linessoftware.com/2010/08/03/singletons-and-services-and-shutdowns-oh-my/

posted on 2013-01-31 01:15 罗斯摩根 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/savagemorgan/archive/2013/01/31/2883888.html

内容概要:本文详细介绍了一个基于Java和Vue的联邦学习隐私保护推荐系统的设计与实现。系统采用联邦学习架构,使用户数据在本地完成模型训练,仅上传加密后的模型参数或梯度,通过中心服务器进行联邦平均聚合,从而实现数据隐私保护与协同建模的双重目标。项目涵盖完整的系统架构设计,包括本地模型训练、中心参数聚合、安全通信、前后端解耦、推荐算法插件化等模块,并结合差分隐私与同态加密等技术强化安全性。同时,系统通过Vue前端实现用户行为采集与个性化推荐展示,Java后端支撑高并发服务与日志处理,形成“本地训练—参数上传—全局聚合—模型下发—个性化微调”的完整闭环。文中还提供了关键模块的代码示例,如特征提取、模型聚合、加密上传等,增强了项目的可实施性与工程参考价值。 适合人群:具备一定Java和Vue开发基础,熟悉Spring Boot、RESTful API、分布式系统或机器学习相关技术,从事推荐系统、隐私计算或全栈开发方向的研发人员。 使用场景及目标:①学习联邦学习在推荐系统中的工程落地方法;②掌握隐私保护机制(如加密传输、差分隐私)与模型聚合技术的集成;③构建高安全、可扩展的分布式推荐系统原型;④实现前后端协同的个性化推荐闭环系统。 阅读建议:建议结合代码示例深入理解联邦学习流程,重点关注本地训练与全局聚合的协同逻辑,同时可基于项目架构进行算法替换与功能扩展,适用于科研验证与工业级系统原型开发。
源码来自:https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
### 关于 Vasya 和多重集的编程竞赛算法题目解决方案 #### 题目描述 给定一个多重集合 `s`,目标是将其分割成两个新的多重集合 `a` 和 `b` (其中一个可以为空),使得这两个新集合中的“好数”的数量相等。“好数”定义为在一个特定多集中恰好只出现一次的数字。 为了实现这一目标,需要考虑如何有效地统计并分配这些元素到不同的子集中去[^1]。 #### 解决思路 一种有效的解决方法是从输入数据的特点出发思考。如果某个数值在整个原始集合中出现了偶数次,则该值可以在不影响最终结果的情况下被平均分入两个子集中;而对于那些仅出现奇数次数的情况,则必须小心处理以确保能够达成平衡条件——即让尽可能多的不同类型的单例项分别进入各自的目标组内[^2]。 具体来说: - 对于任何频率大于等于两次(无论是奇还是偶)的数据点而言,总是能通过适当划分来满足上述要求; - 当遇到频度为一的情形时,就需要额外注意了:因为这直接影响着能否成功创建具有相同数目唯一成员的新分区。 因此,在实际编码过程中应该优先处理那些重复率较高的项目,并记录下所有独一无二实例的位置以便后续操作使用。 #### Python 实现代码示例 下面是一个基于此逻辑编写的Python函数,用于求解这个问题: ```python from collections import Counter def can_split_equally(s): count = Counter(s) # 统计各元素出现次数 singletons = sum(1 for v in count.values() if v == 1) return singletons % 2 == 0 # 测试用例 test_cases = [ [1, 2, 2, 3], # True 可以分成 {1} 和 {2, 2, 3} [1, 2, 3, 4, 5], # False 单独存在的数字有五个无法平分 ] for case in test_cases: print(f"Input: {case}, Can Split Equally? :{can_split_equally(case)}") ``` 这个程序首先利用 `collections.Counter` 来计算每个整数在列表里边出现过的总次数。接着它会遍历所有的键值对,累积起所有只出现过一次(也就是所谓的 “好数” 或者说是单一实例)的数量。最后一步就是判断这样的特殊案例是不是构成了一个偶数序列长度 —— 如果是的话就意味着存在至少一组可行解;反之则不存在这样的一分为二方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值