Android如何放置Map< V,T>意向 [英] Android How to put Map<V,T> in an intent
问题描述
我有一个Map
对象,我想将其放入启动Service
的意图:
I have a Map
object and I want to put it in an intent to start a Service
:
Map<Integer, String> modules = new HashMap<Integer, String>();
Intent downloadServiceIntent = new Intent(context.getApplicationContext(), DownloadService.class);
downloadServiceIntent.putExtra("EXTRA_MODULE", modules);
context.startService(downloadServiceIntent);
我想我可以将Map
分成两个数组(int[]
和String[]
),然后将它们放入意图中.例如:
I think I could break the Map
into two arrays (int[]
and String[]
), then put them in intent. For example:
int[] keys = new int[modules.size()];
String[] values = new String[modules.size()];
int i = 0;
for (Map.Entry<Integer, String> entry : modules.entrySet()) {
keys[i] = entry.getKey();
values[i] = entry.getValue();
i++;
}
downloadServiceIntent.putExtra("EXTRA_KEYS", keys);
downloadServiceIntent.putExtra("EXTRA_VALUES", values);
这是个好主意吗?有其他替代方法可以实现这一目标吗?
Is it a good idea? Is there any alternative ways to achieve this?
推荐答案
您可以将可序列化的代码作为额外的[1].以HashMap为例,它确实实现了可序列化的接口[2].因此,如果您将变量类型从Map更改为HashMap,则可以直接将地图作为多余的内容.
You can put a serializable as extra [1]. And HashMap for example does implement the serializable interface [2]. So if you change your variable type from Map to HashMap you can put your map directly as extra.
[1] https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
[1] http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.io.Serializable) [2] https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
这篇关于Android如何放置Map< V,T>意向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!