Konvertieren Sie Ihr Bundle in Bytes und am Empfänger, konvertieren Sie Bytes in Bundle.
Mit dieser einfachen Methode können Sie nur senden String Bundle-Werte.
(und, wie es scheint, dass Sie auch Bundle zu String mit Gson und BundleTypeAdapterFactory umwandeln kann, aber ich bin nicht getestet.)
public void example() {
// Value
Bundle inBundle = new Bundle();
inBundle.putString("key1", "value");
inBundle.putInt("key2", 1); // will be failed
inBundle.putFloat("key3", 0.5f); // will be failed
inBundle.putString("key4", "this is key4");
// From Bundle to bytes
byte[] inBytes = bundleToBytes(inBundle);
// From bytes to Bundle
Bundle outBundle = jsonStringToBundle(new String(inBytes));
// Check values
String value1 = outBundle.getString("key1"); // good
int value2 = outBundle.getInt("key2"); // fail
float value3 = outBundle.getFloat("key3"); // fail
String value4 = outBundle.getString("key4"); // good
}
private byte[] bundleToBytes(Bundle inBundle) {
JSONObject json = new JSONObject();
Set<String> keys = inBundle.keySet();
for (String key : keys) {
try {
json.put(key, inBundle.get(key));
} catch (JSONException e) {
//Handle exception here
}
}
return json.toString().getBytes();
}
public static Bundle jsonStringToBundle(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
return jsonToBundle(jsonObject);
} catch (JSONException ignored) {
}
return null;
}
public static Bundle jsonToBundle(JSONObject jsonObject) throws JSONException {
Bundle bundle = new Bundle();
Iterator iter = jsonObject.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = jsonObject.getString(key);
bundle.putString(key, value);
}
return bundle;
}
funktioniert perfekt. Vielen Dank. – DivisionSi