吐槽:以前做iOS的,从没想过控制器传个对象又是Serializable又是Parcelable的,晕死😵。自己封装了, 可传递任意对象,不需要序列化。
一、调用示例:
1、传入
ObjectIntent.putObjectExtra(intent, "sdkParams", sdkParams);
2、 读取
ObjectIntent.getObjectExtra(getIntent(), "sdkParams");
3、清除
因为是全局的,防止内存泄漏,需要清理下。
- 最后一个getObjectExtra,clearAll传true
ObjectIntent.getObjectExtra(getIntent(), "sdkParams", true);
- 或者:
ObjectIntent.clear(getIntent());
二、ObjectIntent类
public class ObjectIntent extends Intent {
private static String INTENT_ID = "INTENT-ID-TAIWAN-BELONGS-TO-CHINA";
private static Map<String, Map<String, Object>> objectExtras = new ConcurrentHashMap<>();
public static void putObjectExtra(Intent intent, String name, Object value) {
String intentId = intent.getStringExtra(INTENT_ID);
if (intentId == null || "".equals(intentId)) {
intentId = uniqueUUID();
//创建extra容器
Map<String, Object> extras = new HashMap<>();
objectExtras.put(intentId, extras);
//在intent中记录容器id
intent.putExtra(INTENT_ID, intentId);
}
Map<String, Object> intentContainer = objectExtras.get(intentId);
intentContainer.put(name, value);
}
@SuppressWarnings(value = {"unchecked"})
public static <T> T getObjectExtra(Intent intent, String name) {
try {
Map<String, T> extras = getObjectExtras(intent);
return extras.get(name);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T> T getObjectExtra(Intent intent, String name, boolean clearAll) {
try {
Map<String, T> extras = getObjectExtras(intent);
if (clearAll) {
clear(intent);
}
return extras.get(name);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void clear(Intent intent) {
objectExtras.remove(intent.getStringExtra(INTENT_ID));
}
@SuppressWarnings(value = {"unchecked"})
public static <T> Map<String, T> getObjectExtras(Intent intent) {
try {
String intentId = intent.getStringExtra(INTENT_ID);
Map<String, T> extras = (Map<String, T>) objectExtras.get(intentId);
return extras;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String uniqueUUID(){
String uuid = null;
while (uuid == null || objectExtras.containsKey(uuid)) {
uuid = UUID.randomUUID().toString().replaceAll("-", "");
}
return uuid;
}
}