2017-07-18 36 views
8

API21發佈了PersistableBundle,它是系統爲各種目的而保留的包(JobScheduler jobs,ShortcutInfos等)。我想要一個簡單的方法來將舊代碼中存在的Bundle轉換爲PersistableBundle的...我該怎麼做?如何將一個Bundle轉換爲PersistableBundle?

+1

我想你會得到一個有限的空間爲你節省了什麼。無論如何,而不是地毯式轟炸去精確打擊,即保存重新啓動後需要恢復的東西,而不是別的。 ///'JobInfo.Builder.setExtras'只接受一個'PersistableBundle'。所以,如果你直接創建一個,你甚至不會觸摸普通的'Bundle',也沒有什麼可以轉換的。 –

+0

這不是問題的答案。 –

+1

這就是爲什麼它是一個評論。我只是確保你沒有解決一個人爲問題(一個不應該出現的問題)。 –

回答

3

由於API26的,沒有辦法接觸到很容易地做到這一點,你必須手動驗證這些值是兼容的:

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); 
} 
相關問題