Android的 - 什么是共享活动之间数据的最佳方式是什么? [英] Android - What's the best way to share data between activities?

查看:141
本文介绍了Android的 - 什么是共享活动之间数据的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动是在整个该应用中使用的主要的活性,它有一个号码的变量。我有2个,我希望能够从第一个活动使用的数据等活动。 现在我知道我可以做这样的事情:

I have one activity which is the main activity used throughout the app and it has a number of variables. I have 2 other activities which I would like to be able to use the data from the first activity. Now I know I can do something like this:

GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

不过,我想分享的变量很多,有的可能是相当大的,所以我不希望被创建它们的副本如上。因此,有没有办法直接获取和更改,恕不使用GET变量和设置方法,因为我记得看过一篇文章,对谷歌开发的网站说这是不建议在Android上的表现。

However I want to share alot of variables and some might be rather large so I don't want to be creating copies of them like above. Therefore is there a way to directly get and change the variables without using get and set methods as I remember reading an article on the google dev site saying this is not recommended for performance on android.

因此​​,如果任何人有任何意见或知道一个更好的办法,我会AP preciate吧。

So if anyone has any ideas or knows a better way I would appreciate it.

推荐答案

下面一个最常见的方法为实现这一:

  • 发送内部意图数据
  • 使用单个类
  • 使用应用单
  • 静态字段
  • 在WeakReferences
  • 的HashMap中
  • 坚持对象(源码,每股preferences,文件等)
  • Send data inside intent
  • Use a singleton class
  • Use application singleton
  • Static fields
  • HashMap of WeakReferences
  • Persist objects (sqlite, share preferences, file, etc.)

TL; DR :有共享数据的方式有两种:传递数据的意图的额外或保存到其他地方。如果数据是原语,字符串或用户定义的对象:它作为额外的意图的一部分发送(用户定义的对象必须实现 Parcelable )。如果通过复杂的对象保存一个实例在一个单身别的地方,从启动的活动访问它们。

TL;DR: there are two ways of sharing data: passing data in the intent's extras or saving it somewhere else. If data is primitives, Strings or user-defined objects: send it as part of the intent extras (user-defined objects must implement Parcelable). If passing complex objects save an instance in a singleton somewhere else and access them from the launched activity.

如何以及为什么要实现每个方法的一些例子:

Some examples of how and why to implement each approach:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);

在第二个活动:

Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");

使用这种方法的如果您通过原始数据或字符串。您也可以通过对象实现序列化

Use this method if you are passing primitive data or Strings. You can also pass objects that implements Serializable.

虽然诱人,你应该三思而后使用序列化之前:这是容易出错和异常缓慢。所以一般:远离序列化 如果可能的话。如果你想通过复杂的用户定义的对象,看看的 Parcelable 接口。这是很难实现的,但它相对于序列化

Although tempting, you should think twice before using Serializable: it's error prone and horribly slow. So in general: stay away from Serializable if possible. If you want to pass complex user-defined objects, take a look at the Parcelable interface. It's harder to implement, but it has considerable speed gains compared to Serializable.

有可能通过将其保存在存储器中给出的是,在大多数情况下,这两种活动在同一进程中运行共享活动之间的内容

It is possible to share data between activities by saving it in memory given that, in most cases, both activities run in the same process.

注意:有时候,当用户离开你的活动时(不退出的话),机器人可以决定要杀死你的应用程序。在这种情况下,我所经历的情况,即机器人将尝试使用所提供的应用程序被打死之前的意图发动最后一次活动。在这种情况下,存储在一个单独的数据(无论是你还是应用程序)将消失,不好的事情都可能发生。为了避免这种情况下,你要么坚持对象到磁盘或用它来确保其有效之前检查数据。

Note: sometimes, when the user leaves your activity (without quitting it), Android may decide to kill your application. In such scenario, I have experienced cases in which android attempts to launch the last activity using the intent provided before the app was killed. In this cases, data stored in a singleton (either yours or Application) will be gone and bad things could happen. To avoid such cases, you either persist objects to disk or check data before using it to make sure its valid.

有一个类来整个数据:

public class DataHolder {
  private String data;
  public String getData() {return data;}
  public void setData(String data) {this.data = data;}

  private static final DataHolder holder = new DataHolder();
  public static DataHolder getInstance() {return holder;}
}

从启动的活动:

From the launched activity:

String data = DataHolder.getInstance().getData();

使用应用单

申请单是 android.app.Application 当应用程序被启动,它会创建一个实例。您可以通过扩展提供了一个自定义的应用程序

Use application singleton

The application singleton is an instance of android.app.Application which is created when the app is launched. You can provide a custom one by extending Application:

import android.app.Application;
public class MyApplication extends Application {
  private String data;
  public String getData() {return data;}
  public void setData(String data) {this.data = data;}
}

在开展活动:

MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);

然后,从启动的活动:

Then, from the launched activity:

MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();

静态字段

的想法基本上是比单,但在这种情况下,你提供静态访问数据:

Static fields

The idea is basically the than the singleton, but in this case you provide static access to the data:

public class DataHolder {
  private static String data;
  public static String getData() {return data;}
  public static String setData(String data) {this.data = data;}
}

从启动的活动:

From the launched activity:

String data = DataHolder.getData();

在WeakReferences

的HashMap

同样的想法,但允许垃圾收集器删除未引用的对象(例如,当用户退出活动):

HashMap of WeakReferences

Same idea, but allowing the garbage collector to removed unreferenced objects (e.g. when the user quits the activity):

public class DataHolder {
  Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();

  void save(String id, Object object) {
    data.put(id, new WeakReference<Object>(object));
  }

  Object retrieve(String id) {
    WeakReference<Object> objectWeakReference = data.get(id);
    return objectWeakReference.get();
  }
}

在开展活动:

DataHolder.getInstance().save(someId, someObject);

从启动的活动:

From the launched activity:

DataHolder.getInstance().retrieve(someId);

您可能会或可能不会有通过使用意图的额外的对象ID。这一切都取决于你的具体问题。

You may or may not have to pass the object id using the intent’s extras. It all depends on your specific problem.

的想法是在启动其他活动之前保存在磁盘上的数据。

The idea is to save the data in disk before launching the other activity.

优势:您可以从其他地方推出的活动,如果该数据已经坚持着,这应该只是罚款

Advantages: you can launch the activity from other places and, if the data is already persisted, it should work just fine.

缺点:这是繁琐,需要花费更多的时间来实施。需要更多的code和引入错误的。因此更多的机会。这也将是慢得多。

Disadvantages: it’s cumbersome and takes more time to implement. Requires more code and thus more chance of introducing bugs. It will also be much slower.

有些坚持目标的途径包括:

Some of the ways to persist objects include:

  • Save them to the shared preferences
  • Save them to a sqlite database
  • Save them to a file (I’d avoid this one)

这篇关于Android的 - 什么是共享活动之间数据的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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