如何将Bundle转换为PersistableBundle? [英] How can I convert a Bundle to a PersistableBundle?
本文介绍了如何将Bundle转换为PersistableBundle?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
API21发布了 PersistableBundle
,这是系统出于各种目的保留的捆绑包( JobScheduler
工作, ShortcutInfo
s 等)。我想用一种简单的方法将旧代码中的 Bundle
转换为 PersistableBundle
的...我该怎么办?
API21 released the PersistableBundle
which is a bundle that the system retains for various purposes (JobScheduler
jobs, ShortcutInfo
s etc). I'd like an easy way to convert the Bundle
's that are present in my old code to PersistableBundle
's...how can I do it?
推荐答案
从API26开始,没有方法可以轻松地做到这一点,手动验证值是否兼容:
As of API26, there is no way exposed to easily do this, you have to manually verify that the values are compatible:
private boolean bundleCanBePersisted(final Bundle extras) {
if (extras == null) {
return true;
}
Set<String> keys = extras.keySet();
Iterator<String> it = keys.iterator();
boolean allExtrasPersistable = true;
while (it.hasNext()) {
String key = it.next();
boolean isPersistable = isPersistable(extras.get(key));
if (!isPersistable) {
LOGGER.warning("Non persistable value in bundle. " + bundleItemToString(key, extras));
}
allExtrasPersistable &= isPersistable;
}
return allExtrasPersistable;
}
/**
* These are all the values that can be put into a PersistableBundle.
*/
private boolean isPersistable(final Object o) {
return o == null
|| o instanceof PersistableBundle
|| o instanceof String
|| o instanceof String[]
|| o instanceof Boolean
|| o instanceof Boolean[]
|| o instanceof Double
|| o instanceof Double[]
|| o instanceof Integer
|| o instanceof Integer[]
|| o instanceof Long
|| o instanceof Long[];
}
private String bundleItemToString(final String key, final Bundle bundle) {
Object value = bundle.get(key);
Class<?> valueClazz = null;
if (value != null) {
valueClazz = value.getClass();
}
return String.format("[%s = %s (%s)]", key, value, valueClazz);
}
这篇关于如何将Bundle转换为PersistableBundle?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文