현재 다음을 사용하여 AnroidWear에 바이트를 전달하고 있습니다.
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
mGoogleApiClient, node.getId(), path, text.getBytes() ).await();
적절한 데이터 번들을 웨어러블에 보내고 싶습니다. 어떻게해야합니까?
번들을 바이트로 변환하고 수신자에서 바이트를 번들로 변환합니다.
이 간단한 방법을 사용하면 String Bundle 값만 보낼 수 있습니다 .
(그리고 GSON 및 BundleTypeAdapterFactory를 사용하여 Bundle을 String으로 변환 할 수있는 것 같지만 테스트되지 않았습니다.)
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;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다