在java中定义一个全局变量_java – 声明一个全局变量,或在每个类中声明多次

本文介绍了在Java中定义全局变量的几种方式,包括使用Singleton类、静态字段/方法以及WeakReferences的HashMap。同时,对于需要跨活动持久保存的数据,推荐使用Application Preferences、SQLite DB、Files或ContentProviders等数据存储方法。
摘要由CSDN通过智能技术生成

For sharing complex non-persistent user-defined objects for short

duration, the following approaches are recommended:

Singleton class

You can take advantage of the fact that your application components

run in the same process through the use of a singleton. This is a

class that is designed to have only one instance. It has a static

method with a name such as getInstance() that returns the instance;

the first time this method is called, it creates the global instance.

Because all callers get the same instance, they can use this as a

point of interaction. For example activity A may retrieve the instance

and call setValue(3); later activity B may retrieve the instance and

call getValue() to retrieve the last set value.

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.

Persistent Objects

Even while an application appears to continue running, the system may

choose to kill its process and restart it later. If you have data that

you need to persist from one activity invocation to the next, you need

to represent that data as state that gets saved by an activity when it

is informed that it might go away.

For sharing complex persistent user-defined objects, the following

approaches are recommended:

06002

If the shared data needs to be retained across points where the

application process can be killed, then place that data in persistent

storage like Application Preferences, SQLite DB, Files or

ContentProviders. Please refer to the Data Storage for further details

on how to use these components.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值