我有一个Map对象,我想把它放在一个意图开始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);
Run Code Online (Sandbox Code Playgroud)
我想我可以Map分成两个数组(int[]和String[]),然后将它们置于意图之中.例如:
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);
Run Code Online (Sandbox Code Playgroud)
这是个好主意吗?有没有其他方法可以实现这一目标?
你可以把序列化作为额外的[1].例如,HashMap实现了可序列化接口[2].因此,如果您将变量类型从Map更改为HashMap,则可以将地图直接添加为额外的.
[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
| 归档时间: |
|
| 查看次数: |
732 次 |
| 最近记录: |