我有一个 Map
对象,我想将它放在启动 Service
的 Intent 中:
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[]
),然后将它们放入 intent 中。例如:
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);
这是个好主意吗?有没有其他方法可以实现这一目标?
最佳答案
你可以把一个可序列化的作为额外的[1]。例如,HashMap 确实实现了可序列化接口(interface) [2]。因此,如果您将变量类型从 Map 更改为 HashMap,您可以将 map 直接作为 extra。
[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> 放入 Intent 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27265292/